def avatar(self, value): if value is not None: try: self._avatar = Avatar.create_from(value) except DimensionValidationError as e: raise HTTPStatus(f'618 {e}') except AspectRatioValidationError as e: raise HTTPStatus( '619 Invalid aspect ratio Only 1/1 is accepted.') except ContentTypeValidationError as e: raise HTTPStatus( f'620 Invalid content type, Valid options are: '\ f'{", ".join(type for type in AVATAR_CONTENT_TYPES)}' ) except MaximumLengthIsReachedError as e: max_length = settings.attachments.members.avatars.max_length raise HTTPStatus( f'621 Cannot store files larger than: '\ f'{max_length * 1024} bytes' ) else: self._avatar = None
def kick(self, id): try: id = int(id) except (ValueError, TypeError): raise HTTPNotFound() room = DBSession.query(Room).filter(Room.id == id).one_or_none() if room is None: raise HTTPNotFound() member_id = context.form.get('memberId') member = DBSession.query(Member) \ .filter(Member.reference_id == member_id).one_or_none() if member is None: raise HTTPStatus('611 Member Not Found') is_member = DBSession.query(Member) \ .filter( TargetMember.target_id == id, TargetMember.member_id == member.id ) \ .count() if not is_member: raise HTTPStatus('617 Not A Member') DBSession.query(TargetMember) \ .filter( TargetMember.target_id == id, TargetMember.member_id == member.id ) \ .delete() return room
def see(self, id): id = int_or_notfound(id) member = Member.current() message = DBSession.query(Message).get(id) if message is None: raise HTTPNotFound() if message.sender_id == member.id: raise HTTPStatus('621 Can Not See Own Message') member_message_seen = DBSession.query(MemberMessageSeen) \ .filter(MemberMessageSeen.member_id == member.id) \ .filter(MemberMessageSeen.message_id == message.id) \ .one_or_none() if member_message_seen is not None: raise HTTPStatus('619 Message Already Seen') query = DBSession.query(Message) \ .filter(Message.target_id == message.target_id) \ .filter(Message.created_at <= message.created_at) \ .filter(Message.seen_at == None) \ .filter(Message.sender_id != member.id) \ query = Message.filter_by_request(query) for m in query: m.seen_by.append(member) seen_message = message.to_dict() seen_message.update({'type': 'seen'}) queues.push(settings.messaging.workers_queue, seen_message) return message
def claim(self): email = context.form.get('email') email_pattern = r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)' if not email: raise HTTPBadRequest() if not re.match(email_pattern, email): raise HTTPStatus('701 Invalid email format.') if DBSession.query(Member.email).filter(Member.email == email).count(): raise HTTPStatus( '601 The requested email address is already registered.') # FIXME: Token should be put in payload serializer = \ itsdangerous.URLSafeTimedSerializer(settings.activation.secret) token = serializer.dumps(email) DBSession.add( ActivationEmail(to=email, subject='Activate your NueMD Coder account', body={ 'activation_token': token, 'activation_url': settings.activation.url })) return dict(email=email)
def load(cls, token): try: return super().load(token).payload except itsdangerous.SignatureExpired: raise HTTPStatus('609 Token Expired') except itsdangerous.BadSignature: raise HTTPStatus('611 Malformed Token')
def create(self): email = context.form.get('email') password = context.form.get('password') if email and password is None: raise HTTPStatus('603 Incorrect Email Or Password') principal = context.application.__authenticator__.\ login((email, password)) if principal is None: raise HTTPStatus('603 Incorrect Email Or Password') return dict(token=principal.dump())
def attachment(self, value): if value is not None: try: self._attachment = FileAttachment.create_from(value) except ContentTypeValidationError: raise HTTPStatus( '710 The Mimetype Does Not Match The File Type') except MaximumLengthIsReachedError: raise HTTPStatus('413 Request Entity Too Large') else: self._attachment = None
def subscribe(self): member = Member.current() query = DBSession.query(Room) requested_rooms = Target.filter_by_request(query).all() if len(requested_rooms) >= settings.room.subscription.max_length: raise HTTPStatus( f'716 Maximum {settings.room.subscription.max_length} Rooms ' f'To Subscribe At A Time') requested_rooms_id = {i.id for i in requested_rooms} subscribed_rooms = DBSession.query(TargetMember) \ .filter(TargetMember.member_id == member.id) \ .join(Target, Target.id == TargetMember.target_id) \ .filter(Target.type == 'room') \ .all() subscribed_rooms_id = {i.target_id for i in subscribed_rooms} not_subscribed_rooms_id = requested_rooms_id - subscribed_rooms_id flush_counter = 0 for each_room_id in not_subscribed_rooms_id: flush_counter += 1 target_member = TargetMember(target_id=each_room_id, member_id=member.id) DBSession.add(target_member) if flush_counter % 10 == 0: DBSession.flush() not_subscribed_rooms = DBSession.query(Target) \ .filter(Target.id.in_(not_subscribed_rooms_id)) return not_subscribed_rooms
def safe_member_lookup(condition): member = DBSession.query(Member).filter(condition).one_or_none() if member is None: raise HTTPStatus('603 Incorrect Email Or Password') return member
def register(self): email = context.form.get('email') password = context.form.get('password') name = context.form.get('name') family = context.form.get('family') description = context.form.get('description') role = 'member' member = DBSession.query(Member) \ .filter(Member.email == email) \ .one_or_none() if DBSession.query(Member.email).filter(Member.email == email).count(): raise HTTPStatus('601 Email Address Is Already Registered') member = Member( email=email, name=name, password=password, family=family, description=description, role=role, ) DBSession.add(member) return member
def create(self): user_id = context.form.get('userId') destination = DBSession.query(Member) \ .filter(Member.id == user_id).one_or_none() if destination is None: raise HTTPStatus('611 Member Not Found') current_user = DBSession.query(Member) \ .filter(Member.reference_id == context.identity.reference_id) \ .one() is_blocked = DBSession.query(member_block) \ .filter(or_( and_( member_block.c.member_id == user_id, member_block.c.blocked_member_id == current_user.id ), and_( member_block.c.member_id == current_user.id, member_block.c.blocked_member_id == user_id ) )) \ .count() if is_blocked: raise HTTPStatus( '613 Not Allowed To Create Direct With This Member') source = Member.current() cte = select([ TargetMember.target_id.label('direct_id'), func.array_agg(aggregate_order_by(TargetMember.member_id, TargetMember.member_id), type_=ARRAY(Integer)).label('members') ]).group_by(TargetMember.target_id).cte() direct = DBSession.query(Direct) \ .join(cte, cte.c.direct_id == Direct.id) \ .filter(cte.c.members == sorted([source.id, user_id])) \ .one_or_none() if direct: return direct direct = Direct(members=[source, destination]) return direct
def create(self): code = context.form.get('code') if _cas_server_status != 'idle': raise HTTPStatus(_cas_server_status) if not code.startswith('authorization code'): return dict(accessToken='token is damage', memberId=1) return dict(accessToken='access token', memberId=1)
def create(self): title = context.form.get('title') if DBSession.query(Person).filter(Person.title == title).count(): raise HTTPStatus('600 Already person has existed') person = Person(title=context.form.get('title')) DBSession.add(person) return person
def add(self, id: int): user_id = context.form.get('userId') requested_user = DBSession.query(Member) \ .filter(Member.reference_id == user_id) \ .one_or_none() if requested_user is None: raise HTTPStatus('611 Member Not Found') room = DBSession.query(Room).filter(Room.id == id).one_or_none() if room is None: raise HTTPStatus('612 Room Not Found') is_member = DBSession.query(TargetMember) \ .filter( TargetMember.target_id == id, TargetMember.member_id == requested_user.id ) \ .count() if is_member: raise HTTPStatus('604 Already Added To Target') if not requested_user.add_to_room: raise HTTPStatus('602 Not Allowed To Add This Person To Any Room') current_user = DBSession.query(Member) \ .filter(Member.reference_id == context.identity.reference_id) \ .one() is_blocked = DBSession.query(member_block) \ .filter(or_( and_( member_block.c.member_id == requested_user.id, member_block.c.blocked_member_id == current_user.id ), and_( member_block.c.member_id == current_user.id, member_block.c.blocked_member_id == requested_user.id ) )) \ .count() if is_blocked: raise HTTPStatus('601 Not Allowed To Add Member To Any Room') room.members.append(requested_user) return room
def test_validation_required_as_httpstatus(): class Myclass(HTTPStatus): status = '600 Custom exception' validator = RequestValidator(fields=dict(foo=dict(required=Myclass))) with pytest.raises(HTTPStatus(Myclass).__class__): validator(dict(another_param='value1')) assert dict(foo='value1') == validator(dict(foo='value1'))[0]
def create(self): title = context.form.get('title') if DBSession.query(Foo).filter(Foo.title == title).count(): raise HTTPStatus('604 Title Is Already Registered') foo = Foo() foo.update_from_request() DBSession.add(foo) return foo
def get(self, id_: int = None): q = DBSession.query(Resource) status = context.query.get('status') if status: raise HTTPStatus(status) if id_ is not None: return q.filter(Resource.id == id_).one_or_none() return q
def _get_target(self, id): try: int(id) except: raise HTTPStatus('706 Invalid Target Id') target = DBSession.query(Target).filter(Target.id == id).one_or_none() if target is None: raise HTTPNotFound('Target Not Exists') return target
def test_registeration_token(self): # Create registeration token using dump and load mothods payload = dict(a=1, b=2) registeration_token = RegisterationToken(payload) dump = registeration_token.dump() load = RegisterationToken.load(dump.decode()) assert load == payload # Trying to load token using bad signature token with pytest.raises(HTTPStatus('607 Malformed Token').__class__): load = RegisterationToken.load('token') # Trying to load token when token is expired with pytest.raises(HTTPStatus('609 Token Expired').__class__): settings.registeration.max_age = 0.3 registeration_token = RegisterationToken(payload) dump = registeration_token.dump() time.sleep(1) load = RegisterationToken.load(dump.decode())
def register(self): title = context.form.get('title') password = context.form.get('password') ownership_token = context.form.get('ownershipToken') if DBSession.query(Member.title).filter(Member.title == title).count(): raise HTTPStatus('604 Title Is Already Registered') regiteration_token_payload = RegisterationToken.load(ownership_token) email = regiteration_token_payload['email'] if DBSession.query(Member.email).filter(Member.email == email).count(): raise HTTPStatus('601 Email Address Is Already Registered') member = Member(email=email, title=title, password=password) DBSession.add(member) principal = member.create_jwt_principal() context.response_headers.add_header('X-New-JWT-Token', principal.dump().decode('utf-8')) return member
def change(self): current_password = context.form.get('currentPassword') new_password = context.form.get('newPassword') member = Member.current() if current_password is None or \ not member.validate_password(current_password): raise HTTPStatus('602 Invalid Current Password') member.password = new_password return {}
def get(self): access_token = context.environ['HTTP_AUTHORIZATION'] if _cas_server_status != 'idle': raise HTTPStatus(_cas_server_status) if 'access token1' in access_token: return dict( id=2, email='*****@*****.**', title='user1', firstName='user1_first_name', lastName='user1_last_name', avatar='avatar2', ) if 'access token2' in access_token: return dict( id=3, email='*****@*****.**', title='user2', firstName='user2_first_name', lastName='user2_last_name', avatar='avatar3', ) if 'access token3' in access_token: return dict( id=4, email='*****@*****.**', title='blocked1', firstName='blocked1_first_name', lastName='blocked1_last_name', avatar='avatar4', ) if 'access token4' in access_token: return dict( id=5, email='*****@*****.**', title='blocker', firstName='blocker_first_name', lastName='blocker_last_name', avatar='avatar5', ) return dict( id=1, email='*****@*****.**', title='user', firstName='user_first_name', lastName='user_last_name', avatar='avatar1', )
def get(self): access_token = context.environ['HTTP_AUTHORIZATION'] if _cas_server_status != 'idle': raise HTTPStatus(_cas_server_status) if 'access token' in access_token: return dict( id=1, title='manager1', email='*****@*****.**', avatar='avatar1', ) raise HTTPForbidden()
def delete(self, id): try: id = int(id) except: raise HTTPStatus('707 Invalid MessageId') message = DBSession.query(Message) \ .filter(Message.id == id) \ .one_or_none() if message is None: raise HTTPStatus('614 Message Not Found') if message.is_deleted: raise HTTPStatus('616 Message Already Deleted') if not message.sender_id == Member.current().id: raise HTTPForbidden() message.body = 'This message is deleted' message.mimetype = 'text/plain' message.soft_delete() DBSession.flush() queues.push(settings.messaging.workers_queue, message.to_dict()) return message
def add(self): user_id = context.form.get('userId') destination = DBSession.query(Member) \ .filter(Member.id == user_id) \ .one_or_none() if destination is None: raise HTTPStatus('611 Member Not Found') current_member = DBSession.query(Member) \ .filter(Member.reference_id == context.identity.reference_id) \ .one() is_contact = DBSession.query(MemberContact) \ .filter( MemberContact.member_id == current_member.id, MemberContact.contact_member_id == user_id ) \ .count() if is_contact: raise HTTPStatus('603 Already Added To Contacts') DBSession.add( MemberContact(member_id=current_member.id, contact_member_id=user_id)) return destination
def claim(self): email = context.form.get('email') if DBSession.query(Member.email).filter(Member.email == email).count(): raise HTTPStatus('601 Email Address Is Already Registered') token = RegisterationToken(dict(email=email)) DBSession.add( RegisterEmail(to=email, subject='Register your CAS account', body={ 'registeration_token': token.dump(), 'registeration_callback_url': settings.registeration.callback_url })) return dict(email=email)
def edit(self, id): id = int_or_notfound(id) new_message_body = context.form.get('body') message = DBSession.query(Message).get(id) if message is None: raise HTTPNotFound() if message.is_deleted: raise HTTPStatus('616 Message Already Deleted') if message.sender_id != Member.current().id: raise HTTPForbidden() message.body = new_message_body DBSession.add(message) DBSession.flush() queues.push(settings.messaging.workers_queue, message.to_dict()) return message
def create(self): title = context.form.get('title') current_user = DBSession.query(Member) \ .filter(Member.reference_id == context.identity.reference_id) \ .one() is_exist = DBSession.query(Room) \ .filter( Room.title == title, Room.owner_id == current_user.id ) \ .count() if is_exist: raise HTTPStatus('615 Room Already Exists') room = Room(title=title) member = Member.current() room.administrators.append(member) room.members.append(member) room.owner = member DBSession.add(room) return room
def test_validation_required(): validator = RequestValidator(fields=dict(a=dict(required=True))) # Trying to pass with a assert dict(a='value1') == validator(dict(a='value1'))[0] # Trying to pass without a with pytest.raises(HTTPBadRequest): validator(dict(another_param='value1')) # Define required validation with custom exception validator = RequestValidator(fields=dict(a=dict( required='600 Custom exception'))) # Trying to pass with another param without a with pytest.raises(HTTPStatus('600 Custom exception').__class__): validator(dict(another_param='value1')) # Trying to pass with a assert dict(a='value1') == validator(dict(a='value1'))[0]
def reply(self, message_id): id = int_or_notfound(message_id) mimetype = context.form.get('mimetype') requested_message = DBSession.query(Message).get(id) if requested_message is None: raise HTTPNotFound() if requested_message.is_deleted: raise HTTPStatus('616 Message Already Deleted') message = Message( body=context.form.get('body'), target_id=requested_message.target_id, sender_id=Member.current().id, reply_to=requested_message, ) if 'attachment' in context.form: message.attachment = context.form.get('attachment') message.mimetype = message.attachment.content_type if message.attachment.content_type in BLACKLIST_MIME_TYPES: raise HTTPUnsupportedMediaType() elif mimetype: if mimetype not in SUPPORTED_TEXT_MIME_TYPES: raise HTTPUnsupportedMediaType() message.mimetype = mimetype else: message.mimetype = 'text/plain' DBSession.add(message) DBSession.flush() queues.push(settings.messaging.workers_queue, message.to_dict()) return message