def add_user(username, email, password, roles=None): baseline = {'username': username, 'email': email, 'password': password} user = User(**baseline) if roles: user.roles = roles db.session.add(user) db.session.commit() return user
def post(self): # On a Post Request try: # We need these to return None to ensure entries are unique username = UserModel.query.filter_by( username=rp_api.payload['username']).first() email = UserModel.query.filter_by( email=rp_api.payload['email']).first() if not (username or email): user = UserModel.create(**rp_api.payload) # If we want to override the access key or refresh key lifespan access_lifespan = rp_api.payload.get('access_lifespan', None) refresh_lifespan = rp_api.payload.get('refresh_lifespan', None) auth_token = guard.encode_jwt_token( user, override_access_lifespan=access_lifespan, override_refresh_lifespan=refresh_lifespan, email=user.email, username=user.username, ) user.auth_token = auth_token return user, 201 if email: rp_api.abort(409, f"Email already exists: {email.email}") if username: rp_api.abort(409, f"Username already exists: {username.username}") except (exc.IntegrityError, ValueError) as e: db.session.rollback() rp_api.abort(400, e)
def get(self): # On a Get Request try: user = UserModel.get_by_id( record_id=flask_praetorian.current_user().id) return user, 200 except Exception as e: rp_api.abort(400, e)
def seed_db(): """Seeds the database.""" db.session.add( User(username='******', email='*****@*****.**', password='******')) db.session.commit()
def get(self, user_id): """Get single user details""" try: user = UserModel.get_by_id(record_id=user_id) if not user: rp_api.abort(404, f"User Not Found by Id {user_id}") return user, 200 except (exc.IntegrityError, ValueError): rp_api.abort(400)
def test_add_user_duplicate_email(self): add_user('testuser', '*****@*****.**', 'Downf0ryourRIGHTtoParty!') duplicate_user = User( username='******', email='*****@*****.**', password='******', ) db.session.add(duplicate_user) self.assertRaises(IntegrityError, db.session.commit)
def post(self): try: username = UserModel.query.filter_by( username=rp_api.payload['username']).first() email = UserModel.query.filter_by( email=rp_api.payload['email']).first() if not (username or email): user = UserModel.create(**rp_api.payload) return user, 201 if email: rp_api.abort( 409, f"Email already in use: {rp_api.payload['email']}") if username: rp_api.abort( 409, f"Username already in use: {rp_api.payload['username']}") rp_api.abort(409, "Invalid fields") except (exc.IntegrityError, ValueError) as e: db.session.rollback() rp_api.abort(400, e)