def test_get_or_create_from_api_data_returns_user_if_exists(self): user_data = { 'username': u"user_one", 'first_name': u"", 'last_name': u"" } # create the instance refresh_token = 'a123f4' OnaUser.get_or_create_from_api_data(user_data, refresh_token) # try to get or create new_refresh_token = 'b234f5' ona_user = OnaUser.get_or_create_from_api_data( user_data, new_refresh_token) self.assertIsInstance(ona_user, OnaUser) self.assertIsInstance(ona_user.user, User) self.assertEqual(ona_user.refresh_token, new_refresh_token)
def oauth_callback(request): # check if we have `error` in our params, meaning user canceled if 'error' in request.GET: # redirect to login page with an alert request.session.flash(u"You must select authorize to continue", 'error') return HTTPFound(request.route_url('auth', action='login')) # TODO: validate the `oauth_state` session base_url = request.registry.settings['oauth_base_url'] state = request.GET.get('state') client_id = request.registry.settings['oauth_client_id'] client_secret = request.registry.settings['oauth_secret'] token_url = "{base_url}{path}".format( base_url=base_url, path=request.registry.settings['oauth_token_path']) redirect_uri = request.route_url('auth', action='callback') session = OAuth2Session(client_id, state=state, redirect_uri=redirect_uri) code = request.GET.get('code') token = session.fetch_token(token_url, client_secret=client_secret, code=code) # retrieve username and store in db if it doesnt exist yet user_api_url = "{base_url}{path}".format( base_url=base_url, path=request.registry.settings['oauth_user_api_path']) response = session.request('GET', user_api_url) try: user_data = json.loads(response.text) except ValueError: # couldn't decode json pass else: refresh_token = token['refresh_token'] try: ona_user = OnaUser.get_or_create_from_api_data( user_data, refresh_token) except ValueError: pass else: request.session['oauth_token'] = json.dumps(token) # flash to get the auto-inc id DBSession.flush() user_id = ona_user.user.id # login user headers = remember(request, user_id) # TODO: redirect to `came_from` url return HTTPFound(request.route_url('default'), headers=headers) request.session.flash(u"Failed to login, please try again", 'error') return HTTPFound(request.route_url('auth', action='login'))
def test_get_or_create_from_api_data_creates_user(self): user_data = { 'username': u"user_one", 'first_name': u"", 'last_name': u"" } refresh_token = 'a123f4' ona_user = OnaUser.get_or_create_from_api_data( user_data, refresh_token) self.assertIsInstance(ona_user, OnaUser) self.assertIsInstance(ona_user.user, User)