def setup_function(function): db.drop_all_tables(with_all_data=True) db.create_tables() ph = PasswordHasher() with db_session: editor = Group(id=3, name="Editor") moderator = Group(id=2, name="Moderator") admin = Group(id=1, name="Admin") User( id=1, nickname="Leader", email="*****@*****.**", password=ph.hash("test1"), groups=[admin], ) User( id=2, nickname="Mary", email="*****@*****.**", password=ph.hash("test2"), groups=[moderator], ) User( id=3, nickname="Jürgen", email="*****@*****.**", password=ph.hash("test3"), groups=[editor], )
def register_user(): """ Route for creating a new user """ data = request.get_json() username = data.get('username') password = data.get('password') if not username or not password: return jsonify({ 'status': 400, 'status_message': 'Invalid or incomplete request data' }) try: encrypted_password = bcrypt.hashpw(bytes(password, 'utf-8'), bcrypt.gensalt()) newUser = User(public_id=str(uuid.uuid4()), username=username, password=encrypted_password, date_created=datetime.datetime.now()) db.session.add(newUser) db.session.commit() return jsonify({ 'status': 200, 'status_message': 'New user successfuly created' }) except Exception as error: return jsonify({'status': 400, 'status_message': 'Duplicate Entry'})
def auth(email, password): """Log a user in. POST { username: String, password: String } -> 200 { success: Boolean, session: String } -> 400 PUT { session } -> 200 # Session key valid -> 400 # Session key invalid """ try: # Get the user user = User.getBy(db.session, email=email) except NotFound: raise HttpException(403, "Account not found.", { "email": email }) session = user.login(password) db.session.add(user) db.session.commit() db.session.refresh(user) return respond({ "key": session.key, "user": user })
def test_delete_user(): c = Client(App()) response = c.post( "/login", json.dumps({"email": "*****@*****.**", "password": "******"}) ) headers = {"Authorization": response.headers["Authorization"]} with db_session: assert User.exists(nickname="Mary") c.delete("/users/2", headers=headers) with db_session: assert not User.exists(nickname="Mary")
def register(): req = request.get_json() if not exists(u.id for u in User if u.username == req['display_name']): now = datetime.datetime.now() User(username=req['display_name'], gender=req['gender'], avatar=req['avatar'], age=req['age'], user_id=now, password=req['password'], created_at=now) user = User.get(username=req['display_name']) return jsonify( success=True, user=user.describe(), access_token=create_access_token(identity=user.describe())) else: return jsonify(success=False, err='INVAILD_USERNAME')
def login(): req = request.get_json(force=True) user = User.get(username=req['display_name']) if not user: return jsonify(success=False, err="INVAILD_USER") if user.password == req['password']: return jsonify(success=True, user=user.describe(), access_token=create_access_token(identity=user.id)) else: return jsonify(success=False, err="INVAILD_PASSWORD")
def add_message(): current_id = get_jwt_identity() user = User.get(id=current_id) if not user: return (err='INVALID_AUTHORIZATION'), 401 req = request.get_json() now = datetime.datetime.now() Notice( title=req['title'], region=req['region'], price=req['price'], user=user, created_at=now ) return jsonify(success=False)
def create_user(self, username, password): response = Response("register") if username.strip() == "" or password.strip() == "": self.socket.request.sendall( response(False, err="username or password cannot be empty")) return user = User(username=username, password=password) self.db.add(user) try: self.db.commit() self.socket.request.sendall(response(username=user.username)) except Exception as e: self.db.rollback() self.socket.request.sendall(response(False, err=str(e)))
def test_refresh_token(): app = App() c = Client(app) response = c.post( "/login", json.dumps({"email": "*****@*****.**", "password": "******"}) ) headers = {"Authorization": response.headers["Authorization"]} response = c.get("/refresh", headers=headers) jwtauth_settings = app.settings.jwtauth.__dict__.copy() identity_policy = JWTIdentityPolicy(**jwtauth_settings) authtype, token = response.headers["Authorization"].split(" ", 1) claims_set_decoded = identity_policy.decode_jwt(token) assert identity_policy.get_userid(claims_set_decoded) == "*****@*****.**" with db_session: # set new nonce to invalid current tokens for this user User[2].nonce = uuid4().hex response = c.get("/refresh", headers=headers, status=403) assert response.json == {"validationError": "Could not refresh your token"} now = timegm(datetime.utcnow().utctimetuple()) with db_session: nonce = User.get(email="*****@*****.**").nonce claims_set = { "sub": "*****@*****.**", "uid": "/users/2", "refresh_until": now - 3, "nonce": nonce, "exp": now + 3, } token = identity_policy.encode_jwt(claims_set) headers = {"Authorization": "JWT " + token} response = c.get("/refresh", headers=headers, status=403) assert response.json == {"validationError": "Your session has expired"}
def test_user_institution_extraction(): instit = User.extract_domain("*****@*****.**") assert instit == "nuigalway.ie", "Institution domain incorrect."
def refresh(): current_id = get_jwt_identity() user = User.get(id=current_id) if not user: return jsonify(err='INVALID_AUTHORIZATION'), 401 return jsonify(user=user.describe()), 200
def add_user(self, username, email, password): session = self.make_session() user_object = User(username=username, email=email, password=password) session.add(user_object) session.commit()
def identity(payload): user_id = payload['identity'] return User.find_by_id(user_id)
def authenicate(username, password): user = User.find_by_username(username) return user
def test_add_user(smtp): assert len(smtp.outbox) == 0 c = Client(App(), extra_environ=dict(REMOTE_ADDR="127.0.0.1")) new_user_json = json.dumps( {"nickname": "NewUser", "email": "*****@*****.**", "password": "******"} ) response = c.post("/users", new_user_json, status=201) with db_session: assert User.exists(nickname="NewUser") assert User.get(nickname="NewUser").register_ip == "127.0.0.1" assert len(smtp.outbox) == 1 message = smtp.outbox[0] assert message["subject"] == "Confirm Your Email Address" assert message["To"] == "*****@*****.**" response = c.post("/users", new_user_json, status=409) assert response.json == {"validationError": "Email already exists"} assert len(smtp.outbox) == 1 with db_session: new_editor_json = json.dumps( { "nickname": "NewEditor", "email": "*****@*****.**", "password": "******", "groups": ["Editor"], } ) c.post("/users", new_editor_json) assert User.exists(nickname="NewEditor") assert Group.get(name="Editor") in User.get(nickname="NewEditor").groups assert User.get(nickname="NewEditor").email == "*****@*****.**" assert len(smtp.outbox) == 2 message = smtp.outbox[1] assert message["subject"] == "Confirm Your Email Address" assert message["To"] == "*****@*****.**" new_user_json = json.dumps( { "nickname": "NewUser", "email": "*****@*****.**", "password": "******", } ) response = c.post("/users", new_user_json, status=422) assert response.json == {"email": ["Email could not be delivered"]} new_user_json = json.dumps( {"nickname": "NewUser", "email": "newuser@example", "password": "******"} ) response = c.post("/users", new_user_json, status=422) assert response.json == {"email": ["Not valid email"]} new_user_json = json.dumps( { "nickname": 123, "email": "*****@*****.**", "password": "******", } ) response = c.post("/users", new_user_json, status=422) assert response.json == {"nickname": ["must be of string type"]}