def post(): try: data = Login.parser.parse_args() if data['email']: user = UserModel.find_by_email(data['email']) else: user = UserModel.find_by_phone(data['phoneNumber']) pass if data['lastIPConnection'] and DeviceModel.find_by_ip(data['lastIPConnection']) is None \ and user is not None: user.lastIPConnection = data['lastIPConnection'] if (data['lastIPConnection'] is not None) \ else user.lastIPConnection user.save_to_db() device = DeviceModel(user_id=user.id, ip=data['lastIPConnection'], created_at=datetime.now().strftime('%Y-%m-%d %H:%M:%S')) device.save_to_db() if user and user.check_password(data['password']): access_token = create_access_token(identity=user.json(is_long=False), fresh=True) refresh_token = create_refresh_token(identity=user.json(is_long=False)) return BaseResponse.ok_response('Login successfully.', { 'accessToken': access_token, 'refreshToken': refresh_token, 'user': user.json(is_long=False) }) return BaseResponse.bad_request_response('Incorrect credentials.', {}) except Exception as e: return BaseResponse.server_error_response(str(e))
def get(self): parser = reqparse.RequestParser() parser.add_argument('username', location='args', required=True) parser.add_argument('password', location='args', required=True) args = parser.parse_args() qry_client = UserModel.query.filter_by( username=args['username']).first() result = {"message": {}, "data": {}} if qry_client is not None: client_salt = qry_client.salt encoded = ('%s%s' % (args['password'], client_salt)).encode('utf-8') hash_pass = hashlib.sha512(encoded).hexdigest() if hash_pass == qry_client.password: qry_client = marshal(qry_client, UserModel.jwt_client_fields) token = create_access_token(identity=args['username'], user_claims=qry_client) result["message"]["en"] = "Login success" result["message"]["id"] = "Login sukses" result["data"]["token"] = token return result, 200 else: result["message"]["en"] = "Wrong password" result["message"]["id"] = "Password salah" return result, 401 result["message"]["en"] = "User not found" result["message"]["id"] = "User tidak ditemukan" return result, 404
def test_change_password_failures(app): new_password = "******" user = users_factories.UserFactory() access_token = create_access_token(identity=user.email) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.post( "/native/v1/change_password", json={"currentPassword": "******", "newPassword": new_password}, ) assert response.status_code == 400 assert response.json["code"] == "INVALID_PASSWORD" response = test_client.post( "/native/v1/change_password", json={"currentPassword": users_factories.DEFAULT_PASSWORD, "newPassword": "******"}, ) assert response.status_code == 400 assert response.json["code"] == "WEAK_PASSWORD" user = find_user_by_id(user.id) assert user.password == hash_password(users_factories.DEFAULT_PASSWORD)
def test_toggle_visibility(self, app): user = users_factories.BeneficiaryGrant18Factory(email=self.identifier) access_token = create_access_token(identity=self.identifier) booking = booking_factories.IndividualBookingFactory( individualBooking__user=user, displayAsEnded=None) booking_id = booking.id test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.post( f"/native/v1/bookings/{booking_id}/toggle_display", json={"ended": True}) assert response.status_code == 204 db.session.refresh(booking) assert booking.displayAsEnded response = test_client.post( f"/native/v1/bookings/{booking_id}/toggle_display", json={"ended": False}) assert response.status_code == 204 db.session.refresh(booking) assert not booking.displayAsEnded
def test_change_password_failures(client): new_password = "******" user = users_factories.UserFactory() access_token = create_access_token(identity=user.email) client.auth_header = {"Authorization": f"Bearer {access_token}"} response = client.post( "/native/v1/change_password", json={ "currentPassword": "******", "newPassword": new_password }, ) assert response.status_code == 400 assert response.json["code"] == "INVALID_PASSWORD" response = client.post( "/native/v1/change_password", json={ "currentPassword": users_factories.DEFAULT_PASSWORD, "newPassword": "******" }, ) assert response.status_code == 400 assert response.json["code"] == "WEAK_PASSWORD" db.session.refresh(user) assert user.password == crypto.hash_password( users_factories.DEFAULT_PASSWORD)
def test_create_access_token_with_object(self): # Complex object to test building a JWT from. Normally if you are using # this functionality, this is something that would be retrieved from # disk somewhere (think sqlalchemy) class TestUser: def __init__(self, username, roles): self.username = username self.roles = roles # Setup the flask stuff app = Flask(__name__) app.secret_key = 'super=secret' app.config['JWT_ALGORITHM'] = 'HS256' jwt = JWTManager(app) @jwt.user_claims_loader def custom_claims(user): return {'roles': user.roles} @jwt.user_identity_loader def user_identity_lookup(user): return user.username # Create the token using the complex object with app.test_request_context(): user = TestUser(username='******', roles=['bar', 'baz']) token = create_access_token(identity=user) # Decode the token and make sure the values are set properly token_data = _decode_jwt(token, app.secret_key, app.config['JWT_ALGORITHM']) self.assertEqual(token_data['identity'], 'foo') self.assertEqual(token_data['user_claims']['roles'], ['bar', 'baz'])
def teacher_login(): email = request.json.get("email", None) password = request.json.get("password", None) if not email: return jsonify({"msg": "Email is required"}), 400 if not password: return jsonify({"msg": "Password is required"}), 400 teacher = TeacherUser.query.filter_by(email=email).first() if not teacher: return jsonify({"msg": "Email/password incorrect"}), 400 if not bcrypt.check_password_hash(teacher.password, password): return jsonify({"msg": "Email/password incorrect"}), 400 expires = timedelta(days=3) data = { "access_token": create_access_token(identity=teacher.email, expires_delta=expires), "teacher": teacher.serialize() } return jsonify({"success": "Log In Successfully", "data": data}), 200
def create_user_and_test_client(app, **kwargs): user = users_factories.UserFactory(**kwargs) access_token = create_access_token(identity=user.email) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} return user, test_client
def test_no_stock_found(self, app): users_factories.UserFactory(email=self.identifier) access_token = create_access_token(identity=self.identifier) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.post("/native/v1/book_offer", json={"stockId": 404, "quantity": 1}) assert response.status_code == 404
def test_get_id_check_token_not_eligible(self, app): user = users_factories.UserFactory(dateOfBirth=datetime(2001, 1, 1)) access_token = create_access_token(identity=user.email) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.get("/native/v1/id_check_token") assert response.status_code == 200 assert not response.json["token"]
def test_educonnect_login_no_redirect(self, client): users_factories.UserFactory(email=self.email) access_token = create_access_token(identity=self.email) client.auth_header = {"Authorization": f"Bearer {access_token}"} response = client.get("/saml/educonnect/login?redirect=false") assert response.status_code == 204 assert response.headers["educonnect-redirect"].startswith( "https://pr4.educonnect.phm.education.gouv.fr/idp") assert response.headers[ "Access-Control-Expose-Headers"] == "educonnect-redirect"
def test_cancel_others_booking(self, app): users_factories.BeneficiaryGrant18Factory(email=self.identifier) booking = booking_factories.IndividualBookingFactory() access_token = create_access_token(identity=self.identifier) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.post(f"/native/v1/bookings/{booking.id}/cancel") assert response.status_code == 404
def test_ログインすればユーザー情報が見れる(self): user1, _ = self.addSampleUser() token: str = create_access_token(user1) response = self.app.get( "users/2", headers={"Authorization": f"Bearer {token}"}, ) assert response.status_code == 200 data = json.loads(response.get_data()) assert data["result"] is True assert data["data"]["name"] == "テストユーザー2"
def test_get_user_profile_not_active(self, app): users_factories.UserFactory(email=self.identifier, isActive=False) access_token = create_access_token(identity=self.identifier) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.get("/native/v1/me") assert response.status_code == 403 assert response.json["email"] == ["Utilisateur introuvable"]
def test_insufficient_credit(self, app): users_factories.UserFactory(email=self.identifier) stock = StockFactory(price=501) access_token = create_access_token(identity=self.identifier) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.post("/native/v1/book_offer", json={"stockId": stock.id, "quantity": 1}) assert response.status_code == 400 assert response.json["code"] == "INSUFFICIENT_CREDIT"
def refresh_expired_token(response): try: exp_timestamp = get_raw_jwt()['exp'] now = datetime.now(timezone.utc) target_timestam = datetime.timestamp(now + timedelta(minutes=30)) if target_timestam > exp_timestamp: access_token = create_access_token(identity=get_jwt_identity()) set_access_cookies(response=response, encoded_access_token=access_token) return response except: return response
def test_already_booked(self, app): user = users_factories.UserFactory(email=self.identifier) booking = BookingFactory(user=user) access_token = create_access_token(identity=self.identifier) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.post("/native/v1/book_offer", json={"stockId": booking.stock.id, "quantity": 1}) assert response.status_code == 400 assert response.json["code"] == "ALREADY_BOOKED"
def post(self): args = login_parser.parse_args() username = args['username'] password = args['password'] user = User.find_by_username(username=username) if not user or not user.check_password(password): return max_res('',401,'Invalid username or password') # Identity can be any data that is json serializable expires = datetime.timedelta(days=10) access_token = create_access_token(user.id, expires_delta=expires) return max_res({'token':access_token}), 200
def test_get_educonnect_login_production(self, client, app): user = users_factories.UserFactory(email=self.email) access_token = create_access_token(identity=self.email) client.auth_header = {"Authorization": f"Bearer {access_token}"} response = client.get("/saml/educonnect/login") assert response.status_code == 302 assert response.location.startswith( "https://educonnect.education.gouv.fr/idp") assert len( app.redis_client.keys(f"{self.request_id_key_prefix}*")) == 1 request_id = app.redis_client.keys(f"{self.request_id_key_prefix}*")[0] assert int(app.redis_client.get(request_id)) == user.id
def test_book_offer(self, app): stock = StockFactory() user = users_factories.UserFactory(email=self.identifier) access_token = create_access_token(identity=self.identifier) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.post("/native/v1/book_offer", json={"stockId": stock.id, "quantity": 1}) assert response.status_code == 204 booking = Booking.query.filter(Booking.stockId == stock.id).first() assert booking.userId == user.id
def test_integration_toggle_visibility(self, app): user = users_factories.BeneficiaryGrant18Factory(email=self.identifier) access_token = create_access_token(identity=self.identifier) stock = StockWithActivationCodesFactory() activation_code = stock.activationCodes[0] booking = booking_factories.UsedIndividualBookingFactory( individualBooking__user=user, displayAsEnded=None, dateUsed=datetime.now(), stock=stock, activationCode=activation_code, ) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.get("/native/v1/bookings") assert response.status_code == 200 assert [b["id"] for b in response.json["ongoing_bookings"]] == [booking.id] assert [b["id"] for b in response.json["ended_bookings"]] == [] response = test_client.post( f"/native/v1/bookings/{booking.id}/toggle_display", json={"ended": True}) assert response.status_code == 204 response = test_client.get("/native/v1/bookings") assert response.status_code == 200 assert [b["id"] for b in response.json["ongoing_bookings"]] == [] assert [b["id"] for b in response.json["ended_bookings"]] == [booking.id] response = test_client.post( f"/native/v1/bookings/{booking.id}/toggle_display", json={"ended": False}) assert response.status_code == 204 response = test_client.get("/native/v1/bookings") assert response.status_code == 200 assert [b["id"] for b in response.json["ongoing_bookings"]] == [booking.id] assert [b["id"] for b in response.json["ended_bookings"]] == []
def test_get_user_profile(self, app): first_name = "Gaëtan" users_factories.UserFactory(email=self.identifier, firstName=first_name) access_token = create_access_token(identity=self.identifier) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.get("/native/v1/me") assert response.status_code == 200 assert response.json["email"] == self.identifier assert response.json["firstName"] == first_name assert response.json["isBeneficiary"]
def connect_to_educonnect(self, client, app): user = users_factories.UserFactory(email=self.email) access_token = create_access_token(identity=self.email) client.auth_header = {"Authorization": f"Bearer {access_token}"} # Calling /saml/educonnect/login redirects to educonnect login response = client.get("/saml/educonnect/login") assert response.status_code == 302 assert response.location.startswith( "https://pr4.educonnect.phm.education.gouv.fr/idp") prefixed_request_id = app.redis_client.keys( f"{self.request_id_key_prefix}*")[0] request_id = prefixed_request_id[len(self.request_id_key_prefix):] return user, request_id
def login(self, params: dict) -> dict: if not params: abort(400, code_error=400, error='No username or password to authenticate') user_to_login = self.repositorie.filter_by_email(email=params.get('email')) if not user_to_login: abort(400, code_error=400, error='username does not exist') if not user_to_login.password == params.get('password'): abort(401, code_error=401, error='Username or password incorrect') access_token = create_access_token(identity=user_to_login.id) expires = datetime.timestamp(datetime.now() + timedelta(days=1)) return {'user': user_to_login.email, 'access_token': access_token, 'expires': expires}
def post(self): args = login_parser.parse_args() email = args['email'] password = args['password'] user = User.find_by_email(email=email) if not user or not user.check_password(password): return max_res('', 401, 'Invalid email or password') user_j = {'name': user.name, 'email': user.email, 'id': user.id} # Identity can be any data that is json serializable expires = datetime.timedelta(days=10) access_token = create_access_token(user.id, expires_delta=expires) return max_res({'token': access_token, 'user': user_j}), 200
def test_cancel_booking(self, app): user = users_factories.BeneficiaryGrant18Factory(email=self.identifier) booking = booking_factories.IndividualBookingFactory( individualBooking__user=user) access_token = create_access_token(identity=self.identifier) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.post(f"/native/v1/bookings/{booking.id}/cancel") assert response.status_code == 204 booking = Booking.query.get(booking.id) assert booking.isCancelled assert booking.cancellationReason == BookingCancellationReasons.BENEFICIARY
def test_cancel_confirmed_booking(self, app): user = users_factories.BeneficiaryGrant18Factory(email=self.identifier) booking = booking_factories.IndividualBookingFactory( individualBooking__user=user, cancellation_limit_date=datetime.now() - timedelta(days=1)) access_token = create_access_token(identity=self.identifier) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.post(f"/native/v1/bookings/{booking.id}/cancel") assert response.status_code == 400 assert response.json == { "code": "CONFIRMED_BOOKING", "message": "La date limite d'annulation est dépassée.", }
def test_get_user_profile_empty_first_name(self, app): users_factories.UserFactory(email=self.identifier, firstName="", isBeneficiary=False, publicName=VOID_PUBLIC_NAME) access_token = create_access_token(identity=self.identifier) test_client = TestClient(app.test_client()) test_client.auth_header = {"Authorization": f"Bearer {access_token}"} response = test_client.get("/native/v1/me") assert response.status_code == 200 assert response.json["email"] == self.identifier assert response.json["firstName"] is None assert response.json["pseudo"] is None assert not response.json["isBeneficiary"]
def post(cls): # Get data from parser data = cls.parser.parse_args() # Find admin from db admin = adm.AdminModel.find_by_username(data["username"]) # Check password if admin and admin.password == utils.hash(data["password"]): # Create access token access_token = create_access_token(identity=admin.id, fresh=True) # Create refresh token refresh_token = create_refresh_token(admin.id) return Succ.SUCCESS_AUTHENTICATED(access_token, refresh_token) return Err.ERROR_INVALID_CREDS
def test_change_password_success(client): new_password = "******" user = users_factories.UserFactory() access_token = create_access_token(identity=user.email) client.auth_header = {"Authorization": f"Bearer {access_token}"} response = client.post( "/native/v1/change_password", json={ "currentPassword": users_factories.DEFAULT_PASSWORD, "newPassword": new_password }, ) assert response.status_code == 204 db.session.refresh(user) assert user.password == crypto.hash_password(new_password)