Index: /branches/amp_3_7_0/src/webui/webui/htdocs/new/src/cm/models/system/user_mgmt/__init__.py
===================================================================
--- /branches/amp_3_7_0/src/webui/webui/htdocs/new/src/cm/models/system/user_mgmt/__init__.py	(revision 2437)
+++ /branches/amp_3_7_0/src/webui/webui/htdocs/new/src/cm/models/system/user_mgmt/__init__.py	(working copy)
@@ -137,6 +137,7 @@
                 # should not delete auth info here, avoid not write memory and reboot, will do clean in script when bootup
                 delete_sql = ''' DELETE FROM user_authorization WHERE username='%s' ''' % each['username']
                 db.execute_sql(delete_sql)
+                ANSession.delete_session_by_username(each['username'])
             db.close()
             return
 
Index: /branches/amp_3_7_0/src/webui/webui/htdocs/new/src/hive/session.py
===================================================================
--- /branches/amp_3_7_0/src/webui/webui/htdocs/new/src/hive/session.py	(revision 2437)
+++ /branches/amp_3_7_0/src/webui/webui/htdocs/new/src/hive/session.py	(working copy)
@@ -5,7 +5,7 @@
 from datetime import datetime
 from hive.utils import anlog, anerror, andebug
 from hive.model.legacycli import ANCLIConn, CLIEnablePassError, RegexParser, MATCHONE
-from hive.model.loading import get_apps,get_model
+from hive.model.loading import get_apps, get_model
 from hive.model.package import ANPackageAgent
 from jinja2 import Environment, PackageLoader, ChoiceLoader
 from django.http import HttpResponse
@@ -22,10 +22,11 @@
 from django.views.decorators.csrf import csrf_exempt
 from datetime import timedelta
 from cm.lib.libbasic_operation import oper_log
-    
+
+
 class ANSession(object):
     _session_pool = {}
-    
+
     def __init__(self, username, password, priv):
         self._username = username
         self._password = password
@@ -41,7 +42,7 @@
         self.theme = self.pref.get_default_theme()
         self.engmode = False
         self.doc_engmode = False
-        self.eng_app_xml_trees = {} # per-session XML doc cache for eng mode
+        self.eng_app_xml_trees = {}  # per-session XML doc cache for eng mode
         self.create_time = datetime.now()
         self.timestamp = time.time()
         self.enable_password_checked = False
@@ -56,13 +57,13 @@
                 self.cli.set_enable(force=True)
             except CLIEnablePassError:
                 return None
-            
+
         """ 
         for name, app in get_apps().iteritems():
             setattr(self, name, ANPackageAgent(package=app,session=self))
         """
         return self
-        
+
     def logout(self):
         if an_settings.LEGACY_CLI_AGENT:
             try:
@@ -86,7 +87,7 @@
         if model_class is None:
             raise KeyError('No such model %s.%s' % (app_name, '.'.join(model_path)))
         return model_class.get_manager(self)
-        
+
     @property
     def sessid(self):
         return self._sessid
@@ -105,7 +106,7 @@
 
     @property
     def model(self):
-        return self.cli.cmd('show version',RegexParser('Model : (.+?)\n'))[0]
+        return self.cli.cmd('show version', RegexParser('Model : (.+?)\n'))[0]
 
     @staticmethod
     def gen_random_sessid():
@@ -118,18 +119,35 @@
     @staticmethod
     def find_session_by_id(sessid):
         return ANSession._session_pool.get(sessid, None)
-    
+
+    @staticmethod
+    def find_session_by_username(username):
+        pool = ANSession._session_pool
+        for session_id in pool:
+            session = ANSession.find_session_by_id(session_id)
+            if session.username.strip() == username.strip():
+                return session
+        return None
+
+    @staticmethod
+    def delete_session_by_username(username):
+        session = ANSession.find_session_by_username(username)
+        if session is not None:
+            ANSession._session_pool.pop(session.sessid)
+
     def _clear_eng_doc_cache(self):
         self.eng_app_xml_trees = {}
