async def post(self, user): # Id of the user being reported try: target = int(self.get_argument('target', False)) except: raise CustomError(reason="Target user not provided", status_code=404) logger.error( "Id of target couldn't be converted to int or is not present") user_target = await self.application.objects.get(UserProfile, id=target) if not user_target: raise CustomError(reason="Target provided is not valid", status_code=404) # Id of the user reporting reporter = user.id # Message of the report message = self.get_param('message', default="") # Reason of the report reason = self.get_param('reason', default="Not expecified") report = Report.create(target=user_target, reporter=reporter, message=message, reason=reason) resp.body = json.dumps(report.json()) resp.status = falcon.HTTP_200
async def post(self): token = self.get_argument('token') data = confirm_token(token) if data: typ, email = data else: self.write({"Error": "Code expired"}) self.set_status(500) self.finish() return if email: try: user = await self.application.objects.get(User, email=email) password = self.get_argument('password') confirmation = self.get_argument('password_confirmation') valid_password = password == confirmation if valid_password: user.password = bcrypt.hashpw(password, salt_code) await self.application.objects.update(user) else: raise CustomError( reason="Password and confirmation do not match", status_code=401) except User.DoesNotExist: raise CustomError(reason="User not found", status_code=404) else: raise CustomError(reason="Invalid code or too old", status_code=401)
async def prepare(self): self.current_user = None auth = self.request.headers.get('Authorization') if auth: parts = auth.split() if parts[0].lower() != 'bearer': raise CustomError(reason="Invalid header authorization", status_code=401) elif len(parts) == 1: raise CustomError(reason="Invalid header authorization", status_code=401) elif len(parts) > 2: raise CustomError(reason="Invalid header authorization", status_code=401) token = parts[1] try: canditate = await self.application.objects.get(Token, key=token) self.current_user = canditate.user except Token.DoesNotExist: raise CustomError(reason="Invalid token", status_code=401)
async def get(self, id): try: user = await self.application.objects.get(UserProfile, id=id) followers = [following.to_json() for following in user.following()] self.write(json.dumps(followers, default=str)) self.set_status(200) except UserProfile.DoesNotExist: raise CustomError(reason="User not found", status_code=404) except Exception as e: raise CustomError(reason="Unexpected error", status_code=500) log.error(e)
async def get(self, token): email = confirm_token(token) if email: try: user = self.application.objects.get(User, email=email) user.confirmed = True self.application.objects.update(user) except User.DoesNotExist: raise CustomError(reason="User not available", status_code=404) else: raise CustomError(reason="Invalid code or too old", status_code=400)
async def post(sef, user): token = self.request.headers.get('Authorization').split()[1] try: token = await self.application.objects.get(Token, key=token) if user == token.user: await self.application.objects.delete(token) self.write({"Success": "Removed token"}) else: raise CustomError(reason="Unauthorized user", status_code=401) except Token.DoesNotExist: raise CustomError(reason="Token not valid", status_code=401)
async def get(self, user): target_id = self.get_argument('id', None) if target_id: try: target = await self.application.objects.get(UserProfile, id=target_id) data = { 'id': target_id, } # Check if the current user is following that account manager = UserManager(user) target_manager = UserManager(target) data['following'] = await manager.is_following_async( self.application.objects, target) data['followed_by'] = await target_manager.is_following_async( self.application.objects, user) self.write(data) self.set_status(200) except UserProfile.DoesNotExist: log.error(f'User with id {target_id} not found') self.write({"Error": "Target user not found"}) self.set_status(404) else: raise CustomError(reason="Targed it not provided", status_code=400) log.error("Missing target id on request")
async def post(self): username = self.get_argument('username') password = self.get_argument('password') confirmation = self.get_argument('password_confirmation') email = self.get_argument('email') valid_password = password == confirmation if '@' not in parseaddr(email)[1]: raise CustomError(reason="Invalid email", status_code=400) try: user = await self.application.objects.get(User, username=username) if user: raise CustomError(reason="Username not available", status_code=400) except: pass if valid_password: try: log.debug("Creating new user") profile = await new_user_async(username=username, password=password, email=parseaddr(email)[1]) if not profile: log.error("Error creating profile") self.set_status(402) CustomError( reason= "Wrong username. Valid characters are number, ascii letters and (.) (_)", status_code=400) else: self.set_status(200) self.write(json.dumps(profile.to_json(), default=str)) except Exception as e: log.error(e) CustomError(reason="Error creating new user", status_code=500) else: raise CustomError( reason="User not available or password not matching", status_code=400)
async def post(self, target_id, user): try: target = await self.application.objects.get(UserProfile, id=target_id) user.unfollow(target) remove_from_timeline(user, target) except User.DoesNotExist: raise CustomError(reason="User not found", status_code=404)
async def post(self, email): try: user = await self.application.objects.get(User, email=email) profile = user.profile.get() send_password_reset(profile) except User.DoesNotExist: raise CustomError(reason="User not found", status_code=404) self.write( {"Success": "If the email is our database we'll contact the user"}) self.set_status(200)
async def post(self): user = self.current_user if not 'file' in self.request.files.keys(): self.write({"Error": "File not provided"}) self.set_status(422) return image = self.request.files['file'][0] # Search for a valid id valid = False ident = "" while not valid: try: ident = str(uuid.uuid4()) media = await self.application.objects.get(Media, media_name = ident) except Media.DoesNotExist: valid = True # If we are here that means that the object exits manager = MediaManager(self.request.files['file'][0]['body']) valid = manager.is_valid() if valid: description = self.get_argument('description', '') focus = (0,0) if self.get_argument('focus', False): args = self.get_argument('focus').replace(" ", "").split(',') if len(args) == 2: focus = args[:2] extension = manager.get_media_type() urls = URIs( media=uri("media", {"id":ident, "extension": extension}), preview=uri("preview", {"id":ident, "extension": extension}) ) m = { "description": description, "id": ident, "type": "unknown", "url": urls.media, "preview_url": urls.preview, "meta": None } store_media(manager, ident, description, focus) self.write(json.dumps(m, default=str)) self.set_status(200) else: raise CustomError(reason="Error storing files", status_code=400)
async def get(self, id): try: #person = await self.application.objects.get(User, User.id==int(id)) profile = await self.application.objects.get( UserProfile, UserProfile.id == int(id)) self.write( json.dumps(profile.to_json(), default=str).encode('utf-8')) self.set_status(200) except User.DoesNotExist: raise CustomError(reason="User not found", status_code=401)
async def post(self, target_id, user): try: target = await self.application.objects.get(UserProfile, id=target_id) user.follow(target) add_to_timeline(user, target) NotificationManager(user).create_follow_notification(target) log.debug(f"{user.username} followed {target.username}") except User.DoesNotExist: raise CustomError(reason="User not found", status_code=404)
async def get(self, id): try: user = await self.application.objects.get(User, id=id) if self.get_argument('max_id', False): feed = generate_feed(user, int(self.get_argument('max_id'))) else: feed = generate_feed(user) self.set_header('Content-Type', 'application/xml') self.write(feed) except User.DoesNotExist: raise CustomError(reason="User not available", status_code=404)
async def post(self, *args, **kwargs): """ Handle creation of statuses """ user = self.current_user print(user.username) hashids = Hashids(salt=salt_code, min_length=9) if self.kwargs.get('media_ids', False): data = { "caption": self.get_argument('status', ''), "visibility": bool(self.get_argument('visibility', False)), "user": user, "sensitive": bool(self.get_argument('sensitive', False)), "remote": False, "sotory": bool(self.get_argument('story', False)), "identifier": hashids.encode( int( str(user.id) + str(int(datetime.datetime.now().timestamp()))) ) # TODO: We're losing time here } if data['sensitive']: data['spoliet_text'] = self.get_argument('spoiler_text', '') par = Parser(domain=BASE_URL) parsed = par.parse(html.escape(data["caption"])) mentions = parsed.users data['caption'] = parsed.html status = await self.application.objects.create(Status, **data) imgs = self.kwargs.get('media_ids') task = atach_media_to_status.s(status, imgs[0]) for image in imgs[1:]: task = self._then(task, atach_media_to_status, status, image) await self.application.objects.execute( UserProfile.update({ UserProfile.statuses_count: UserProfile.statuses_count + 1 }).where(UserProfile.id == user.id)) task = self._then(task, spread_status, status, mentions, True) huey.enqueue(task) self.write(json.dumps(status.to_json(), default=str)) elif self.get_argument('in_reply_to_id', False): try: replying_to = await self.application.objects.get( Status, identifier=self.get_argument('in_reply_to_id')) data = { "caption": self.get_argument('status', ''), "visibility": bool(self.get_argument('visibility', False)), "user": user, "sensitive": bool(self.get_argument('sensitive', False)), "remote": False, "identifier": hashids.encode( int( str(user.id) + str(int(datetime.datetime.now().timestamp())))), "in_reply_to": replying_to } status = await self.application.objects.create(Status, **data) self.write(json.dumps(status.to_json(), default=str)) except Status.DoesNotExist: raise CustomError(reason="Replying to bad ID", status_code=400) else: raise CustomError(reason="No media attached nor in reply to", status_code=400)