def confirm_registration(token: str): """ Determines whether a user's email registration has been confirmed. Determines whether a user's email registration was invalid, previously confirmed, or just confirmed. Arguments: token: Serialized and signed email address as a URL safe string. Returns: A message that indicates if the confirmation was invalid, already happened, or just happened, and the HTTP response code. """ email_from_token = confirm_token(token) if not email_from_token or email_from_token is None: return messages.EMAIL_EXPIRED_OR_TOKEN_IS_INVALID, HTTPStatus.BAD_REQUEST user = UserModel.find_by_email(email_from_token) if user.is_email_verified: return messages.ACCOUNT_ALREADY_CONFIRMED, HTTPStatus.OK else: user.is_email_verified = True user.email_verification_date = datetime.now() user.save_to_db() return messages.ACCOUNT_ALREADY_CONFIRMED_AND_THANKS, HTTPStatus.OK
def send_invite_to_mod(firebase_id: str, email: str): mod_email = email try: user = UserModel.find_by_firebase_id(firebase_id) except Exception as e: return messages.CANNOT_FIND_USER, 400 if user.is_donor: mod_exists = UserModel.find_by_email(mod_email) if mod_exists: if mod_exists.is_moderator: return {"message": f"Moderator is already registered. Do you want to proceed?"}, 409 else: role = "donor" if mod_exists.is_donor else "recipient" if mod_exists.is_recipient else "moderator" return {"message": f"User with this email is already signed up as a {role}"}, 400 else: otp = random.randint(111111,999999) invite = InvitesModel(user, email, otp) invite.save_to_db() send_invite_mod_email(user.name, otp, email) return {"message": "Invitation sent"}, 200 else: return {"message": "User cannot invite moderator"}, 401
def get_user_by_email(email: str): """ Retrieves a user's profile information using a specified email. Provides the user profile of the user whose email matches the one specified. Arguments: email: The email of the user to be searched. Returns: The UserModel class of the user whose email was searched, containing the public information of their profile such as bio, location, etc. """ return UserModel.find_by_email(email)
def authenticate(email: str, password: str): """ User login process""" try: user = auth.get_user_by_email(email) if user.email_verified != True: return {"message": "Email is not verified, Please verify email first"}, 400 else: local_user = UserModel.find_by_email(email) if local_user.is_email_verified: pass else: local_user.is_email_verified = True db.session.commit() except Exception as e: return {"message": e.args[0]}, 400 json_string = {"email":email,"password":password,"returnSecureToken":True} API_KEY = environ.get('API_KEY') url = 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=' + API_KEY res = requests.post(url, data=json_string) json_res = json.loads(res.text) if "error" in json_res.keys(): error_message = json_res["error"] if error_message["message"] == "INVALID_PASSWORD": return {"message": "Password is incorrect"}, 401 else: return { "message": error_message["message"]}, 401 if "idToken" in json_res.keys(): '''Sample response of role i.e. 0''' json_res["role"] = 3 return json_res, 200
def create_user(data: Dict[str, str]): """Creates a new user. Creates a new user with provided data. Arguments: data: A list containing the user's name, username, password, and email, as well as recognition that they have read and agree to the Terms and Conditions. Returns: A tuple with two elements. The first element is a dictionary containing a key 'message' containing a string which indicates whether or not the user was created successfully. The second is the HTTP response code. """ name = data["name"] username = data["username"] password = data["password"] email = data["email"] terms_and_conditions_checked = data["terms_and_conditions_checked"] existing_user = UserModel.find_by_username(data["username"]) if existing_user: return messages.USER_USES_A_USERNAME_THAT_ALREADY_EXISTS, HTTPStatus.CONFLICT else: existing_user = UserModel.find_by_email(data["email"]) if existing_user: return messages.USER_USES_AN_EMAIL_ID_THAT_ALREADY_EXISTS, HTTPStatus.CONFLICT user = UserModel(name, username, password, email, terms_and_conditions_checked) if "need_mentoring" in data: user.need_mentoring = data["need_mentoring"] if "available_to_mentor" in data: user.available_to_mentor = data["available_to_mentor"] user.save_to_db() return messages.USER_WAS_CREATED_SUCCESSFULLY, HTTPStatus.CREATED
def authenticate(username_or_email: str, password: str): """ User login process. The user can login with two options: -> username + password -> email + password Arguments: username_or_email: The username or email associated with the account being authenticated. password: The password associated with the account being authenticated. Returns: Returns authenticated user if username and password are valid, otherwise returns None. """ if is_email_valid(username_or_email): user = UserModel.find_by_email(username_or_email) else: user = UserModel.find_by_username(username_or_email) if user and user.check_password(password): return user return None
def accept_application(firebase_id: str, data: Dict[str, str]): try: user = UserModel.find_by_firebase_id(firebase_id) except Exception as e: return messages.CANNOT_FIND_USER, 400 if user.is_donor == False: return {"message": "This user cannot accept application"}, 403 application_id = data["application_id"] donating_full_amount = data["donating_full_amount"] amount = data["amount"] moderator_email = data["moderator_email"] application = ApplicationModel.find_by_id(application_id) if application.remaining_amount == 0: return {"message": "No further amount needed"}, 409 if application in user.donating: return {"message": "Already donating to this application"}, 409 application.donor.append(user) application.no_of_donors = application.no_of_donors + 1 if donating_full_amount: application.remaining_amount = 0 else: application.remaining_amount = application.remaining_amount - amount ''' Find existing moderator ''' moderator = UserModel.find_by_email(moderator_email.lower()) if moderator: if moderator.is_moderator: application.moderator.append(moderator) application.moderator_email = moderator.email application.save_to_db() reserved = ReservedApplicationModel(application=application, donor=user, moderator=moderator, is_active=True, verified=False, amount=amount) reserved.save_to_db() if moderator.firebase_id == "": return { "message": "Application accepted. Moderator is already invited, please ask moderator to register by code given earlier." }, 200 else: return {"message": "Application accepted"}, 200 else: role = "donor" if moderator.is_donor else "recipient" if moderator.is_recipient else "moderator" return { "message": f"Invited Moderator is register as a {role}" }, 409 else: temp_mod_user = UserModel("", "", moderator_email.lower(), "", 2) temp_mod_user.save_to_db() application.moderator.append(temp_mod_user) reserved = ReservedApplicationModel(application=application, donor=user, moderator=temp_mod_user, is_active=True, verified=False, amount=amount) reserved.save_to_db() application.save_to_db() ''' Send invite to moderator ''' invite_code = random.randint(111111, 999999) invite = InvitesModel(user, temp_mod_user, moderator_email, invite_code) invite.save_to_db() send_invite_mod_email(user.name, invite_code, moderator_email) return { "message": "Application accepted. Waiting for moderator to accept the inivite" }, 200 return {"message": "Application accepted"}, 200
def create_user(data: Dict[str, str]): """Creates a new user""" name = data['name'] email = data['email'] password = data['password'] role = data['role'] existing_user = UserModel.find_by_email(email.lower()) if existing_user and existing_user.firebase_id != "": return {"message": "User already exists"}, 400 if existing_user and existing_user.firebase_id == "" and role != 2: return {"message": "User is invited as a moderator. Please sign up as a moderator with unique code"}, 400 if role == 2: if "otp" in data: invitation = InvitesModel.find_by_mod_email(email.lower()) if invitation: if data["otp"] != invitation.unique_code: return {"message": "Code is incorrect"}, 401 else: return {"message": "Sorry! Invite is needed to be a moderator"}, 400 else: return {"message": "Please send unique code"}, 400 print("Passed") try: user = auth.create_user( email=email, email_verified=False, password=password, display_name=name, disabled=False ) link = auth.generate_email_verification_link(email, action_code_settings=None) ''' To implement, send verification link usingg # send_verification_link(email,link) ''' except Exception as e: return {"message": str(e)}, 400 try: firebase_details = auth.get_user_by_email(email) uid = firebase_details.uid firebase_email = firebase_details.email ''' Existing user is a temporary moderator user ''' if existing_user: existing_user.firebase_id = uid existing_user.name = name existing_user.email = firebase_email existing_user.save_to_db() else: user = UserModel(uid, name, firebase_email, password, role) user.save_to_db() except Exception as e: print(e) send_email_verification_message(link, email) return {"verify_link": link, "message" : "User was created successfully. Please check your email to verify the account" }, 201