-    
+
     def reload_document(self):
         self._clear_eng_doc_cache()
         for name, app in get_apps().iteritems():
             app.reload_document()
 
+
 def current_app():
     return an_settings.AN_APPS[0]
 
+
 def login_handler(request):
     django_ctx = RequestContext(request)
     if request.method == 'GET':
@@ -142,8 +160,9 @@
         else:
             env = HiveEnvironment(loader=PackageLoader('hive', 'templates'))
             template = env.get_template('login.html')
-            return HttpResponse(template.render({'csrf_token':django_ctx['csrf_token'], 'MEDIA':'/media/', 'APP':current_app().upper()}))
-        
+            return HttpResponse(template.render(
+                {'csrf_token': django_ctx['csrf_token'], 'MEDIA': '/media/', 'APP': current_app().upper()}))
+
     elif request.method == 'POST':
         session = None
         if 'hive_sess' in request.COOKIES:
@@ -158,14 +177,16 @@
             else:
                 env = HiveEnvironment(loader=PackageLoader('hive', 'templates'))
                 template = env.get_template('login.html')
-                return HttpResponse(template.render({'csrf_token':django_ctx['csrf_token'], 'MEDIA':'/media/', 'error':'Invalid request', 'APP':current_app().upper()}))
+                return HttpResponse(template.render(
+                    {'csrf_token': django_ctx['csrf_token'], 'MEDIA': '/media/', 'error': 'Invalid request',
+                     'APP': current_app().upper()}))
 
-        ret = getattr(auth, 'auth_'+current_app())(username, password)
+        ret = getattr(auth, 'auth_' + current_app())(username, password)
         if ret:
             if not session:
                 # create session
                 session = ANSession(username, password, ret)
-            
+
             # XXX APV enable password
             if 'enable_password' in request.POST:
                 result = session.login(request.POST['enable_password'])
@@ -189,11 +210,14 @@
                 env = HiveEnvironment(loader=PackageLoader('hive', 'templates'))
                 template = env.get_template('login.html')
                 if 'enable_password' in request.POST:
-                    send_notification('error', '%s is trying to login with an invalid enable password.' % username, session=session)
+                    send_notification('error', '%s is trying to login with an invalid enable password.' % username,
+                                      session=session)
                     error_msg = 'Invalid enable password'
                 else:
                     error_msg = ''
-                response = HttpResponse(template.render({'csrf_token':django_ctx['csrf_token'], 'MEDIA':'/media/', 'error':error_msg, 'get_enable':1, 'APP':current_app().upper()}))
+                response = HttpResponse(template.render(
+                    {'csrf_token': django_ctx['csrf_token'], 'MEDIA': '/media/', 'error': error_msg, 'get_enable': 1,
+                     'APP': current_app().upper()}))
                 response.set_cookie('django_language', session.pref.get_default_lang())
                 response.set_cookie('hive_sess', session.sessid)
                 return response
@@ -202,16 +226,19 @@
             template = env.get_template('login.html')
             if session:
                 session.logout()
-            #clear session in thread here, just make it send notification correctly.
+            # clear session in thread here, just make it send notification correctly.
             _thread_locals.session = None
             send_notification('error', '%s is trying to login with an invalid password.' % username)
-            return HttpResponse(template.render({'csrf_token':django_ctx['csrf_token'], 'MEDIA':'/media/', 'error':'Invalid username or password', 'APP':current_app().upper()}))
+            return HttpResponse(template.render(
+                {'csrf_token': django_ctx['csrf_token'], 'MEDIA': '/media/', 'error': 'Invalid username or password',
+                 'APP': current_app().upper()}))
+
 
 def logout_handler(request):
