def get(self): # Get token as params from the url token = request.args.get('emailtoken') # Decode the token by calling the decode_email_token method email = User.decode_email_token(token) # search through the database to find email user = User.query.filter_by(email=email).first() # If user is not yet confirm then confirm User if user.confirmed == False: try: user.confirmed = True user.confirmed_on_date = datetime.now() user.save() response = jsonify({ 'message': 'Your have confirmed your accounts. Thanks!' }) response.status_code = 200 return response except Exception as e: # An error occured, therefore return a string message containing the error response = jsonify({ 'message': str(e), }) response.status_code = 500 return response # If user is already confirmed return a message to the user else: response = jsonify({ 'message': 'This Account has already been confirmed.' }) response.status_code = 409 return response
def post(self): # Get all required variables from the user password_token = request.args.get('resettoken') password = request.form.get('password') confirm_password = request.form.get('confirm_password') # Validates User input if password == None or password == '': response = jsonify({'message': "This field is required."}) response.status_code = 400 return response if confirm_password == None or confirm_password == '': response = jsonify({'message': "This field is required."}) response.status_code = 400 return response if password != confirm_password: response = jsonify({ 'message': 'Oops! Sorry. The passwords you inputted are not the same.' }) response.status_code = 400 return response if password_token == None or password_token == '': response = jsonify( {'message': 'You are not authorise to view this page.'}) response.status_code = 403 return response # Decode the token that is passed in the password reset link password_token_decode = User.decode_email_token(password_token) # Find user with the email in the database user = User.query.filter_by(email=password_token_decode).first() # Hash the new password gotten from user hash_password = user.generate_password_hash(password) # Check if the hash password is the same with password provided check_password_validity = user.check_password_validation( hash_password.decode(), password) if user and check_password_validity: # If all conditions are met update the user details with the new password user.password = hash_password.decode() user.save() # respond with a success message response = jsonify({ 'message': 'Password successfully updated, you can now login with your new password.' }) response.status_code = 200 return response else: # else return an error message response = jsonify({'message': 'Invalid Token.'}) response.status_code = 500 return response
def test_email_already_confirmed(self): """Test for email already confirmed by user""" email_token = User.generate_email_token(self, email='*****@*****.**') email_res = self.client().get( '/api/auth/email-confirmation/?emailtoken=' + email_token.decode()) # Get the results returned in json format result = json.loads(email_res.data.decode()) # assert that this response must contain an error message # and an error status code 409(Conflit) self.assertEqual(result['message'], "This Account has already been confirmed.") self.assertEqual(email_res.status_code, 409)
def setUp(self): """Set up test variables.""" self.app = create_app(config_name="testing") # initialize the test client self.client = self.app.test_client # This is the user test json data with a predefined email and password self.user_data = { "email": "*****@*****.**", "password": "******", "username": "******", "phone_number": "09067582433", "confirm_password": "******" } # This is the user test json data with a predefined email, password and confirmed = True self.confirmed_user_data = { "email": "*****@*****.**", "password": "******", "username": "******", "phone_number": "09067582777", "confirm_password": "******" } with self.app.app_context(): # Create all tables db.session.close() db.drop_all() db.create_all() user_1 = User(email="*****@*****.**", password="******", username="******", phone_number="09067582999", confirmed=False, firstname='', lastname='') user_2 = User(email="*****@*****.**", password="******", username="******", phone_number="09067582777", confirmed=True, firstname='', lastname='') user_1.save() user_2.save()
def post(self): """Handle POST request URL -----> /api/auth/login""" try: # Get the user object using the email (unique to every user) email = request.form.get('email').lstrip() password = request.form.get('password') if email == '' or password == '': response = jsonify({'message': 'This field is required.'}) response.status_code = 400 return response if validate_email(email) == False: response = jsonify({'message': 'Invalid Email Inputed'}) response.status_code = 400 return response # Try to authenticate the found user using their password password_hash = User.generate_password_hash(self, password) user = User.query.filter_by(email=email).first() # The condition below checks if user exists and if the password validation returns True if user and user.check_password_validation(user.password, password): # Generate the access token. This will be used as the authorisation header access_token = user.generate_token(user.id) if access_token: response = jsonify({ 'message': 'Welcome! You are now logged in.', 'access_token': access_token.decode(), 'email_validation': user.confirmed }) response.status_code = 200 return response else: # User does not exist. Therefore, return an error message to the user response = jsonify( {'message': 'Invalid credentials, Please try again.'}) response.status_code = 401 return response except Exception as e: # Create a response containing a string error message response = jsonify({'message': str(e)}) response.status_code = 500 return response
def test_for_resend_email_confirm_link(self): """Test for resend email confirmation mail when user request for it""" self.user_data['email'] = '*****@*****.**' res = self.client().post('/api/auth/reverify-email', data=self.user_data) email_token = User.generate_email_token(self, email=self.user_data) # Get the results returned in json format result = json.loads(res.data.decode()) # assert that this response must contain an response # and a status code 200(Success) self.assertEqual( result['message'], 'An email confirmation link has been sent to this email: %s' % ("*****@*****.**")) self.assertEqual(res.status_code, 200)
def test_email_confirmation_route_valid_token(self): """Test for email confirmation mail been sent""" self.email_user_data = { "email": "*****@*****.**", "password": "******", "username": "******", "phone_number": "09067582555", "confirm_password": "******" } res = self.client().post('/api/auth/signup', data=self.email_user_data) email_token = User.generate_email_token(self, email='*****@*****.**') email_res = self.client().get( '/api/auth/email-confirmation/?emailtoken=' + email_token.decode()) # Get the results returned in json format result = json.loads(email_res.data.decode()) # assert that this response must contain an error message # and an error status code 200(Successful) self.assertEqual(result['message'], "Your have confirmed your accounts. Thanks!") self.assertEqual(email_res.status_code, 200)
def post(self): email_input = request.form.get('email').lstrip() email = email_input.lower() # Remove whitespaces from left and right username_input = request.form.get('username').lstrip() username = username_input.lower() password = request.form.get('password') confirm_password = request.form.get('confirm_password') phone_number = request.form.get('phone_number').lstrip() firstname = request.form.get('firstname') lastname = request.form.get('lastname') confirmed = False # validate email as a valid email address without using regex is_valid = validate_email(email) # validate user inputs if email == '' or password == '' or phone_number == '' or username == '': response = jsonify({'message': 'This field is required.'}) response.status_code = 400 return response if len(password) < 6: response = jsonify( {'message': 'Password should be greater than 6 characters'}) response.status_code = 400 return response if password != confirm_password: response = jsonify({ 'message': 'Oops! Sorry. The passwords you inputted are not the same.' }) response.status_code = 400 return response # This validate if what is inputed are all numbers if phone_number.isnumeric() == False: response = jsonify( {'message': 'Phone numbers must all contain numbers'}) response.status_code = 400 return response if len(phone_number) < 8: response = jsonify({ 'message': 'Phone number should be greater than 8 characters' }) response.status_code = 400 return response if len(username) < 2: response = jsonify( {'message': 'Username should be greater than 2 characters'}) response.status_code = 400 return response if is_valid == False: response = jsonify({'message': 'Invalid Email Inputed'}) response.status_code = 400 return response else: password_hash = User.generate_password_hash(self, password) # Find user email in the database user = User.query.filter_by(email=email, phone_number=phone_number).first() # If User is not found do this if user == None: try: # Register the user email = email password = password_hash phone_number = phone_number firstname = firstname lastname = lastname confirmed = confirmed user = User(email=email, password=password, phone_number=phone_number, firstname=firstname, lastname=lastname, username=username, confirmed=confirmed) user.save() # Generate Authentication token for the user using the user_id access_token = user.generate_token(user.id) auth_user_email = user.generate_email_token(user.email) confirm_url = 'http://%s/api/auth/email-confirmation/?emailtoken=%s' % ( os.getenv('HOST_URL'), auth_user_email.decode()) html = email_template(confirm_url) subject = "Please confirm your mail" send_email(user.email, subject, html) response = jsonify({ 'email': user.email, 'password': user.password, 'username': user.username, 'access_token': access_token.decode(), 'email_validation': user.confirmed, 'message': 'Registration Successful. An email has been sent to this email: ' + user.email + '. Please confirm your email to proceed.' }) # return a response notifying the user that they registered response.status_code = 201 return response except Exception as e: # An error occured, therefore return a string message containing the error response = jsonify({ 'message': str(e), }) response.status_code = 409 return response else: # There is an existing user. We don't want to register users twice # Return a message to the user telling them that the email, username or phone number is been used by another user response = jsonify({ 'message': 'Email or phone number is already been used by an existing user. Please try again.' }) response.status_code = 409 return response