Exemplo n.º 1
0
def login():
    """
    Обработчик POST-запроса на авторизацию пользователя.
    :return: response
    """
    request_json = request.json
    email = request_json.get('email')
    password = request_json.get('password')
    with db.connection as con:
        service = AuthService(con)
        # Попытка авторизации в роли пользователя
        try:
            account_id = service.login(email, password)
        except AuthorizationFailedError:
            return '', 401
        else:
            session['account_id'] = account_id
            # Попытка авторизации в роли продавца
            try:
                seller_id = service.get_seller(account_id)
            except SellerDoesNotExistError:
                pass
            else:
                session['seller_id'] = seller_id
            return '', 200
Exemplo n.º 2
0
 def setUp(self):
     self.session_mock = Mock()
     self.token_secret = 'secret'
     self.alg = 'HS256'
     self.ttl = 3600
     self.test_instance = AuthService(logger, self.session_mock,
                                      self.token_secret, self.alg, self.ttl)
Exemplo n.º 3
0
def login():
    data = request.get_json()
    auth_service = AuthService()
    try:
        auth_service.login(data['email'], data['password'])
    except (UserNotFound, InvalidCredentials) as e:
        return json_response.unauthorized()
    return json_response.success({"result": "success"})
Exemplo n.º 4
0
def register():
    data = request.get_json()
    auth_service = AuthService()
    try:
        user = auth_service.register(data)
    except EmailAlreadyExist:
        return json_response.conflict()
    return json_response.success(user)
Exemplo n.º 5
0
    def wrapper(*args, **kwargs):
        auth_service = AuthService()
        user_id = auth_service.get_auth_user_id()

        if user_id is None:
            return json_response.unauthorized()

        user = auth_service.model.get_by_id(user_id)

        if user is None:
            return json_response.unauthorized()

        return func(*args, **kwargs, user=user)
Exemplo n.º 6
0
def login():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        auth_service = AuthService()
        login_result = auth_service.login({'email': email, 'password': password})
        if login_result['success']:
            user = login_result['user']
            #login_user(user, remember=True) #https://flask-login.readthedocs.io/en/latest/#remember-me
            user_service = UserService()
            user_service.login_user(user)
            return redirect(url_for('.get_user', user_id=user.id))
        return render_template("login.html", invalid_credentials=True)
    return render_template("login.html")
Exemplo n.º 7
0
def login():
    """ Обработка аутентификации пользователя """
    try:
        auth_data = AuthSchema().load(request.json)
    except ValidationError as error:
        return jsonify(error.messages), 400
    else:
        with db.connection as con:
            service = AuthService(con)
            try:
                session['account_id'] = service.login_user(auth_data)
            except PermissionError:
                return '', 403
        return '', 200
Exemplo n.º 8
0
def login():
    email = request.form.get('email', '')
    password = request.form.get('password', '')
    remember = True if request.form.get('remember') else False
    if not email.strip() or not password.strip(
    ) or not AuthService.validate_email(email):
        return ResponseDto(status=-1, msg='Data Incomplete/Invalid.').to_json()

    response = AuthService.login(email=email,
                                 password=password,
                                 remember=remember)
    if not response['value']:
        return ResponseDto(status=-1, msg=response['error']).to_json()
    return ResponseDto(status=0, msg=response['msg'],
                       result=response['data']).to_json()
Exemplo n.º 9
0
def get_user():
    page, per_page, offset = get_page_items()
    paginate = request.args.get('paginate', 'true').lower()
    paginate = False if paginate == 'false' else True
    user_ids = request.args.get('userIds', None)
    if user_ids:
        user_ids = [
            user_id for user_id in user_ids.split(',')
            if ObjectId.is_valid(user_id)
        ]
        users = UserService.get_users(user_ids=user_ids, paginate=False)
    else:
        q = request.args.get('q', '')
        emails = [
            email for email in request.args.get('emails', '').split(',')
            if AuthService.validate_email(email)
        ]
        users = UserService.get_users(query=q,
                                      page=page,
                                      limit=per_page,
                                      emails=emails,
                                      paginate=paginate)

    if users.get('data'):
        return ResponseDto(status=0, result=users).to_json()
    return ResponseDto(status=-1, msg='No User Found.').to_json()
def login():
    request_json = request.json
    email = request_json.get('email')
    password = request_json.get('password')
    if not email or not password:
        return '', 404

    with db.connection as con:
        service = AuthService(con)
        user = service.get_user(email)
        if not user:
            return '', 401
        if not check_password_hash(user['password'], password):
            return '', 401
        session['user_id'] = user['id']
        return '', 200