-    #django_ctx = RequestContext(request)
-    #env = HiveEnvironment(loader=PackageLoader('hive', 'templates'))
-    #template = env.get_template('login.html')
-    #response = HttpResponse(template.render({'csrf_token':django_ctx['csrf_token'], 'MEDIA':'/media/'}))
+    # django_ctx = RequestContext(request)
+    # env = HiveEnvironment(loader=PackageLoader('hive', 'templates'))
+    # template = env.get_template('login.html')
+    # response = HttpResponse(template.render({'csrf_token':django_ctx['csrf_token'], 'MEDIA':'/media/'}))
     response = HttpResponse()
     if 'hive_sess' in request.COOKIES:
         sess = ANSession.find_session_by_id(request.COOKIES['hive_sess'])
@@ -224,6 +251,7 @@
     response = redirect('/app/')
     return response
 
+
 @csrf_exempt
 def app_login_handler(request):
     django_ctx = RequestContext(request)
@@ -232,10 +260,12 @@
         if 'hive_sess' in request.COOKIES:
             session = ANSession.find_session_by_id(request.COOKIES['hive_sess'])
         if session:
-            return HttpResponse(json.dumps({'error_code':0, 'msg': 'You have logged in.'}), content_type='application/json')
+            return HttpResponse(json.dumps({'error_code': 0, 'msg': 'You have logged in.'}),
+                                content_type='application/json')
         else:
-            return HttpResponse(json.dumps({'error_code':1, 'msg': 'You need to log in.'}), content_type='application/json')
-        
+            return HttpResponse(json.dumps({'error_code': 1, 'msg': 'You need to log in.'}),
+                                content_type='application/json')
+
     elif request.method == 'POST':
         session = None
         if 'hive_sess' in request.COOKIES:
@@ -249,14 +279,15 @@
                 password = session._password
             else:
                 oper_log('error', 'login', 'User <%s> failed to login.' % username)
-                return HttpResponse(json.dumps({'error_code':1, 'msg': 'Invalid request.'}), content_type='application/json')
+                return HttpResponse(json.dumps({'error_code': 1, 'msg': 'Invalid request.'}),
+                                    content_type='application/json')
 
-        ret = getattr(auth, 'auth_'+current_app())(username, password)
+        ret = getattr(auth, 'auth_' + current_app())(username, password)
         if ret:
             if not session:
                 # create session
                 session = ANSession(username, password, ret)
-            
+
             # XXX APV enable password
             if 'enable_password' in request.POST:
                 result = session.login(request.POST['enable_password'])
@@ -265,10 +296,10 @@
             if result:
                 session.enable_password_checked = True
                 user_info = {
-                    "django_language":session.pref.get_default_lang(),
-                    "csrf_token":unicode(django_ctx['csrf_token']),
-                    "hive_key":str(ret),
-                    "current_user":username
+                    "django_language": session.pref.get_default_lang(),
+                    "csrf_token": unicode(django_ctx['csrf_token']),
+                    "hive_key": str(ret),
+                    "current_user": username
                 }
 
                 check_license = check_license_expire(session)
@@ -276,12 +307,16 @@
                     if session:
                         session.logout()
                     _thread_locals.session = None
-                    response = HttpResponse(json.dumps({'error_code': 3, 'msg': 'License has been expired.'}), content_type='application/json')
-                    oper_log('error', 'login', 'User <%s> failed to login because the license has been expired.' % username)
+                    response = HttpResponse(json.dumps({'error_code': 3, 'msg': 'License has been expired.'}),
+                                            content_type='application/json')
+                    oper_log('error', 'login',
+                             'User <%s> failed to login because the license has been expired.' % username)
                     return response
                 send_notification('success', 'User logged in.', session=session)
 
-                response = HttpResponse(json.dumps({'error_code':0, 'hive_key':ret, 'user_info':user_info, 'msg': 'Logging in successfully.', 'check_license': check_license}), content_type='application/json')
+                response = HttpResponse(json.dumps(
+                    {'error_code': 0, 'hive_key': ret, 'user_info': user_info, 'msg': 'Logging in successfully.',
+                     'check_license': check_license}), content_type='application/json')
                 response.set_cookie('django_language', session.pref.get_default_lang(), secure=True)
                 response.set_cookie('hive_sess', session.sessid, secure=True)
                 # response.set_cookie('ComposerUICookie', 'f1f713c9e000f5d3f280adbd124df4f5')
