def auth_post(request): """ An endpoint to authenticate users and retrieve their access token. The access token is needed to authenticate requests that needs authorization:: /endpont?access_token=<access token> returns ======= returns 401 auth error if fails, otherswise returns:: { 'access_token': '', 'user_id': '' } """ email = request.validated['email'] password = request.validated['password'] user = User.authenticate_user(email, password) response_body = {} if user: # user found and authenticated logger.debug('user:{} authenticated'.format(email)) access_token = create_access_token(user) response_body = json.dumps({ 'access_token': access_token, 'user_id': str(user.id), }) else: # user not found or authenticated logger.debug('user:{} failed authentication'.format(email)) request.response.status_int = 401 response_body = json.dumps({ 'status': 'error', 'message': 'user failed to authenticate', }) request.response.body = response_body request.response.content_type = 'application/json' return request.response
def test_user(self): response = self.testapp.post_json('/api/v1/users', {}, status=400) # create new user payload = { 'email': '*****@*****.**', 'password': '******', } response = self.testapp.post_json('/api/v1/users', payload, status=200) self.assertTrue(response.json['id']) # check duplicate response = self.testapp.post_json('/api/v1/users', payload, status=400) # check database user = User.get_by_email('*****@*****.**') self.assertTrue(user) self.created.append(user) # get user endpoint = '/api/v1/users/{}'.format(user.id) response = self.testapp.get(endpoint, status=200) self.assertTrue(response.json['id']) # update user payload = { 'active': True, 'email': '*****@*****.**', } endpoint = '/api/v1/users/{}'.format(user.id) response = self.testapp.put_json(endpoint, payload, status=200) user = User.get_by_id(user.id) self.assertTrue(user.active) # change password payload = { 'password': '******', } endpoint = '/api/v1/users/{}/password'.format(user.id) response = self.testapp.put_json(endpoint, payload, status=200) user = User.authenticate_user('*****@*****.**', 'world') self.assertTrue(user)
def authentication(self, user): user2 = User.authenticate_user(user.email, 'hello') self.assertTrue(user.id == user2.id) self.assertFalse(User.authenticate_user(user.email, 'world')) self.assertFalse(User.authenticate_user('*****@*****.**', 'hello'))