def authenticate(self, environ, identity): ''' Authenticate and extract identity from OAuth2 tokens ''' request = Request(environ) log.debug('Repoze OAuth authenticate') if 'oauth2.token' in identity: oauth = OAuth2Session( self.client_id, token=identity['oauth2.token']) profile_response = oauth.get(self.profile_api_url) profile_data = profile_response.json() if not profile_data['authenticated']: return None user_data = profile_data['principal'] user = User.by_name(user_data['username']) if user is None: user = User() user.name = user_data['username'] user.email = user_data['email'] user.fullname = u"{} {}".format( user_data['name'], user_data['surname']) user.save() user.activate() user.save() identity.update({'repoze.who.userid': user.name}) self._redirect_from_callback(request, identity) return user.name return None
def preauthenticate(self, environ, identity): # turn the oauth identity into a CKAN one; set it in our identity import oauth2 as oauth try: access_token = dict(urlparse.parse_qsl(identity['userdata'])) oauth_token = access_token['oauth_token'] oauth_token_secret = access_token['oauth_token_secret'] except KeyError: return None access_token = oauth.Token(oauth_token, oauth_token_secret) client = oauth.Client(self.consumer, access_token) resp, content = client.request(self.user_url, "GET") data = json.loads(content) user_id = data['id'] logging.info("Preauth: Got oauth user data for user %s" % user_id) user = User.by_openid(user_id) if user is None: user = User(openid=user_id, name=data['id'], fullname=data['name'], email=data['mail']) Session.add(user) else: user.fullname = data['name'] # if the name is updated Session.commit() Session.remove() logging.info("Preauth: Created new/updated user %s" % user_id) # deal with groups user_groups = data['groups'] _sync_auth_groups(user, user_groups) name = user.name.encode("utf8") logging.info("Preauth: Returning user identifier %s" % name) identity['repoze.who.userid'] = name return identity