def test_encode_auth_token(self): user = User(email='*****@*****.**', password='******', registered_on=datetime.datetime.utcnow()) db.session.add(user) db.session.commit() auth_token = user.encode_auth_token(user.id) self.assertTrue(isinstance(auth_token, bytes))
def test_decode_auth_token(self): user = User(email='*****@*****.**', password='******', registered_on=datetime.datetime.utcnow()) db.session.add(user) db.session.commit() auth_token = User.encode_auth_token(user.id) self.assertTrue( User.decode_auth_token(auth_token.decode('utf-8')) == user.id)
def test_encode_auth_token(self): user = User(email='*****@*****.**', last_name='Arthur', name='Oliver', password='******', registered_on=datetime.datetime.utcnow()) db.session.add(user) db.session.commit() auth_token = User.encode_auth_token(user.id) self.assertTrue(isinstance(auth_token, bytes))
def test_create_user_follow_request(self, mock): user_1 = User(fb_id='123', email=None, name='Jake') user_2 = User(fb_id='123', email=None, name='Jane') db.session.add(user_1) db.session.add(user_2) db.session.commit() mock.return_value = user_1 resp, status_code = user_service.create_user_follow_request({"id": 2}) assert status_code == 201
def create_user(): """ Management Script for creating users """ print("=== Create User ===") questions = [ inquirer.Text("name", message="Full Name"), inquirer.Text("username", message="Username"), inquirer.Password("password", message="Password"), inquirer.Password("password_repeat", message="Confirm Password"), inquirer.Text("tribe_id", message="Tribe ID (optional)"), inquirer.List( "role", message="Role", choices=[UserRoles.USER, UserRoles.ADMIN, UserRoles.TRIBE_ADMIN]) ] answers = inquirer.prompt(questions) name = answers.get("name") username = answers.get("username") password = answers.get("password") password_repeat = answers.get("password_repeat") tribe_id = answers.get("tribe_id") role = answers.get("role") if not tribe_id: tribe_id = None if password_repeat != password: print("Passwords do not match!") return user = User(tribe_id=tribe_id, public_id=str(uuid4()), username=username, name=name, role=role, created_on=datetime.utcnow()) user.password = password print("Do you want to add this user to the database?") print(user) answers = inquirer.prompt([inquirer.Confirm("confirm", message="Confirm")]) confirm = answers.get("confirm") if not confirm: return db.session.add(user) db.session.commit() print(f"Successfully added user: {user}")
def test_get_all_users(self, mock): user_1 = User(fb_id='123', email=None, name='Jake') user_2 = User(fb_id='123', email=None, name='Jane') db.session.add(user_1) db.session.add(user_2) db.session.commit() mock.return_value = User(fb_id='123', email=None, name='Albert') user_list, status_code = user_service.get_all_users() expected = [{'email': None, 'name': 'Jane', 'id': 2, 'relationship_status': None}, {'email': None, 'name': 'Jake', 'id': 1, 'relationship_status': None}] assert user_list == expected assert status_code == 200
def save_new_user(data): user = User.query.filter_by(email=data['email']).first() if not user: new_user = User(first_name=data['first_name'], last_name=data['last_name'], user_name=data['user_name'], email=data['email'], password_hash=data['password'], confirmation_code=data['confirmation_code'], confirmation_time=None, insert_ts=datetime.datetime.utcnow()) save_changes(new_user) response_object = { 'status': 'success', 'status_code': 00, 'message': 'Successfully registered.' } return response_object, 201 else: response_object = { 'status': 'fail', 'status_code': 2, 'message': 'User already exists. Please Log in.' } return response_object, 409
def test_get_user_subscribers(self, mock): user_1 = User(fb_id='123', email=None, name='Jake') user_2 = User(fb_id='123', email=None, name='Jane') user_1.followers.append(user_2) db.session.add(user_1) db.session.add(user_2) db.session.commit() mock.side_effect = [user_2, user_1] user_service.confirm_user_follow_request({"id": 1}) resp, status_code = user_service.get_user_subscribers() expected = [{'follower_id': 2, 'name': 'Jane'}] assert resp == expected assert status_code == 200
def get_logged_in_user(new_request): # get the auth token auth_token = new_request.headers.get('Authorization') if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): user = User.query.filter_by(id=resp).first() response_object = { 'status': 'success', 'data': { 'user_id': user.id, 'email': user.email, 'admin': user.admin, 'registered_on': str(user.registered_on) } } return response_object, 200 response_object = {'status': 'fail', 'message': resp} return response_object, 401 else: response_object = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return response_object, 401
def test_get_user_subscribedto(self, mock): user_1 = User(fb_id='123', email=None, name='Jake') user_2 = User(fb_id='123', email=None, name='Jane') user_1.followers.append(user_2) db.session.add(user_1) db.session.add(user_2) db.session.commit() mock.return_value = user_2 user_service.confirm_user_follow_request({"id": 1}) resp, status_code = user_service.get_user_subscribedto() expected = [{ "name": "Jake", "user_id": 1 }] assert resp == expected assert status_code == 200
def test_user_create(self): user = User(email='*****@*****.**', name="Test Test", fb_id="12345678") db.session.add(user) db.session.commit() self.assertTrue(user.id == 1) self.assertTrue(user.email == "*****@*****.**") self.assertTrue(user.name == "Test Test")
def test_save_new_poll(self, mock): user_1 = User(fb_id='123', email=None, name='Jake') user_2 = User(fb_id='123', email=None, name='Jane') user_1.followers.append(user_2) db.session.add(user_1) db.session.add(user_2) db.session.commit() mock.return_value = user_1 resp, status_code = poll_service.save_new_poll(1, { "prompt": "test", "form_type": "multChoice", "resp_struct": None }) expected = {"id": 1} assert expected == resp assert status_code == 201
def test_get_a_user(self): user_1 = User(fb_id='123', email=None, name='Jake') db.session.add(user_1) db.session.commit() resp, status_code = user_service.get_a_user(1) expected = {'fb_id': '123', 'email': None, 'id': 1, 'name': 'Jake'} assert resp == expected assert status_code == 200
def post(self): """Creates a new User """ data = request.json new_user = User( email=data['email'], username=data['username'], password=data['password'], registered_on=datetime.datetime.utcnow() ) save_new_item(new_user) return Response(status=201)
def save_new_user(data): user = mongo.db.user.find_one({'email': data['email']}) if user is None: new_user = User(email=data['email'], username=data['username'], password=base64.b64encode(data['password'].encode()), registered_on=datetime.datetime.utcnow()) mongo.db.user.insert_one(new_user.__dict__) return True else: return False
def create_user(self, data): new_user = User(public_id=str(uuid.uuid4()), email=data['email']) if save(new_user): response = {'status': 'success', 'message': 'User created'} return response, 201 else: response = { 'status': 'failure', 'message': 'Failed to create user' } return response, 409
def patch(self, user: User, jwt: dict, **_): """ PATCH /user/<user_id> Edits a User """ user.name = request.json.get("name") or user.name user.username = request.json.get("username") or user.username tribe_id = request.json.get("tribe_id") if tribe_id is not None: tribe = TribeService.get_by_public_id(tribe_id) if tribe is None: return self.format_failure(404, "Tribe not found") user.tribe_id = tribe_id role = request.json.get("role") if role is not None: if jwt.get("role") != UserRoles.ADMIN: return self.format_failure( 401, "You are not authorized to perform this action") user.role = role user.save() return self.format_success(200, {"user": user.dictionary})
def post(self, tribe, **_): """ POST /users/create """ role = request.json.get("role", UserRoles.USER) tribe_id = tribe.id if tribe is not None else None user = User.create(username=request.json["username"], password=request.json["password"], name=request.json["name"], role=role, tribe_id=tribe_id) return self.format_success(200, {"user": user.dictionary})
def generate_token(user): try: # generate the auth token auth_token = User.encode_auth_token(user.id) response_object = { 'status': 'success', 'message': 'Successfully registered.', 'Authorization': auth_token.decode() } return response_object, 201 except Exception as e: response_object = { 'status': 'fail', 'message': 'Some error occurred. Please try again.' } return response_object, 401
def save_new_user(data): user = User.query.filter_by(email=data['email']).first() if not user: new_user = User(public_id=str(uuid.uuid4()), email=data['email'], username=data['username'], password=data['password'], registered_on=datetime.datetime.utcnow()) save_changes(new_user) return generate_token(new_user) else: response_object = { 'status': 'fail', 'message': 'User already exists. Please Log in.', } return response_object, 409
def save_new_user(data): """ Creates a new user """ user = User.query.filter_by(email=data['email']).first() if not user: new_user = User(email=data['email'], username=data['username'], password=data['password'], registered_on=datetime.datetime.utcnow()) save_changes(new_user) response = { 'status': 'success', 'message': 'User successfully created' } return response, 201 else: response = {'status': 'fail', 'message': 'User already exists'} return response, 409
def setUp(self): super().setUp() self.user = User(email='*****@*****.**', password='******', registered_on=datetime.datetime.utcnow()) db.session.add(self.user) self.book = Book(name='Test') db.session.add(self.user) db.session.add(self.book) db.session.commit() self.ratings_len = 5 self.ratings = [ Rating(user_id=self.user.id, book_id=self.book.id, value=randint(1, 5)) for _ in range(self.ratings_len) ] db.session.add_all(self.ratings) db.session.commit()
def create_new_user(data): user = User.query.filter_by(email=data['email']).first() if not user: new_user = User(email=data['email'], last_name=data['last_name'], name=data['name'], password=data['password'], public_id=str(uuid.uuid4()), registered_on=datetime.datetime.utcnow()) save_changes(new_user) return generate_token(new_user) else: response_object = { 'status': 'error', 'message': 'User already exists, Please log in' } return response_object, 409
def test_get_user_polls(self): user_1 = User(fb_id='123', email=None, name='Jake') poll_1_date = datetime.datetime(2019, 12, 5, 4, 10, 12, 400736) poll_2_date = datetime.datetime(2019, 12, 5, 4, 10, 12, 402306) poll_1 = Poll(owner_id=1, prompt="test1", form_type="multChoice", resp_struct=None, created_date=poll_1_date) poll_2 = Poll(owner_id=1, prompt="test2", form_type="multChoice", resp_struct=None, created_date=poll_2_date) db.session.add(user_1) db.session.add(poll_1) db.session.add(poll_2) db.session.commit() resp, status_code = poll_service.get_user_polls(1) expected = [{ 'id': 1, 'is_open': True, 'resp_struct': None, 'owner_id': 1, 'created_date': poll_1_date, 'prompt': 'test1', 'form_type': 'multChoice' }, { 'id': 2, 'is_open': True, 'resp_struct': None, 'owner_id': 1, 'created_date': poll_2_date, 'prompt': 'test2', 'form_type': 'multChoice' }] assert expected == resp assert status_code == 200
def logout_user(data): if data: auth_token = data.split(" ")[1] else: auth_token = '' if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): return save_token(token=auth_token) else: response_object = {'status': 'error', 'message': resp} return response_object, 401 else: response_object = { 'status': 'error', 'message': 'Provide a valid auth token.' } return response_object, 403
def setUp(self): super().setUp() self.user = User( email='*****@*****.**', password='******', registered_on=datetime.datetime.utcnow() ) self.writer = Writer( first_name='Test', last_name='Test' ) self.writer_books = [Book(name=f'Book{i}', authors=[self.writer]) for i in range(10)] db.session.add(self.user) db.session.add(self.writer) db.session.add_all(self.writer_books) db.session.commit() self.ratings = [Rating(user_id=self.user.id, book_id=book.id, value=randint(1, 5)) for book in self.writer_books] db.session.add_all(self.ratings) db.session.commit()
def logout_user(data): if data: auth_token = data.split(" ")[1] else: auth_token = '' if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): # mark the token as blacklisted # return save_token(token=auth_token) pass else: response_object = {'status': 'fail', 'message': resp} return response_object, 401 else: response_object = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return response_object, 403
def post(self, tribe: Tribe, body: dict, **_): """ POST /users/claim-token Creates a standard user, using authorization from the token provided Also links the user with a tribe obtained from the token. """ del body["token"] user = User.create(tribe_id=tribe.id, role=UserRoles.USER, **body) print(user) access, refresh = generate_jwt_keypair(user.id, tribe.id, user.role) return self.format_success( 200, { "user": user.dictionary, "tokens": { "access": access, "refresh": refresh } })
def logout_user(data): if data: auth_token = data.split(" ")[1] else: auth_token = "" if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): # mark the token as blacklisted # return save_token(token=auth_token) pass else: response_object = {"status": "fail", "message": resp} return response_object, 401 else: response_object = { "status": "fail", "message": "Provide a valid auth token.", } return response_object, 403
def save_new_user(data): try: access_token = data['accessToken'] debug_token_request = requests.get( current_app.config['DEBUG_TOKEN_URL'].format( access_token=access_token)) debug_token_json = debug_token_request.json() user_id = debug_token_json['data']['user_id'] user = User.query.filter_by(fb_id=user_id).first() # if user exists, just return new JWT if user: jwt = create_access_token(user.id, expires_delta=False) return dict(token=jwt), 201 user_details_request = requests.get( url=current_app.config['USER_DETAIL_URL'].format( access_token=access_token, user_id=user_id)) user_detail_json = user_details_request.json() name = user_detail_json['name'] email = None if 'email' not in user_detail_json else user_detail_json[ 'email'] fb_id = user_detail_json['id'] user = User(fb_id=fb_id, name=name, email=email) db.session.add(user) db.session.commit() jwt = create_access_token(user.id) return dict(token=jwt, expires_delta=False), 201 except Exception as e: raise ValueError(e) response_object = {'status': 'error', 'message': 'Internal Error'} return response_object, 500