@@ -292,11 +327,13 @@
                 return response
             else:
                 if 'enable_password' in request.POST:
-                   send_notification('error', '%s is trying to login with an invalid enable password.' % username, session=session)
-                   error_msg = 'Invalid enable password'
+                    send_notification('error', '%s is trying to login with an invalid enable password.' % username,
+                                      session=session)
+                    error_msg = 'Invalid enable password'
                 else:
-                   error_msg = ''
-                response = HttpResponse(json.dumps({'error_code':-1, 'msg': error_msg}), content_type='application/json')
+                    error_msg = ''
+                response = HttpResponse(json.dumps({'error_code': -1, 'msg': error_msg}),
+                                        content_type='application/json')
                 response.set_cookie('django_language', session.pref.get_default_lang(), secure=True)
                 response.set_cookie('hive_sess', session.sessid, secure=True)
                 oper_log('error', 'login', 'User <%s> failed to login with an invalid enable password.' % username)
@@ -304,14 +341,17 @@
         else:
             if session:
                 session.logout()
-            #clear session in thread here, just make it send notification correctly.
+            # clear session in thread here, just make it send notification correctly.
             _thread_locals.session = None
             send_notification('error', '%s is trying to login with an invalid password.' % username)
             oper_log('error', 'login', 'User <%s> failed to login with an invalid password.' % username)
-            return HttpResponse(json.dumps({'error_code':2, 'msg': 'Invalid username or password.'}), content_type='application/json')
+            return HttpResponse(json.dumps({'error_code': 2, 'msg': 'Invalid username or password.'}),
+                                content_type='application/json')
+
 
 def app_logout_handler(request):
-    response = HttpResponse(json.dumps({'error_code':0, 'msg': 'Loging out successfully.'}), content_type='application/json')
+    response = HttpResponse(json.dumps({'error_code': 0, 'msg': 'Loging out successfully.'}),
+                            content_type='application/json')
     if 'hive_sess' in request.COOKIES:
         sess = ANSession.find_session_by_id(request.COOKIES['hive_sess'])
         send_notification('info', 'User logged out.')
@@ -321,7 +361,8 @@
         # response.delete_cookie('ComposerUICookie')
         response.delete_cookie('csrf_token')
         response.delete_cookie('current_user')
-    return response    
+    return response
+
 
 def register_complete(request):
     response = HttpResponse("")
@@ -330,14 +371,16 @@
         sess.register_complete()
     return response
 
+
 def is_avx_mode():
-    rst=os.popen("sysctl kern.avx_model").read()
-    rst=rst.split()
+    rst = os.popen("sysctl kern.avx_model").read()
+    rst = rst.split()
     if len(rst) == 2:
-        if '-1'!=rst[1]:
-            return True 
+        if '-1' != rst[1]:
+            return True
     return False
 
+
 def check_license_expire(session):
     expire = True
     msg = ""
@@ -362,6 +405,7 @@
 
     return [expire, msg]
 
+
 @contextmanager
 def temp_session(request, app):
     sess = None
@@ -370,8 +414,8 @@
         if len(a) == 2:
             if a[0].lower() == "basic":
                 uname, passwd = a[1].decode('base64').split(':')
-                #andebug('hive.debug', 'user name: %s, password: %s' % (uname, passwd) )
-                ret = getattr(auth, 'auth_'+current_app())(uname, passwd)
+                # andebug('hive.debug', 'user name: %s, password: %s' % (uname, passwd) )
+                ret = getattr(auth, 'auth_' + current_app())(uname, passwd)
                 if ret:
                     # create session
                     sess = ANSession(uname, passwd, ret).login('')
@@ -384,8 +428,10 @@
             sess.logout()
             _thread_locals.session = None
 
+
 class HiveSessionMiddleware(object):
     global_thread_id = 1