Exemplo n.º 11
0
async def auth_user(request):
    """
    :param request:
    :return: json(user_id, token)
    """
    try:
        user_data = AuthUserSchema.parse_obj(request.json)
    except ValidationError as e:
        return json((e.errors(), 400))
    service = AuthService()
    try:
        user_id, token = service.authenticate(user_data)
        return json({"user_id": user_id, "token": token},
                    200)
    except IncorrectlyLoginPassExcept:
        return json({"answer": "Password or username incorrectly"}, 400)
Exemplo n.º 12
0
async def create_offer(request):
    """
    Create new offer
    из-за требования user_id в теле запроса, код вышел запутанный
    приходется проверять user_id в токене с user_id в теле запроса
    :param request:
    :return: json offer
    """
    try:
        offer_data = CreateOfferSchema.parse_obj(request.json)
    except ValidationError as e:
        return json(e.errors(), 422)

    try:
        is_current_user = AuthService().indentify(request, "user_id")
    except:
        return json({"answer": "not a valid token"}, 401)
    if not is_current_user:
        return json({"answer": "not a valid token"}, 401)
    try:
        user = UserService().get_user_by_id(offer_data.user_id)
    except UserNotFound as e:
        return json({"answer": "user with this id does not exist"}, 400)
    offer_serivce = OfferService()
    new_offer = offer_serivce.create_offer(offer_data)
    return json(new_offer.as_dict(), 201)
Exemplo n.º 13
0
    def post(self):
        request_json = request.json

        try:
            auth = scheme.auth.auth_schema.load(request_json)
        except ValidationError as ValEr:
            return jsonify(ValEr.messages), 400

        auth_service = AuthService(db.connection)
        try:
            auth_user = auth_service.authorization(auth)
        except UserNotFoundOrInvalidData as user_er:
            return user_er.message, 404
        session['user_id'] = auth_user
        session.modified = True

        return jsonify({'answer': 'Вы вошли в аккаунт'}), 200
Exemplo n.º 14
0
    def post(self):
        """
        accepts user data and authorizes him
        :return: answer and status
        """
        request_json = request.json
        try:
            auth = scheme.auth.auth_schema.load(request_json)
        except ValidationError as ValEr:
            return jsonify(ValEr.messages), 400

        auth_service = AuthService(db.connection)
        try:
            auth_user = auth_service.authorization(auth)
        except UserNotFoundOrInvalidData as user_er:
            return user_er.message, 404
        session['user_id'] = auth_user
        return {"answer": "Вы вошли в аккаунт"}, 200
Exemplo n.º 15
0
def register():
    email = request.form.get('email', '')
    name = request.form.get('name', '')
    password = request.form.get('password', '')
    confirm = request.form.get('confirmPassword', '')
    if not email.strip() or not password.strip() or not name.strip() or not confirm.strip() or password != confirm\
            or not AuthService.validate_email(email):
        return ResponseDto(
            status=-1,
            msg='Data Incomplete/Invalid or Password Mismatch').to_json()

    response = AuthService.register_user(email=email,
                                         name=name,
                                         password=password)
    if not response['value']:
        return ResponseDto(status=-1, msg=response['error']).to_json()
    return ResponseDto(status=0, msg=response['msg'],
                       result=response['data']).to_json()
Exemplo n.º 16
0
def profile(user):
    auth_service = AuthService()
    user = auth_service.get_user_profile(user['id'])
    return json_response.success(user)
