def request_user_reset(): """ Password reset request page accessed by '/auth/reset'. Methods: GET, POST. Permissions: Accessible to ALL. Returns: A Flask template. """ try: form = ResetRequestForm() if form.validate_on_submit(): UserService.send_reset_email(form.email.data) flash('Sent reset email!', 'success') return redirect(url_for('auth.login')) return render_template('reset_request.html', form=form) except: # pylint: disable=bare-except db.session.rollback() flash('An error was encountered.', 'danger') logging.exception(traceback.format_exc()) return redirect(url_for('auth.login'))
def test_user_same_email(self): """ Tests editing a user when everything works. Duplicate email is okay, since it is the one! """ UserService.edit_user(self.test_user.id, '*****@*****.**', 'John', 'Smith') self.assertEqual(self.test_user.email, '*****@*****.**') self.assertEqual(self.test_user.first_name, 'John') self.assertEqual(self.test_user.last_name, 'Smith')
def reset_user(token): """ Password reset page accessed by '/auth/reset/<token>'. Methods: GET, POST. Permissions: Accessible to ALL. Args: token: A password reset token. Returns: A Flask template. """ try: form = ResetPasswordForm() if form.validate_on_submit(): email = serializer.decode_attr(token, 'ovs-reset-email') user = UserService.get_user_by_email(email) UserService.reset_user(user, form.password.data) db.session.commit() flash('Successfully updated password!', 'success') return redirect(url_for('/.landing_page')) return render_template('reset_password.html', form=form) except: # pylint: disable=bare-except db.session.rollback() flash('An error was encountered', 'danger') logging.exception(traceback.format_exc()) return redirect(url_for('auth.login'))
def test_edit_user( self): # cases : bad user, overwrite, same email, normal """ Tests editing a user when everything works""" UserService.edit_user(self.test_user.id, '*****@*****.**', 'John', 'Smith') self.assertEqual(self.test_user.email, '*****@*****.**') self.assertEqual(self.test_user.first_name, 'John') self.assertEqual(self.test_user.last_name, 'Smith')
def test_delete_user_null(self): """ Tests that nothing breaks when deleting a nonexistant resident """ expected = User.query.count() # This id is NOT the resident with self.assertRaises(AttributeError): UserService.delete_user(self.test_user.id + 1) self.assertEqual(User.query.count(), expected)
def create_test_resident(self): """ Creates a test resident for use in testing """ self.test_resident_info = ('*****@*****.**', 'Bob', 'Ross', 'RESIDENT') self.test_admin_info = ('*****@*****.**', 'Bob', 'Ross', 'ADMIN') self.test_user = UserService.create_user(*self.test_resident_info) self.test_admin = UserService.create_user(*self.test_admin_info) self.test_resident = ResidentService.get_resident_by_id( self.test_user.id) self.test_room = RoomService.create_room('1', 'Good', 'Single')
def test_create_user_doesnt_send_email(self, mock_mail): """ Tests that creating a user without a default password doesn't send an email. Args: mock_mail: The mock_client for the patched function. This allows us to check if an email would get sent without actually sending one. """ UserService.create_user('*****@*****.**', 'Bob', 'Ross', 'ADMIN', password='******') mock_mail.assert_not_called()
def test_edit_user_duplicate_email(self): """ Tests edit resident to an existing email """ UserService.create_user('*****@*****.**', '', '', 'ADMIN') with self.assertRaises(ValueError): UserService.edit_user(self.test_user.id, '*****@*****.**', 'John', 'Smith') self.assertEqual(self.test_user.email, self.test_user_info[0]) self.assertEqual(self.test_user.first_name, self.test_user_info[1]) self.assertEqual(self.test_user.last_name, self.test_user_info[2])
def test_delete_user(self): """ Tests that a user can be deleted """ user = UserService.create_user('*****@*****.**', '', '', 'STAFF') expected = User.query.count() - 1 # check if deletion successful UserService.delete_user(user.id) self.assertEqual(expected, User.query.count())
def create_test_users(self): """ Creates two RESIDENT accounts and one ADMIN account for use in testing """ DataGen.create_default_room() self.test_resident_1 = UserService.create_user('*****@*****.**', 'Bob', 'Ross', 'RESIDENT') self.test_resident_2 = UserService.create_user('*****@*****.**', 'Joe', 'Smith', 'RESIDENT') self.test_admin = UserService.create_user('*****@*****.**', 'Jim', 'White', 'ADMIN')
def test_delete_user_resident(self): """ Tests that deleting a user deletes their resident info """ resident = UserService.create_user('*****@*****.**', 'John', 'Smith', 'RESIDENT') expected_user = User.query.count() - 1 expected_resident = Resident.query.count() - 1 UserService.delete_user(resident.id) self.assertEqual(User.query.count(), expected_user) self.assertEqual(Resident.query.count(), expected_resident)
def edit_resident(user_id, email, first_name, last_name, room_number): """ Edits an existing resident identified by user_id. Args: user_id: Unique user id. email: New email. first_name: New first name. last_name: New last name. room_number: New room number. """ from ovs.services.user_service import UserService from ovs.services.room_service import RoomService UserService.edit_user(user_id, email, first_name, last_name) RoomService.add_resident_to_room(email, room_number)
def test_get_user_by_email(self): """ Tests get_user_by_email successfully finds a user """ user = UserService.get_user_by_email(self.test_user_info[0]) self.assertEqual( (user.email, user.first_name, user.last_name, user.role), self.test_user_info) self.assertIsNotNone(user.password)
def test_delete_user_last_admin(self): """ Tests that a user can be deleted """ expected = self.db.session.query(User).count() # check if deletion successful self.assertFalse(UserService.delete_user(self.test_user.id)) self.assertEqual(self.db.session.query(User).count(), expected)
def test_create_user_sends_email(self, mock_mail): """ Tests that creating a user sends an email. Args: mock_mail: The mock_client for the patched function. This allows us to check if an email would get sent without actually sending one. """ expected_substitutions = { 'first_name': 'Bob', 'last_name': 'Ross', 'role': 'admin', 'confirm_url': ANY } UserService.create_user('*****@*****.**', 'Bob', 'Ross', 'ADMIN') mock_mail.assert_called_once_with('*****@*****.**', 'User Account Creation', templates['user_creation_email'], substitutions=expected_substitutions)
def validate_email(form, field): # pylint: disable=no-self-argument """ Checks whether email is unregistered. Args: form: The ManageResidentsForm that was submitted. field: The email field. Raises: ValidationError: If email is already in use. """ user = UserService.get_user_by_id(form.user_id.data) if user: email = user.email if (field.data != email) and UserService.get_user_by_email( field.data) is not None: raise ValidationError('A user with that email already exists') else: raise ValidationError('No user with that ID')
def test_invalid_add_resident_to_room(self): """ Tests that non-resident users cannot be added to a room """ test_user_info = ('*****@*****.**', 'Bob', 'Ross', 'ADMIN') test_user = UserService.create_user(*test_user_info) with self.assertRaises(ValueError): RoomService.add_resident_to_room(test_user.email, self.test_room.number) resident = ResidentService.get_resident_by_id(test_user.id) self.assertIsNone(resident) self.assertFalse(resident in self.test_room.occupants)
def test_add_resident_to_room(self): """ Tests that residents can be added to a room """ test_user_info = ('*****@*****.**', 'Bob', 'Ross', 'RESIDENT') test_user = UserService.create_user(*test_user_info) resident = ResidentService.get_resident_by_id(test_user.id) old_room = RoomService.get_room_by_number('') self.assertTrue(resident in old_room.occupants) RoomService.add_resident_to_room(test_user.email, self.test_room.number) self.assertEqual(resident.room_number, self.test_room.number) self.assertTrue(resident in self.test_room.occupants) self.assertFalse(resident in old_room.occupants)
def __call__(self, form, field): """ Does the validation. Args: form: The form this validator is applied to. field: The field this validator is applied to. Raises: ValidationError: If the given email is unregistered if check=True and if the given email is registered if check=False. """ email = field.data.strip() user = UserService.get_user_by_email(email) not_registered = user is None if not_registered == self.check: raise ValidationError(self.message)
def login(): """ Login in page accessed by '/auth/login'. Methods: GET, POST. Permissions: Accessible to ALL. Returns: A Flask template. """ try: login_form = LoginForm() if login_form.validate_on_submit(): email = login_form.email.data password = login_form.password.data user = UserService.get_user_by_email(email) if user is None: flash('Invalid email or password.', 'danger') return redirect(url_for('auth.login')) elif not AuthService.verify_auth(user, password): flash('Invalid email or password.', 'danger') return redirect(url_for('auth.login')) login_user(user) db.session.commit() if user.role == UserRole.RESIDENT: return redirect(url_for('resident.landing_page')) return redirect(url_for('manager.landing_page')) return render_template('login.html', login_form=login_form) except: # pylint: disable=bare-except db.session.rollback() flash('Could not log in', 'danger') logging.exception(traceback.format_exc()) return redirect(url_for('/.landing_page'))
def test_get_admin_count(self): """ Tests that get_admin_count returns the correct number of users""" UserService.create_user('*****@*****.**', 'Bob', 'Ross', 'ADMIN') expected = 2 self.assertEqual(ManagerService.get_admin_count(), expected)
def create_test_weekly_meal_plan(self): """ Creates a meal plan of WEEKLY plan type for use in testing """ UserService.create_user('*****@*****.**', '', '', 'RESIDENT') self.test_meal_plan_info = (10, 'WEEKLY', '*****@*****.**') self.test_meal_plan = MealService.create_meal_plan_for_resident_by_email( *self.test_meal_plan_info)
def test_edit_user_bad_id(self): """ Tests editing a nonexistant user""" with self.assertRaises(AttributeError): UserService.edit_user(self.test_user.id + 3, '*****@*****.**', 'John', 'Smith') # random id self.assertIsNone(UserService.get_user_by_email('*****@*****.**'))
def create_test_user(self): """ Creates a test user """ self.test_user_info = ('*****@*****.**', 'Bob', 'Ross', 'ADMIN') self.test_user = UserService.create_user(*self.test_user_info)
def test_invalid_get_user_by_email(self): """ Tests get_user_by_email does not find anyone with an invalid email """ user = UserService.get_user_by_email("*****@*****.**") self.assertIsNone(user)
def setUp(self): """ Runs before every test and clears relevant tables """ super().setUp() test_user_info = ('*****@*****.**', 'Bob', 'Smith', 'RESIDENT') UserService.create_user(*test_user_info) self.test_user = UserService.get_user_by_email('*****@*****.**')