+
     def process_request(self, request):
         if getattr(_thread_locals, '_hive_thread_id', -1) == -1:
             _thread_locals._hive_thread_id = HiveSessionMiddleware.global_thread_id
@@ -393,23 +439,23 @@
         _thread_locals.request = request
         # validate the session
         if request.path_info in an_settings.PUBLIC_PATHS:
-            return None # got public path, continue the process to the router
+            return None  # got public path, continue the process to the router
         if request.path_info.startswith("/restapi_on/"):
-            return None # as we send port after RESTful_API_ON, so could not match in PUBLIC_PATHS 
+            return None  # as we send port after RESTful_API_ON, so could not match in PUBLIC_PATHS
         if request.path_info.startswith("/ReloadAppNode/"):
-            return None # as we send app name after /ReloadAppNode/, so could not match in PUBLIC_PATHS 
+            return None  # as we send app name after /ReloadAppNode/, so could not match in PUBLIC_PATHS
         if request.path_info.startswith("/rest"):
             return None
         if request.META['REQUEST_URI'].startswith('/rest'):
-            return None # restful api continue the process to the hive_rest_router
+            return None  # restful api continue the process to the hive_rest_router
         if request.META['REQUEST_URI'].startswith('/statistics'):
-            return None # restful api continue the process to the hive_rest_router
+            return None  # restful api continue the process to the hive_rest_router
         if request.META['REQUEST_URI'].startswith('/monitord'):
-            return None # restful api continue the process to the hive_rest_router
+            return None  # restful api continue the process to the hive_rest_router
         if request.META['REQUEST_URI'].startswith('/cm/device_change_result'):
-            return None # restful api continue the process to the hive_rest_router
+            return None  # restful api continue the process to the hive_rest_router
         if 'AUTH_TYPE' in request.META:
-            return None # restful api continue the process to the hive_rest_router
+            return None  # restful api continue the process to the hive_rest_router
         # get session id from cookie
         sess = None
         if 'hive_sess' in request.COOKIES:
@@ -419,11 +465,11 @@
                     sess.logout()
                     _thread_locals.session = None
                     sess = None
-                else:                    
-                    #here we should add the timeout mechanism by checking && updating timestamp in session
+                else:
+                    # here we should add the timeout mechanism by checking && updating timestamp in session
                     timestamp = sess.timestamp
-                    difference = time.time()-timestamp
-                    if difference > 15*60 and timestamp != -1:
+                    difference = time.time() - timestamp
+                    if difference > 15 * 60 and timestamp != -1:
                         sess.logout()
                         _thread_locals.session = None
                         sess = None
@@ -431,23 +477,24 @@
                         # for time change request, rest the timestamp
                         if request.path_info in ['/api/avx/system/TimeSettings/_update']:
                             sess.timestamp = -1
-                        #for request in white list, won't update the timestamp in session
+                        # for request in white list, won't update the timestamp in session
                         elif not request.path_info in ['/poll_notification', '/cm/get_user_auth', '/cm/get_user_info']:
                             sess.timestamp = time.time()
         if sess is None:
-            #codes for new frontend
+            # codes for new frontend
             if request.path_info == '/':
                 response = redirect('/app/')
             else:
                 response = HttpResponse()
                 response.status_code = 401
                 return response
-            #codes for old frontend    
-            #response = redirect('/login')
-            
+            # codes for old frontend
+            # response = redirect('/login')
+
             # reset the language cookie into system default
             response.set_cookie('django_language', an_settings.SYS_DEFAULT_LANG)
-            if request.path_info and request.path_info.startswith('/'+current_app()) and 'ajax' not in request.path_info:
+            if request.path_info and request.path_info.startswith(
+                    '/' + current_app()) and 'ajax' not in request.path_info:
                 original_url = request.path_info
                 if len(request.GET):
                     original_url += ('?' + request.GET.urlencode())
@@ -459,5 +506,4 @@
             except:
                 pass
             _thread_locals.session = sess
-            return None # found session continue the process to the router
-
+            return None  # found session continue the process to the router
\ No newline at end of file
