コード例 #1
0
    def post(self):
        '''Log in user'''
        try:
            # Get User-agent and ip address
            my_ip = request.environ.get('HTTP_X_FORWARDED_FOR')
            if my_ip is None:
                ip = request.environ['REMOTE_ADDR']
            else:
                ip = request.environ['HTTP_X_FORWARDED_FOR']

            if ip is None or str(ip) == '127.0.0.1'or str(ip) == '172.17.0.1':
                return{'message': 'This request has been rejected. Please use a recognised device'}, 403

            # Compute operating system and location
            device_operating_system = generate_device_data()
            if 'error' in device_operating_system.keys():
                return {'message': device_operating_system['error']}, 403
            device_os = device_operating_system['device_os']


            data = api.payload
            if not data:
                return {'message': 'No input data detected'}, 400

            email = data['email']
            this_user = UserModel.fetch_by_email(email)
            if this_user:
                if check_password_hash(this_user.password, data['password']):
                    # current_user = user_schema.dump(this_user) # This line would be used if we were outputing the user
                    user_id = this_user.id
                    # fetch User role
                    user_role = UserRoleModel.fetch_by_user_id(user_id)
                    # UserPrivilege.get_privileges(user_id = user_id, role= user_role.role)
                    # privileges = UserPrivilege.privileges
                    privileges = user_role.role.role
                    
                    # Create access token
                    expiry_time = timedelta(minutes=30)
                    my_identity = {'id':this_user.id, 'privileges':privileges}
                    access_token = create_access_token(identity=my_identity, expires_delta=expiry_time, fresh=True)
                    refresh_token = create_refresh_token(my_identity)
                    # Save session info to db
                    new_session_record = SessionModel(user_ip_address=ip, device_operating_system=device_os, user_id=user_id)    
                    new_session_record.insert_record()
                    return { 'access_token': access_token, "refresh_token": refresh_token}, 200
            if not this_user or not check_password_hash(this_user.password, data['password']):
                return {'message': 'Could not log in, please check your credentials'}, 400
        except Exception as e:
            print('========================================')
            print('error description: ', e)
            print('========================================')
            return {'message': 'Could not log in user.'}, 500
コード例 #2
0
    def put(self, reset_token: str):
        '''Reset User Password'''
        # Get User-agent and ip address
        try:
            my_ip = request.environ.get('HTTP_X_FORWARDED_FOR')
            if my_ip is None:
                ip = request.environ['REMOTE_ADDR']
            else:
                ip = request.environ['HTTP_X_FORWARDED_FOR']

            if ip is None or str(ip) == '127.0.0.1' or str(ip) == '172.17.0.1':
                return {
                    'message':
                    'This request has been rejected. Please use a recognised device'
                }, 403

            # Compute operating system
            device_operating_system = generate_device_data()
            if 'error' in device_operating_system.keys():
                return {'message': device_operating_system['error']}, 403
            device_os = device_operating_system['device_os']

            received_reset_token = reset_token
            TokenGenerator.decode_token(received_reset_token)
            token = TokenGenerator.token

            # Check for an existing reset_token with is_expired status as False
            reset_code_record = PasswordResetModel.fetch_by_reset_code(
                reset_code=token)
            if not reset_code_record:
                return {'message': 'This reset token does not exist'}, 404

            if reset_code_record.is_expired == True:
                user_id = reset_code_record.user_id
                is_expired = True
                user_records = PasswordResetModel.fetch_by_user_id(user_id)
                record_ids = []
                for record in user_records:
                    record_ids.append(record.id)
                for record_id in record_ids:
                    PasswordResetModel.expire_token(id=record_id,
                                                    is_expired=is_expired)
                return {
                    'message':
                    'Password reset token has already been used. Please request a new password reset.'
                }, 403

            user_id = reset_code_record.user_id
            is_expired = True
            user_records = PasswordResetModel.fetch_by_user_id(user_id)
            record_ids = []
            for record in user_records:
                record_ids.append(record.id)
            for record_id in record_ids:
                PasswordResetModel.expire_token(id=record_id,
                                                is_expired=is_expired)

            data = api.payload

            if not data:
                return {'message': 'No input data detected'}, 400

            password = data['password']
            hashed_password = generate_password_hash(data['password'],
                                                     method='sha256')
            UserModel.update_password(id=user_id, password=hashed_password)

            this_user = UserModel.fetch_by_id(id=user_id)
            # user = user_schema.dump(this_user) # This line would be used if we were outputing the user

            user_id = this_user.id

            # fetch User role
            user_role = UserRoleModel.fetch_by_user_id(user_id)
            privileges = user_role.role.role
            # Create access token
            expiry_time = timedelta(minutes=30)
            my_identity = {'id': this_user.id, 'privileges': privileges}
            access_token = create_access_token(identity=my_identity,
                                               expires_delta=expiry_time,
                                               fresh=True)
            refresh_token = create_refresh_token(my_identity)
            # Save session info to db
            new_session_record = SessionModel(
                user_ip_address=ip,
                device_operating_system=device_os,
                user_id=user_id)
            new_session_record.insert_record()

            # Record this event in user's logs
            log_method = 'put'
            log_description = 'Password reset'

            auth_token = {"Authorization": "Bearer %s" % access_token}
            record_user_log(auth_token, log_method, log_description)

            return {
                'access_token': access_token,
                "refresh_token": refresh_token
            }, 200
        except Exception as e:
            print('========================================')
            print('error description: ', e)
            print('========================================')
            return {'message': 'Could not reset password.'}, 500