Commits

Joel Rivera  committed 1579332

Refactor globus login method to an indivudual class

  • Participants
  • Parent commits 419cdd7
  • Branches gauth

Comments (0)

Files changed (1)

File lib/galaxy/web/framework/ext/globus/middleware.py

 
 log = logging.getLogger(__name__)
 
+
 class UserAuthentication(object):
     default_nexus_server = 'nexus.api.globusonline.org'
     auth_page = """\
                 "Unable to set Globus User Authentication middlerware. "
                 "The nexus client 'globus_nexus_client' and client secret "
                 "'globus_nexus_secret' are required.")
-        self.gaccount_cmd = gaccount_cmd
-        self.groupid = groupid
+        self.app = app
+        self.active_users =  {}
         if nexserver is None:
             nexserver = self.default_nexus_server
-        self.nexus_client = nexus.Client({'server': nexserver,
-                                          'client': nexclient,
-                                          'client_secret': nexsecret})
-        self.app = app
-        self.active_users = {}
-        self.handlers = {self.LOGOUT: self._do_logout,
-                         self.LOGIN: self._do_login,
-                         self.AUTHENTICATED: self._authenticate,
-                         self.NOT_AUTHORIZED: self._not_authorized,
-                         self.NOT_ALLOWED: self._user_not_allowed}
+        self.nexus_client = nc = nexus.Client({'server': nexserver,
+                                               'client': nexclient,
+                                               'client_secret': nexsecret})
+        self.handlers = {
+            self.LOGOUT: self._do_logout,
+            self.LOGIN:
+            LoginHandler(app, nc, active_users=self.active_users,
+                         gaccount_cmd=gaccount_cmd,
+                         groupid=groupid),
+            self.AUTHENTICATED: self._authenticate,
+            self.NOT_AUTHORIZED: self._not_authorized,
+            self.NOT_ALLOWED: self._user_not_allowed
+        }
         
     def __call__(self, environ, start_response):
         session = self._session(environ)
                                           ('Location', '/')])
         return ''
 
-    def _is_user_in_group(self, user, atoken):
-        gorc = GlobusOnlineRestClient(self.nexus_client.server, user, goauth_token=atoken)
-        _, membership = gorc.get_group_member(self.groupid, user)
-        if membership:
-            return membership['status'] == 'active'
-        return False
-    
-    def _user_not_in_group(self, user, start_response):
-        headers = [('Content-type', 'text/html'),
-                   ('Location', '/?action=user_not_allowed&user=%s' % user)]
-        start_response('303 See other', headers)
-        return ''
+        
+    def _user_in_session(self, session):
+        if session is not None and \
+               session in self.active_users:
+            user, tokens = self.active_users[session]
+            log.debug('Logged in user %s with tokens %s' % (user, tokens))
+            return user, tokens['access']
+        return None
+
+        
+    def _req_cookie(self, environ):
+        cookie = BaseCookie()
+        cookie.load(environ.get('HTTP_COOKIE', ''))
+        return cookie
+
+    def _session(self, environ):
+        cookie = self._req_cookie(environ)
+        if cookie:
+            try:
+                session = cookie['galaxysession']
+            except KeyError:
+                return None
+            else:
+                return session.value
+
+    def globus_url(self, env):
+        return (('https://www.globusonline.org/OAuth?response_type=code&'
+                'redirect_uri={0}&client_id={1}') 
+                .format(self._host(env), self.nexus_client.client))
+
+    def _host(self, env):
+        scheme = env['wsgi.url_scheme']
+        host = env['HTTP_HOST']
+        return '%s://%s' % (scheme, host)
+        
+        
+class ActionHandler(object):
+    required_args = set([])
+
+    def __init__(self, app, nexus_client, **kwargs):
+        self.app = app
+        self.nexus_client = nexus_client
+        if self.required_args - set(kwargs):
+            raise Exception("Missing required arguments %s" % self.required_args)
+        else:
+            for name, value in kwargs.items():
+                setattr(self, name, value)
+
+
+class LoginHandler(ActionHandler):
+    required_args = set(('active_users', 'gaccount_cmd', 'groupid'))
+
+    def __call__(self, session, start_response, environ, code):
+        tokens = self._fetch_access_tokens(code) 
+        user = self.nexus_client.get_user_using_access_token(tokens['access'])
+        if self.groupid is not None:
+            if not self._is_user_in_group(user['username'], tokens['access']):
+                return self._user_not_in_group(user['username'], start_response)
+        environ['HTTP_REMOTE_USER'] = user['username']
+        def custom_start_response(status, headers, exc_info=None):
+            """This is closure to bind Galaxy Session with Globus User.
+            Look for the Set-Cookie header in the next middleware.
+            """
+            if session is None:
+                for name, value in headers:
+                    if name == 'Set-Cookie':
+                        cookie = BaseCookie()
+                        cookie.load(value)
+                        if 'galaxysession' in cookie:
+                            sess = cookie['galaxysession'].value
+                            self._add_to_active_users(sess, user, tokens)
+                        break
+            else:
+                self._add_to_active_users(session, user, tokens)
+            headers  += [('Content-type', 'text/html'),
+                         ('Location', '/')]
+            return start_response('303 See Other', headers, exc_info)        
+        return self.app(environ, custom_start_response)
+
+    def _add_to_active_users(self, _session, _user, _tokens):
+        username = _user['username']
+        try:
+            pwd.getpwnam(username)
+        except KeyError:
+            self._create_unix_account(username)
+            try:
+                pwd.getpwnam(username) # validate.
+            except KeyError:
+                msg = (
+                    'Unable to create the local account "%s".\n'
+                    'This exception should not be reached, '
+                    '_create_unix_account is not working fine.'
+                    % username)
+                log.error(msg)
+                raise Exception(msg)
+        self.active_users[_session] = (_user, _tokens)
 
     def _create_unix_account(self, user):
         """Create the account with the command "self.gaccount_cmd"
             log.error(msg)
             raise OSError(msg)
 
