Beispiel #1
0
    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))
Beispiel #2
0
def login():
    """
    User authentication method.
    ---
    description: Authenticate user with supplied credentials.
    parameters:
      - name: username
        in: formData
        type: string
        required: true
      - name: password
        in: formData
        type: string
        required: true
    responses:
      200:
        description: User successfully logged in.
      400:
        description: User login failed.
      401:
        description: Invalid username or password.
    tags:
        - authentication
    """
    try:
        username, password = check_request_json(['username', 'password'])
    except ValueError as err:
        return jsonify({'msg': str(err), 'status': 'error', 'code': 400}), 400

    user = UserModel.query.filter_by(username=username).first()
    payload = None
    if not user:
        payload = jsonify({
            'msg': 'Invalid username',
            'status': 'error',
            'code': 401
        }), 401
    elif not UserModel.verify_hash(password, user.password):
        payload = jsonify({
            'msg': 'Invalid password',
            'status': 'error',
            'code': 401
        }), 401

    if not payload:
        # Identity can be any data that is json serialisable
        access_token = create_access_token(identity=username, fresh=True)
        refresh_token = create_refresh_token(identity=username)
        payload = jsonify(access_token=access_token,
                          refresh_token=refresh_token,
                          msg='Successfully logged in',
                          status='ok',
                          code=200), 200
    return payload
    def test_create_jwt_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():
            identity_claim = 'sub'
            app.config['JWT_IDENTITY_CLAIM'] = identity_claim
            user = TestUser(username='******', roles=['bar', 'baz'])
            access_token = create_access_token(identity=user)
            refresh_token = create_refresh_token(identity=user)

            # Decode the tokens and make sure the values are set properly
            access_token_data = decode_jwt(access_token,
                                           app.secret_key,
                                           app.config['JWT_ALGORITHM'],
                                           csrf=False,
                                           identity_claim=identity_claim)
            refresh_token_data = decode_jwt(refresh_token,
                                            app.secret_key,
                                            app.config['JWT_ALGORITHM'],
                                            csrf=False,
                                            identity_claim=identity_claim)
            self.assertEqual(access_token_data[identity_claim], 'foo')
            self.assertEqual(access_token_data['user_claims']['roles'],
                             ['bar', 'baz'])
            self.assertEqual(refresh_token_data[identity_claim], 'foo')
def test_refresh_token_route_updates_user_last_connection_date(client):
    data = {
        "identifier": "*****@*****.**",
        "password": users_factories.DEFAULT_PASSWORD
    }
    user = users_factories.UserFactory(email=data["identifier"],
                                       password=data["password"],
                                       lastConnectionDate=datetime(1990, 1, 1))

    refresh_token = create_refresh_token(identity=user.email)

    client.auth_header = {"Authorization": f"Bearer {refresh_token}"}
    refresh_response = client.post("/native/v1/refresh_access_token")
    assert refresh_response.status_code == 200

    assert user.lastConnectionDate == datetime(2020, 3, 15)
    assert len(sendinblue_testing.sendinblue_requests) == 1
Beispiel #5
0
    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
Beispiel #6
0
    def post(self):
        req_data = request.get_json() or None

        if req_data is None:
            return resp_data_invalid_err('Users', [])

        try:
            user = User.objects.get(username=req_data['username'])
            if checkpw(req_data['password'].encode('utf-8'),
                       user.password.encode('utf-8')) is False:
                return resp_invalid_credentials_err('Users')
            if not user.active:
                return resp_not_active_err('Users', user.username)
            if user and checkpw(req_data['password'].encode('utf-8'),
                                user.password.encode('utf-8')):
                expires = datetime.timedelta(seconds=3600)
                access_token = create_access_token(identity=user.guid,
                                                   fresh=True,
                                                   expires_delta=expires)
                refresh_token = create_refresh_token(user.guid)
                return {
                    'access_token': access_token,
                    'refresh_token': refresh_token
                }, 200
            return resp_invalid_credentials_err('Users')

        except DoesNotExist:
            return resp_does_not_exist_err('Users', req_data['username'])

        except Exception as e:
            return resp_exception_err('Users', e.__str__())


# class TokenRefresh(Resource):
#     @jwt_refresh_token_required
#     def post (self):
#         current_user = get_jwt_identity()
#         new_token = create_access_token(identity=current_user, fresh=False)
#         return {'access_token': new_token}, 200