def post(self): # Acquire all of the data in a dict of each argument defined in the parser above. data = DinnerRegistrar.parser.parse_args() if ProfessorModel.find_by_id(data["professorID"]) is None: return { "Message": "Dinner could not be created as no such professor could be found with id {}." .format(data["professorID"]) }, 404, { "Access-Control-Allow-Origin": "*" } if data["userID"]: if data["userID"] == -1: # Create a new ProfessorModel object containing the passed properties. newDinner = DinnerModel(**( data.pop("userID") )) ## ** automatically separates dict keywords into arguments # Iterate the amount of dinners for this professor by one associatedProfessor = ProfessorModel.find_by_id( data["professorID"]) associatedProfessor.dinnerCount += 1 associatedProfessor.save_to_db() # Save the new professor to the database. newDinner.save_to_db() return newDinner.json(), 201, { "Access-Control-Allow-Origin": "*" } elif not UserModel.find_by_id(data["userID"]): return { "Message": "There is no user in the database with that ID. Could not create dinner" }, 404, { "Access-Control-Allow-Origin": "*" } else: user = UserModel.find_by_id(data["userID"]) user.dinnerCount += 1 user.semDinnerCount += 1 user.save_to_db() # Create a new ProfessorModel object containing the passed properties. newDinner = DinnerModel( **data) ## ** automatically separates dict keywords into arguments # Iterate the amount of dinners for this professor by one associatedProfessor = ProfessorModel.find_by_id(data["professorID"]) associatedProfessor.dinnerCount += 1 associatedProfessor.save_to_db() # Save the new professor to the database. newDinner.save_to_db() return newDinner.json(), 201, {"Access-Control-Allow-Origin": "*"}
def get(self, id): user = UserModel.find_by_id(id) if not user: return { "Message": "No user could be found with that ID" }, 200, { "Access-Control-Allow-Origin": "*" } current_user = get_jwt_identity() currentUser = UserModel.find_by_username(current_user) if user.id == currentUser.id or currentUser.role == 0: if (user): return user.json(), 200, {"Access-Control-Allow-Origin": "*"} else: return { "Message": "You cannot view information about other users unless you are a super admin." }, 401, { "Access-Control-Allow-Origin": "*" } return { "Message": "No user could be found with that ID" }, 200, { "Access-Control-Allow-Origin": "*" }
def on_send_chat(chat): message = MessageModel(**chat) user_id = get_jwt_identity() user = UserModel.find_by_id(user_id) conversation_list = ConversationModel.find_all_by_id( message.conversation_id) conversation_result = next( filter(lambda conv: conv.user_id == user_id, conversation_list), None) conversation = ConversationModel.get_conversation( conversation_result.conversation_id) try: message.upsert(user, conversation) except DatabaseError as error: return { "msg": "An error occurred while saving message to database. Error: {}" .format(error) }, 500 emit('receive_message', message.to_json(), room=message.conversation_id)
def json(self): applicationJSON = [app.json() for app in self.applications] studentReviewJSON = [ studentReview.json() for studentReview in self.studentReviews ] if UserModel.find_by_id(self.userID): userString = self.user.infojson() else: userString = "No User Selected" return { "id": self.id, "timeStamp": self.timeStamp, "topic": self.topic, "description": self.description, "studentLimit": self.studentLimit, "address": self.address, "dietaryRestrictions": self.dietaryRestrictions, "status": self.status, "invitationSentTimeStamp": self.invitationSentTimeStamp, "catering": self.catering, "transportation": self.transportation, "professorID": self.professorID, "professor": self.professor.json(), "userID": self.userID, "user": userString, "applications": applicationJSON, "studentReviews": studentReviewJSON }
def post(cls): data = cls.parser.parse_args() target_user = UserModel.find_by_username(data["target_username"]) user_id = get_jwt_identity() user = UserModel.find_by_id(user_id) try: if ConversationModel.find_by_target_user(user_id, target_user.id): raise ConversationExists(user_id, target_user.id) conversation = ConversationModel() except ConversationExists as error: return {"msg": "Duplicate entry. Error: {}".format(error)}, 409 try: conversation.upsert(user, target_user) except AttributeError as error: return { "msg": "Target user does not exist in the database. Error: {}".format( error) }, 404 except DatabaseError as error: return { "msg": "An error occurred while creating a new chat in the database. Error: {}" .format(error) }, 500 conversation_id = ConversationModel.find_by_target_user( user_id, target_user.id) join_room(conversation_id) return { "username": target_user.username, "conversation_id": conversation_id }, 201
def on_connect(): if not decode_token(request.cookies['access_token_cookie']): raise ConnectionRefusedError('incorrect token') user_id = get_jwt_identity() user = UserModel.find_by_id(user_id) UserModel.add_current_user(user.username) online_users = UserModel.get_current_users() emit('get_users', online_users, broadcast=True)
def get(): user_id = get_jwt_identity() user = UserModel.find_by_id(user_id) return { "username": user.username, "id": user_id, "email": user.email }, 200
def to_json(self): user = UserModel.find_by_id(self.user_id) return { "text": self.text, "timestamp": self.timestamp.__str__(), "sender": user.username, "conversation_id": self.conversation_id, "id": self.id, "user_id": user.id }
def delete(cls): _parser = IdRequest(reqparse.RequestParser(bundle_errors=True)) _parser = _parser.validate() data = _parser.parse_args() user = UserModel.find_by_id(_id=data['id']) if not user: return {'message': message['not-found']}, 404 user.delete() return {'message': message['deleted']}, 200
def put(cls): _parser_id = IdRequest(reqparse.RequestParser(bundle_errors=True)) _parser_id = _parser_id.validate() _parser_register = UserRequest(reqparse.RequestParser()) _parser_register = _parser_register.validate() _id = _parser_id.parse_args()['id'] data = _parser_register.parse_args() user = UserModel.find_by_id(_id=_id) if not user: return {'message': message['not-found']}, 404 elif UserModel.find_by_username(_username=data['username'], _method_update=True, _id=_id): return {"message": message['username-exist']}, 400 elif UserModel.find_by_email(_email=data['email'], _method_update=True, _id=_id): return {"message": message['email-exist']}, 400 elif UserModel.find_by_phonenumber(_phonenumber=data['phonenumber'], _method_update=True, _id=_id): return {"message": message['phonenumber-exist']}, 400 user.name = data['name'] user.username = data['username'] user.photo_profile = data['photo_profile'] user.phonenumber = data['phonenumber'] user.birthday_place = data['birthday_place'] user.birthday = data['birthday'] user.address = data['address'] user.resume = data['resume'] user.headline = data['headline'] user.summary = data['summary'] user.email = data['email'] user.link_instagram = data['link_instagram'] user.link_linkedin = data['link_linkedin'] user.link_twitter = data['link_twitter'] user.link_youtube = data['link_youtube'] user.link_google_plus = data['link_google_plus'] user.link_facebook = data['link_facebook'] user.type_theme = data['type_theme'] if data['password'] or data['password'] != "": user.password = helper.password_hash(data['password']) user.update() return {'message': message['updated'], 'data': user.json()}, 200
def delete(self, id): current_user = get_jwt_identity() user = UserModel.find_by_username(current_user) if user.role is not 0: return { "Message": "Only super admids may delete users. You lack permissions." }, 401 if (UserModel.find_by_id(id)): UserModel.find_by_id(id).delete_from_db() return { "Message": "User with id {} deleted.".format(id) }, 200, { "Access-Control-Allow-Origin": "*" } return { "Message": "No user with ID {} found.".format(id) }, 404, { "Access-Control-Allow-Origin": "*" }
def get_all_for_current_user(cls, user_id): conversation_id_list = cls.get_conversation_ids_for_user(user_id) uc_columns = user_conversations.columns conversation_list = db.session.query(user_conversations).filter( uc_columns["conversation_id"].in_(conversation_id_list)).filter( uc_columns["user_id"] != user_id).all() conversation_list_json = [] for conv in conversation_list: user = UserModel.find_by_id(conv.user_id) conversation_list_json.append({ "username": user.username, "conversation_id": conv.conversation_id }) return conversation_list_json
def get(self, id): # Get the dinner, change status, and then email everyone it is complete if DinnerModel.find_by_id(id): dinnerToConfirm = DinnerModel.find_by_id(id) else: return { "Message": "No dinner could be found with id {}".format(id) }, 404, { "Access-Control-Allow-Origin": "*" } if not UserModel.find_by_id(dinnerToConfirm.userID): return { "Message": "This dinner is unclaimed and cannot be published" }, 400, { "Access-Control-Allow-Origin": "*" } dinnerToConfirm.status = 2 dinnerToConfirm.save_to_db() # Designate all pending applications who are not waitlisted as rejected for application in dinnerToConfirm.applications: if application.status == 0: application.status = 2 application.save_to_db() DinnerConfirmer.notifyRecipients(id) dinnerToConfirm.invitationSentTimeStamp = str(time.time()) return { "Message": "Dinner with id {} is confirmed. All accepted applicants have been emailed. Confirmation email sent to {} {}:{}" .format(id, dinnerToConfirm.user.firstName, dinnerToConfirm.user.lastName, dinnerToConfirm.user.email) }, 200, { "Access-Control-Allow-Origin": "*" }
def put(self, id): current_user = get_jwt_identity() if (UserModel.find_by_username(current_user)): currentUser = UserModel.find_by_username(current_user) else: return { "Message": "JSON token does not match any known user. Please register user first." } if currentUser.role != 0: if currentUser.id != id: return { "Message": "Only super admins and users themselves may modify user information. You lack permissions." }, 401 # Acquire all of the data in a dict of each argument defined in the parser above. data = UserResource.parser.parse_args() if (UserModel.find_by_id(id)): userToChange = UserModel.find_by_id(id) if (data["oldPassword"] is None and currentUser.role != 0): return { "Message": "Please enter oldPassword field. Only superadmins may edit without oldPassword." } if (userToChange.password != data["oldPassword"] and currentUser.role != 0): return { "Messsage": "Old password did not match with this user. Please enter correct password before modifying." }, 401 userToChange.username = data["username"] if data["newPassword"]: userToChange.password = data["newPassword"] userToChange.email = data["email"] addedMessage = True if (currentUser.role == 0): addedMessage = False userToChange.role = data["role"] userToChange.netID = data["netID"] userToChange.firstName = data["firstName"] userToChange.lastName = data["lastName"] userToChange.phone = data["phone"] userToChange.major = data["major"] userToChange.emailText = data["emailText"] userToChange.save_to_db() if (addedMessage): returnJSON = {} returnJSON["user"] = userToChange.json() returnJSON[ "Message"] = "Note: Could not modify role as you do not have superadmin credentials. " return returnJSON else: return userToChange.json() else: return {"Message": "No user could be found with that id"}, 404 return {"Message": "Unexpected error on /User/put"}, 501
def identity(payload): user_id = payload['identity'] return UserModel.find_by_id(user_id)
def get(cls, id: int): user = UserModel.find_by_id(_id=id) if not user: return {'message': message['not-found']}, 404 return {'message': message['single-found'], 'data': user.json()}, 200
def on_disconnect(): user_id = get_jwt_identity() user = UserModel.find_by_id(user_id) UserModel.remove_current_user(user.username) online_users = UserModel.get_current_users() emit('get_users', online_users, broadcast=True)
def put(self, id): data = DinnerResource.parser.parse_args() if (DinnerModel.find_by_id(id)): dinnerOfInterest = DinnerModel.find_by_id(id) if not ProfessorModel.find_by_id(data["professorID"]): return { "Message": "There is no professor in the database with that ID" }, 404, { "Access-Control-Allow-Origin": "*" } if data["userID"]: if data["userID"] == -1: if UserModel.find_by_id(dinnerOfInterest.userID): user = UserModel.find_by_id(dinnerOfInterest.userID) user.dinnerCount -= 1 user.semDinnerCount -= 1 user.save_to_db() dinnerOfInterest.userID = None elif not UserModel.find_by_id(data["userID"]): return { "Message": "There is no user in the database with that ID" }, 404, { "Access-Control-Allow-Origin": "*" } elif UserModel.find_by_id(data["userID"]): dinnerOfInterest.userID = data["userID"] dinnerOfInterest.timeStamp = data["timeStamp"] dinnerOfInterest.topic = data["topic"] dinnerOfInterest.description = data["description"] dinnerOfInterest.studentLimit = data["studentLimit"] dinnerOfInterest.address = data["address"] dinnerOfInterest.dietaryRestrictions = data["dietaryRestrictions"] if ProfessorModel.find_by_id(dinnerOfInterest.professorID): professor = ProfessorModel.find_by_id( dinnerOfInterest.professorID) professor.dinnerCount -= 1 professor.save_to_db() dinnerOfInterest.professorID = data["professorID"] dinnerOfInterest.catering = data["catering"] dinnerOfInterest.transportation = data["transportation"] dinnerOfInterest.invitationSentTimeStamp = data[ "invitationSentTimeStamp"] # Assign new userID else: if not ProfessorModel.find_by_id(data["professorID"]): return { "Message": "There is no professor in the database with that ID" }, 404, { "Access-Control-Allow-Origin": "*" } if not UserModel.find_by_id( data["userID"]) or data["userID"] != -1: return { "Message": "There is no user in the database with that ID" }, 404, { "Access-Control-Allow-Origin": "*" } dinnerOfInterest = DinnerModel(id=id, **data) # If the dinner gains a userID, but is not completely done "not 2", then update the status to 1, which # means it is claimed but does not have a user yet. if dinnerOfInterest.userID and dinnerOfInterest.status is not 2: dinnerOfInterest.status = 1 dinnerOfInterest.save_to_db() # increase the number of dinners for this new userID if data["userID"] and UserModel.find_by_id(data["userID"]): user = UserModel.find_by_id(data["userID"]) user.dinnerCount += 1 user.semDinnerCount += 1 user.save_to_db() professor = ProfessorModel.find_by_id(data["professorID"]) professor.dinnerCount += 1 professor.save_to_db() return dinnerOfInterest.json(), 200, { "Access-Control-Allow-Origin": "*" }