Exemplo n.º 17
0
class TestAuthService(unittest.TestCase):
    def setUp(self):
        self.session_mock = Mock()
        self.token_secret = 'secret'
        self.alg = 'HS256'
        self.ttl = 3600
        self.test_instance = AuthService(logger, self.session_mock,
                                         self.token_secret, self.alg, self.ttl)

    def test_decode_jwt(self):
        # Happy path
        _user = test.generate_user()
        test_jwt = self.test_instance.encode_jwt(_user)

        decoded_jwt, err = self.test_instance.decode_jwt(test_jwt)

        self.assertEqual(decoded_jwt['uid'], str(_user.id))
        self.assertEqual(decoded_jwt['role'], _user.role)

        # Invalid jwt
        decoded_jwt, err = self.test_instance.decode_jwt('not-a-valid-jwt')
        self.assertIsNone(decoded_jwt)
        self.assertIsNotNone(err)

    def test_encode_jwt(self):
        # Happy path
        _user = test.generate_user()
        jwt = self.test_instance.encode_jwt(_user)

        decoded_jwt, err = self.test_instance.decode_jwt(jwt)
        self.assertIsNone(err)
        self.assertEqual(decoded_jwt['uid'], str(_user.id))
        self.assertEqual(decoded_jwt['role'], _user.role)

        # Invalid arg should return None
        result = self.test_instance.encode_jwt('not a user object')
        self.assertIsNone(result)

    def test_validate_login(self):
        # Happy path
        _user = test.generate_user(password='******')
        self.session_mock.return_value.query.return_value.filter.return_value.one_or_none.return_value = _user
        result = self.test_instance.validate_login(_user.username,
                                                   'my-password')
        self.assertIsNotNone(result)
        self.assertEqual(result.id, _user.id)

        # Invalid password
        self.session_mock.return_value.query.return_value.filter.return_value.one_or_none.return_value = _user
        result = self.test_instance.validate_login(_user.username,
                                                   'wrong-password')
        self.assertIsNone(result)

        # User does not exist
        self.session_mock.return_value.query.return_value.filter.return_value.one_or_none.return_value = None
        result = self.test_instance.validate_login(_user.username,
                                                   'wrong-password')
        self.assertIsNone(result)

    def test_authenticate_request(self):
        request_mock = Mock()
        _user = test.generate_user()
        valid_token = self.test_instance.encode_jwt(_user)

        # Happy path
        request_mock.headers.get.return_value = 'Bearer ' + valid_token
        jwt_payload, err = self.test_instance.authenticate_request(
            request_mock)
        request_mock.headers.get.assert_called_with('Authorization')

        self.assertIsNone(err)
        self.assertEqual(jwt_payload['uid'], str(_user.id))
        self.assertEqual(jwt_payload['role'], _user.role)

        # Invalid bearer token
        request_mock.headers.get.return_value = 'Bearer ' + 'invlid-token'
        jwt_payload, err = self.test_instance.authenticate_request(
            request_mock)
        request_mock.headers.get.assert_called_with('Authorization')

        self.assertIsNone(jwt_payload)
        self.assertIsNotNone(err)

        # Missing auth header
        request_mock.headers.get.return_value = None
        jwt_payload, err = self.test_instance.authenticate_request(
            request_mock)
        request_mock.headers.get.assert_called_with('Authorization')

        self.assertIsNone(jwt_payload)
        self.assertIsNotNone(err)
Exemplo n.º 18
0
 def provide_auth_service(self, config: ConfigHelper) -> AuthService:
     return AuthService(config)
Exemplo n.º 19
0
def logout():
    auth_service = AuthService()
    auth_service.logout()
    return json_response.success()
Exemplo n.º 20
0
def login(form_data: OAuth2PasswordRequestForm = Depends(),
          service: AuthService = Depends()):
    return service.login(form_data.username, form_data.password)
Exemplo n.º 21
0
 def auth_service(self):
     return AuthService(self.logger, self.database_engine,
                        self.config['TOKEN_SECRET'],
                        self.config['TOKEN_ALG'], self.config['TOKEN_TTL'])
Exemplo n.º 22
0
 def auth_service(self):
     return AuthService(self.logger, self.Session,
                        self.config['TOKEN_SECRET'],
                        self.config['TOKEN_ALG'], self.config['TOKEN_TTL'])
Exemplo n.º 23
0
def registration(user_data: UserCreationSchema,
                 service: AuthService = Depends()):
    return service.registration(user_data)
Exemplo n.º 24
0
CustomBase = base_provider.get_base()
models = model_factory(CustomBase)  # API routes (blueprints) dependency
schema = schema_factory(mysql_session,
                        models)  # API routes (blueprints) dependency

redis_pw = config["cie.redis.password"]
redis_host = config["cie.redis.host"]
red = redis.StrictRedis(host=redis_host, password=redis_pw, port=6379)
redis_store = RedisStore(red)

module_service = ModuleService(models)
user_service = UserService(models)
student_session_service = StudentSessionService(red, models)

publish_message = create_message_publisher(red, "command")

websocket_manager = WebsocketManager(red)
rc_service = RocketChatService()

aula_actor = AulaActor(websocket_manager, rc_service, models)
aula_service = AulaDataService(models, schema, on_change=aula_actor.emit_event)
aula_endpoints = create_aula_endpoints(aula_service, websocket_manager)
auth_service = AuthService()
payment_api = create_payment_api(auth_service, module_service, user_service)
blueprints = [payment_api, aula_endpoints]

app = create_main_api(publish_message, module_service, student_session_service,
                      user_service, mysql_session, models, schema,
                      aula_service, rc_service, blueprints, websocket_manager,
                      send_mail)
Exemplo n.º 25
0
def load_user(user_id):
    return AuthService.get_session_user_by_email(user_id)
Exemplo n.º 26
0
def logout():
    AuthService.logout()
    return ResponseDto(status=0, msg='Logout Successful').to_json()