-        
-    def _do_login(self, session, start_response, environ, code):
-        tokens = self._fetch_access_tokens(code) 
-        user = self.nexus_client.get_user_using_access_token(tokens['access'])
-        if self.groupid is not None:
-            if not self._is_user_in_group(user['username'], tokens['access']):
-                return self._user_not_in_group(user['username'], start_response)
-        environ['HTTP_REMOTE_USER'] = user['username']
-        def add_to_active_users(_session, _user, _tokens):
-            username = _user['username']
-            try:
-                pwd.getpwnam(username)
-            except KeyError:
-                self._create_unix_account(username)
-                try:
-                    pwd.getpwnam(username) # validate.
-                except KeyError:
-                    msg = (
-                        'Unable to create the local account "%s".\n'
-                        'This exception should not be reached, '
-                        '_create_unix_account is not working fine.'
-                        % username)
-                    log.error(msg)
-                    raise Exception(msg)
-            self.active_users[_session] = (_user, _tokens)
-            
-        def custom_start_response(status, headers, exc_info=None):
-            """This is closure to bind Galaxy Session with Globus User.
-            Look for the Set-Cookie header in the next middleware.
-            """
-            if session is None:
-                for name, value in headers:
-                    if name == 'Set-Cookie':
-                        cookie = BaseCookie()
-                        cookie.load(value)
-                        if 'galaxysession' in cookie:
-                            sess = cookie['galaxysession'].value
-                            add_to_active_users(sess, user, tokens)
-                        break
-            else:
-                add_to_active_users(session, user, tokens)
-            headers  += [('Content-type', 'text/html'),
-                         ('Location', '/')]
-            return start_response('303 See Other', headers, exc_info)
-        
-        return self.app(environ, custom_start_response)
-
-    def _user_in_session(self, session):
-        if session is not None and \
-               session in self.active_users:
-            user, tokens = self.active_users[session]
-            log.debug('Logged in user %s with tokens %s' % (user, tokens))
-            return user, tokens['access']
-        return None
-
     def _fetch_access_tokens(self, code):
         atokens = self.nexus_client.get_access_token_from_code(code)
         return dict(zip(('access', 'refresh', 'exp'), atokens))
         
-    def _req_cookie(self, environ):
-        cookie = BaseCookie()
-        cookie.load(environ.get('HTTP_COOKIE', ''))
-        return cookie
+    def _user_not_in_group(self, user, start_response):
+        headers = [('Content-type', 'text/html'),
+                   ('Location', '/?action=user_not_allowed&user=%s' % user)]
+        start_response('303 See other', headers)
+        return ''
 
-    def _session(self, environ):
-        cookie = self._req_cookie(environ)
-        if cookie:
-            try:
-                session = cookie['galaxysession']
-            except KeyError:
-                return None
-            else:
-                return session.value
+    def _is_user_in_group(self, user, atoken):
+        gorc = GlobusOnlineRestClient(self.nexus_client.server,
+                                      user, goauth_token=atoken)
+        _, membership = gorc.get_group_member(self.groupid, user)
+        if membership:
+            return membership['status'] == 'active'
+        return False
+    
 
-    def globus_url(self, env):
-        return (('https://www.globusonline.org/OAuth?response_type=code&'
-                'redirect_uri={0}&client_id={1}') 
-                .format(self._host(env), self.nexus_client.client))
-
-    def _host(self, env):
-        scheme = env['wsgi.url_scheme']
-        host = env['HTTP_HOST']
-        return '%s://%s' % (scheme, host)
-        
-