def post(self): # Parse the data from the POST request. data = parser.parse_args() # Find the current user model from DB. current_user = UserModel.find_by_username(data['username']) # Handle no user found. if not current_user: return dict(status=401) # Verify user password. if UserModel.verify_hash(data['password'], current_user.password): if config.CACHE_ENABLED: # Clear user cache in order to refresh it. devices_cache.clear_user_cache(current_user.id) # Return the access and refresh tokens, created based on username. access_token = create_access_token(identity=data['username']) refresh_token = create_refresh_token(identity=data['username']) return dict( status=200, access_token=access_token, refresh_token=refresh_token, ) else: return (dict(message='User login failed.', status=401))
def add_claims_to_access_token(identity): return { 'user': identity, 'company_id': UserModel.find_by_id(_id=identity).company_id, 'roles': [ role.name for role in UserModel.find_by_id(_id=identity).roles ] }
def post(cls): user_json = request.get_json() user_data = user_schema.load(user_json) user = UserModel.find_by_username(user_data.username) if user and user.check_password(user_json['password']): access_token = create_access_token(identity=user.id, fresh=True) access_decoded_token = decode_token(access_token) entry = { "jti": access_decoded_token["jti"], "token_type": 'access', "fresh": True, "blacklisted": False, "never_expire": False, } data = token_schema.load(entry) data.user_id = user.id data.expiration_date = datetime.fromtimestamp( access_decoded_token['exp']) data.save_to_db() resp = jsonify({'refresh': True, 'login': True}) set_access_cookies(resp, access_token) return resp, 200 return {"message": INVALID_CREDENTIALS}, 401
def delete(cls, user_id: int): user = UserModel.find_by_id(user_id) if not user: return {"message": USER_NOT_FOUND}, 404 user.delete_from_db() return {"message": USER_DELETED}, 200
def post(self): """ POST request that requires JWT to schedule timer or set specific time to change the state of a device. """ logger.info( "Resource WifiSwitchAction to set timer for device with POST.") # Retrieve the username from the JWT and find the current user from DB. current_user = UserModel.find_by_username(get_jwt_identity()) # Parse request arguments. request_args = self._parser.parse_args() # Update the dictionary (like 'year': 2020) and get the keys from DATETIME_CSV tuple. Convert empty strings to None and splitted datetime strings to integers. request_args.update( dict( zip( constants.DATETIME_CSV, map(lambda d: None if not d else int(d), request_args.get('datetime').split(','))))) # Call the scheduler function related to the trigger. self._trigger_scheduler[request_args.get('trigger')](current_user.id, request_args) return (dict(message='Job scheduled.'), 200)
def get(cls): jti = get_raw_jwt()[ "jti"] # jti is "JWT ID", a unique identifier for a JWT. user_id = get_jwt_identity() user = UserModel.find_by_id(_id=user_id) co = user.company roles = [role.name for role in user.roles] return {"user": user_schema.dump(user), "jti": jti, "roles": roles}
def post(self): # Parse the data from the POST request. data = parser.parse_args() # Find if the user already exists in DB. if UserModel.find_by_username(data['username']): return dict( message='User {} already exists'.format(data['username'])) # Create a new user model. new_user = UserModel(username=data['username'], email=data['email'], password=UserModel.generate_hash( data['password'])) try: # Save model in DB. new_user.save_to_db() # Create access and refresh tokens, based on username and return them. access_token = create_access_token(identity=data['username']) refresh_token = create_refresh_token(identity=data['username']) return (dict(message='User {} was created'.format( data['username']), access_token=access_token, refresh_token=refresh_token), 201) except Exception as e: logger.error(e) return (dict(message='Something went wrong'), 400)
def get(self, device_ui_id, action): """ GET request that requires JWT to retrieve device data for user. """ logger.debug("Resource WifiSwitchAction GET.") # Retrieve the username from the JWT and find the current user from DB. current_user = UserModel.find_by_username(get_jwt_identity()) # Retrieve the related MQTT topic. mqtt_topic = DeviceModel.find_device_mqtt_topic(device_ui_id) if not mqtt_topic: return (dict( message= 'ERROR: Invalid device_ui_id. No related MQTT topic found.'), 404) # User requested the status of the device. if action == constants.DEVICE_STATUS: logger.info( "Refresh: get smart socket status, saved in cache, if exists, else from db." ) if config.CACHE_ENABLED: device_status = devices_cache.find_device_status( current_user.id, device_ui_id) if not device_status: device_status = DeviceModel.find_device_status( device_ui_id) else: device_status = DeviceModel.find_device_status(device_ui_id) return dict( message='Socket status is: %s.' % device_status, status=device_status, switch_state=constants.DEVICE_STATUS_SWITCH.get(device_status)) # User requested to refresh and return the status of the device. if action == constants.DEVICE_REFRESH_STATUS: logger.info("Refresh: get smart socket status, saved in DB.") # Reload cache to update/sync all users devices. # devices_cache.clear_cache() # Ask device to return its status. mqtt.mqttc.publish(mqtt_topic, constants.STATUS_DEVICE) time.sleep(5) # TODO: Change logic. device_status = DeviceModel.find_device_status(device_ui_id) return dict( message='Socket status is: %s.' % device_status, status=device_status, switch_state=constants.DEVICE_STATUS_SWITCH.get(device_status)) return (dict(message='ERROR: Invalid URL.'), 404)
def post(self): """ POST request that requires JWT. """ # Parse request arguments. data = self._parser.parse_args() # Retrieve the username from the JWT username = get_jwt_identity() # Find the current user from DB. current_user = UserModel.find_by_username(username) device_id = DeviceModel.find_device_id(data['device_ui_id']) user_has_device = DeviceModel.find_user_has_device( data['device_ui_id'], username) if user_has_device: return (dict(message='Device {} already exists for user {}'.format( data['device_ui_id'], username)), 200) if device_id: # If the device exists already, just relate it to the user. UserDevice.new_entry(current_user.id, device_id) return (dict(message='Device {} was added also for user {}'.format( data['device_ui_id'], username)), 200) else: # If the device does not exist, register it and relate it to the user. if config.CACHE_ENABLED: # Clear cache in order to reload with the new device. devices_cache.clear_user_cache(current_user.id) new_device = DeviceModel( device_ui_id=data['device_ui_id'], name=data['name'], state=data['state'], status=data['status'], switch_state=eval(data['switch_state'].capitalize()), button_type=data['button_type'], mqtt_topic=data['mqtt_topic'], ) new_device.user.append(current_user) try: new_device.save_to_db() return (dict(message='Device {} was added for user {}'.format( data['device_ui_id'], username)), 201) except Exception as e: logger.error(e) return (dict(message='Something went wrong'), 500)
def put(self): """ PUT request that requires JWT to update device. """ logger.debug("Resource WifiSwitchAction to update device with PUT.") # Retrieve the username from the JWT and find the current user from DB. current_user = UserModel.find_by_username(get_jwt_identity()) # Parse request arguments. args = self._parser.parse_args() # Handle on/off actions. return self._device_switch_util(current_user.id, args.get('device_ui_id'), args.get('action'))
def get(self): """ POST request that requires JWT. """ logger.info("Get a list of the user devices.") # Retrieve the username from the JWT and find the current user from DB. current_user = UserModel.find_by_username(get_jwt_identity()) if config.CACHE_ENABLED: # Get a list of the cached user devices. user_cached_devices = devices_cache.get_user_cache(current_user.id) devices = user_cached_devices if user_cached_devices else DeviceModel.return_user_devices( current_user.id) devices_cache.cache = (current_user.id, devices) return dict(devices=devices) return dict(devices=DeviceModel.return_user_devices(current_user.id))
def post(cls): req_json = request.get_json() errors = user_post_schema.validate(req_json) if errors: response = jsonify({'errors': errors, "status": 400}) response.status_code = 400 return response if UserModel.find_by_username(req_json['username']): return {"message": USER_ALREADY_EXISTS}, 400 if UserModel.query.filter_by(email=req_json['email']).first(): return {"message": EMAIL_ALREADY_EXISTS}, 400 data = user_post_schema.load(req_json) data.set_password(req_json['password']) data.save_to_db() return {"message": CREATED_SUCCESSFULLY}, 201
def post(cls): req_json = request.get_json() user_id = get_jwt_identity() user = UserModel.find_by_id(user_id) errors = new_password_schema.validate(req_json) if errors: response = jsonify({'errors': errors, "status": 400}) response.status_code = 400 return response if user and user.check_password(req_json['password']): user.set_password(req_json['new_password']) user.save_to_db() access_token = create_access_token(identity=user.id, fresh=True) refresh_token = create_refresh_token(user.id) access_decoded_token = decode_token(access_token) entry = { "jti": access_decoded_token["jti"], "token_type": 'access', "fresh": True, "blacklisted": False, "never_expire": False, } data = token_schema.load(entry) data.user_id = user.id data.expiration_date = datetime.fromtimestamp( access_decoded_token['exp']) data.save_to_db() resp = jsonify({ "message": "Successfully set a new password", "login": True }) set_access_cookies(resp, access_token) set_refresh_cookies(resp, refresh_token) return resp, 200 return {"message": INVALID_CREDENTIALS, 'login': False}, 401
def get_company_from_request(): jti = get_raw_jwt()[ "jti"] # jti is "JWT ID", a unique identifier for a JWT. user_id = get_jwt_identity() return UserModel.find_by_id(_id=user_id).company_id
def get(cls, user_id): user = UserModel.find_by_id(user_id) if not user: return {"message": USER_NOT_FOUND}, 404 return user_schema.dump(user), 200