class AuthResource(object): def __init__(self): self.logger = logging.getLogger() self.accessor = UserAccessor() self.secret = os.environ.get('SECRET_KEY') @staticmethod def bytes_to_bearer(token): return {'Authorization': f'Bearer {token.decode()}'} @staticmethod def bearer_to_bytes(header): header_str = header.get('Authorization', '') return header_str[7:].encode() def get_roles(self, username): return self.accessor.get_list(username, 'roles') def build_token(self, username): payload = { 'username': username, 'roles': self.get_roles(username), 'expire_at': time.time() + (30 * 60) } token = jwt.encode(payload, self.secret) return self.bytes_to_bearer(token) def verify_token(self, token, username, allowed_roles): if isinstance(token, dict) and 'Authorization' in token: token = self.bearer_to_bytes(token) elif isinstance(token, str) and token.startswith('Bearer'): token = token[7:].encode() payload = jwt.decode(token, self.secret) if 'ADMIN' not in allowed_roles: allowed_roles.append('ADMIN') try: if (payload.get('expire_at') - time.time()) < 0: raise AuthorizationError('Token expired') elif payload.get( 'username') != username and 'ADMIN' not in payload.get( ['roles'], []): raise AuthorizationError('Username does not match') elif not any(role in allowed_roles for role in payload.get('roles', [])): raise AuthorizationError( 'User does not have the required roles') except AuthorizationError as e: return {'message': str(e)}, 403 return {'message': 'Success'}, 200 def get_auth(self, username, password): if not self.accessor.check_password(username, password): raise AuthorizationError('Not Authorized') return self.build_token(username)
class UsersResource(BaseResource): def __init__(self, api=None): super().__init__(api=api) self.accessor = UserAccessor() @requires_auth(allowed_roles='USER') def get(self, username): user = self.accessor.find_one({'username': username}) return user @requires_auth(allowed_roles='USER') def delete(self, username): self.accessor.delete_user(username) return {'message': f'Deleted user: {username}'}
def cleanup(username=None, mosaic_file=None, frame_directory=None, output_file=None, is_animated=True, frame_duration=0.1, mode='I'): if username is None: return if is_animated: mosaic_frames = prepend_to_path(frame_directory, 'Mosaic_of') stitcher = GifStitcher(mosaic_frames, output_file) stitcher.make_gif(frame_duration, mode) print('cleaning up directories with') for directory in [mosaic_frames, frame_directory]: if os.path.exists(directory): shutil.rmtree(directory) print(output_file) UserAccessor().create_gallery_item(username, mosaic_file) print('done')
def __init__(self): self.accessor = UserAccessor() self.processor = MessageProcessor() self.logger = logging.getLogger(__name__)
class UserResource(object): def __init__(self): self.accessor = UserAccessor() self.processor = MessageProcessor() self.logger = logging.getLogger(__name__) @staticmethod def set_password(password): psw_hash = generate_password_hash(password) return psw_hash @staticmethod def check_password(psw_hash, password): return check_password_hash(psw_hash, password) def get_roles(self, username): query = {'username': username} projection = {'roles': 1, '_id': 0} return self.accessor.collection.find(query, projection) def get_gallery(self, username, skip=0, limit=None, sort=None): return self.accessor.get_paginated_list(username, 'gallery', skip, limit, sort) def get_gallery_item(self, username, gallery_id): return self.accessor.get_list_item(username, 'gallery', gallery_id) def insert_gallery_item(self, username, gallery_item): self.accessor.insert_list_item(username, 'gallery', gallery_item) return gallery_item def create_user(self, username, email, password): return self.accessor.create_user(username, email, password) def insert_message(self, username, message): self.accessor.insert_message(username, message) def post_message(self, username, form_content): message = self.processor.create_message(username, **form_content) self.accessor.insert_message(username, message) def get_pending_message(self, username): message = self.accessor.get_last_message(username) if not message: return message, 404 message = Message.load_from_document(message) path = message.current resp = ImageServer().serve_thumbnail_from_path(path, 300) return resp def get_pending_message_json(self, username): message = self.accessor.get_last_message(username) if not message: return message, 404 message = Message.load_from_document(message) return message.jsonify() def get_uploads(self, username): return self.accessor.get_list(username, 'uploads') def get_upload(self, username, file_id): return self.accessor.get_array_element({'username': username}, 'uploads', {'uploads.file_id': file_id}) def delete_uploads_item(self, username, upload): file_id = upload.get('file_id') return self.delete_upload_by_id(username, file_id) def delete_upload_by_id(self, username, file_id): if not file_id: return {'message': 'No file_id provided'}, 400 upload = self.get_upload(username, file_id) if upload: self._remove_files(upload) self.accessor.delete_one_element({'username': username}, 'uploads', upload) return {'message': f'Successfully deleted {file_id} for {username}'}, 200 return {'message': f'No file to Remove'}, 200 def _remove_files(self, upload_item): file_path = upload_item.get('img_path', '') if os.path.exists(file_path): os.remove(file_path) self.accessor.fs_accessor.delete(upload_item.get('file_id')) self.accessor.fs_accessor.delete(upload_item.get('thumbnail_id'))
def __init__(self): self.logger = logging.getLogger() self.accessor = UserAccessor() self.secret = Environment().secret_key
class AuthResource(object): def __init__(self): self.logger = logging.getLogger() self.accessor = UserAccessor() self.secret = Environment().secret_key @staticmethod def bytes_to_bearer(token): return {'Authorization': f'Bearer {token.decode()}'} @staticmethod def bearer_to_bytes(header): header_str = header.get('Authorization', '') return header_str[7:].encode() def add_role(self, username, role): roles = self.get_roles(username) if role not in roles: self.accessor.insert_list_item(username, 'roles', role) def get_roles(self, username): return self.accessor.get_list(username, 'roles') def is_validated(self, username): return self.accessor.is_validated(username) def get_token(self, token): if isinstance(token, dict) and 'Authorization' in token: token = self.bearer_to_bytes(token) elif isinstance(token, str) and token.lower().startswith('bearer'): token = token[7:].encode() return jwt.decode(token, self.secret) def build_token(self, username): payload = { 'username': username, 'roles': self.get_roles(username), 'validated': self.is_validated(username), 'expire_at': time.time() + (60 * 60) } token = jwt.encode(payload, self.secret) return self.bytes_to_bearer(token) def verify_token(self, token, username, allowed_roles): allowed_roles = allowed_roles if allowed_roles else ['ADMIN'] if isinstance(allowed_roles, str): allowed_roles = [allowed_roles] if 'ADMIN' not in allowed_roles: allowed_roles.append('ADMIN') # ADMIN should always override try: payload = self.get_token(token) if (payload.get('expire_at') - time.time()) < 0: raise AuthorizationError('Token expired') elif not payload.get('validated', False): raise AuthorizationError('User has not been validated') elif 'ADMIN' in payload.get('roles', []): return {'message': 'Success'}, 200 elif username != payload.get('username'): raise AuthorizationError('Username does not match') elif not any(role in allowed_roles for role in payload.get('roles', [])): raise AuthorizationError('User does not have the required roles') except (AuthorizationError, DecodeError) as e: return {'message': str(e)}, 403 return {'message': 'Success'}, 200 def check_password(self, username, password): status, msg = self.accessor.check_password(username, password) if not status: raise AuthorizationError(msg) return status def get_auth(self, username, password): if self.check_password(username, password): return self.build_token(username) def validate_user(self, username, password): if self.check_password(username, password): self.accessor.validate_user(username) return self.build_token(username)
def __init__(self): self.logger = logging.getLogger() self.accessor = UserAccessor() self.secret = os.environ.get('SECRET_KEY')
def __init__(self, api=None): super().__init__(api=api) self.accessor = UserAccessor()