def setUp(self): self.auth_service = AuthService() self.account = Account.objects.create(username="******", password="******", name="thename", is_logged_in=False)
def commands(request): auth_service = AuthService() cmds = [ Command("cr_account", "Create Account", 0xC, True), Command("set_password", "Change Password", 0xF, True), Command("update_contact", "Update Contact Info", 0xF, True), Command("view_contact_info", "Users", 0xF, True), Command("cr_course", "Create Course", 0xC, True), Command("my_courses", "My Courses", 0x2, True), Command("view_courses", "Courses", 0xC, True), Command("my_courses_ta", "My Courses Ta", 0x1, True), Command("notify", "Notify", 0xA, True), ] allowed_commands = [ command for command in cmds if auth_service.is_authorized( request.session.get('username', None), command.req_permissions) ] return { 'commands': allowed_commands, 'username': request.session.get('username', '').lower(), 'active': request.path.strip('/') }
def logout(auth_service: AuthService): try: auth = auth_service.validate(request.headers["Authorization"]) if not auth: return jsonify({"message": "Not authorized"}), 401 auth = auth_service.delete(auth.id) return jsonify({"auth": AuthVo(auth).to_dict()}), 200 except Exception as e: logger.error(e) return jsonify({'message': 'Failed ...'}), 500
def _bind(binder): # Auth auth_repository = AuthRepository(db) auth_service = AuthService(auth_repository) binder.bind(AuthRepository, to=auth_repository, scope=request) binder.bind(AuthService, to=auth_service, scope=request) # File file_repository = FileRepository(db) file_service = FileService(file_repository) binder.bind(FileRepository, to=file_repository, scope=request) binder.bind(FileService, to=file_service, scope=request) # User user_repository = UserRepository(db) user_service = UserService(user_repository) binder.bind(UserRepository, to=user_repository, scope=request) binder.bind(UserService, to=user_service, scope=request) # Tag tag_repository = TagRepository(db) binder.bind(TagRepository, to=tag_repository, scope=request) # Note note_repository = NoteRepository(db) note_service = NoteService(note_repository, tag_repository) binder.bind(NoteRepository, to=note_repository, scope=request) binder.bind(NoteService, to=note_service, scope=request)
def signin(auth_service: AuthService, user_serivce: UserService): try: auth = auth_service.validate(request.headers["Authorization"]) if not auth: return jsonify({"message": "Not authorized"}), 401 return jsonify({"auth": AuthVo(auth).to_dict(), "user": UserVo(auth.user).to_dict()}), 200 except Exception as e: logger.error(e) return jsonify({'message': 'Failed ...'}), 500
def delete(id: str, user_service: UserService, auth_service: AuthService): try: auth = auth_service.validate(request.headers["Authorization"]) if not auth: return jsonify({"message": "Not authorized"}), 401 user = user_service.delete(id) return jsonify({"user": UserVo(user).to_dict()}), 200 except Exception as e: logger.error(e) return jsonify({'message': 'Failed ...'}), 500
def signup(auth_service: AuthService, user_service: UserService): try: form = json.loads(request.data.decode('utf-8')) user = user_service.create(copy.deepcopy(form)) auth = auth_service.login(copy.deepcopy(form), user.password) return jsonify({"auth": AuthVo(auth).to_dict(), "user": UserVo(user).to_dict()}), 200 except Exception as e: logger.error(e) return jsonify({'message': 'Failed ...'}), 500
def delete(id: str, note_service: NoteService, auth_service: AuthService): try: auth = auth_service.validate(request.headers["Authorization"]) if not auth: return jsonify({"message": "Not authorized"}), 401 note_model = note_service.delete(id) note = NoteVo(note_model).to_dict() if note_model else {} return jsonify({"note": note}), 200 except Exception as e: logger.error(e) return jsonify({'message': 'Failed ...'}), 500
def login(auth_service: AuthService, user_service: UserService): try: form = json.loads(request.data.decode('utf-8')) user = user_service.find_by_email(form["email"]) if not user: return jsonify({"message": "User is not found."}), 400 auth = auth_service.login(form, user.password) return jsonify({"auth": AuthVo(auth).to_dict(), "user": UserVo(user).to_dict()}), 200 except Exception as e: logger.error(e) return jsonify({'message': 'Failed ...'}), 500
def signup(self, request: Any) -> str: try: if request.method != 'POST': return jsonify({}) data = json.loads(request.data.decode('utf-8')) if 'email' not in data or 'name' not in data or 'password' not in data: abort(400, {'message': 'Incorrect form submission'}) response = AuthService(self.context).signup(data) return jsonify(response) except Exception as e: self.logger.error(e) abort(500, {'message': 'Failed to signup ...'})
def upload(file_service: FileService, auth_service: AuthService): try: auth = auth_service.validate(request.headers["Authorization"]) if not auth: return jsonify({"message": "Not authorized"}), 401 if not request.files: return jsonify({'message': 'Fail is not found ...'}), 400 file_ = request.files.get('file') file_model = file_service.create(auth.user.id, file_) return jsonify({"file": FileVo(file_model).to_dict()}), 200 except Exception as e: logger.error(e) return jsonify({'message': 'Failed ...'}), 500
def update(note_service: NoteService, auth_service: AuthService): try: auth = auth_service.validate(request.headers["Authorization"]) if not auth: return jsonify({"message": "Not authorized"}), 401 fields = json.loads(request.form["fields"]) logger.error(fields["tags"]) logger.error(type(fields["tags"])) fields = _convert_to_snake_case(fields) note = note_service.update(fields) return jsonify({"note": NoteVo(note).to_dict()}), 200 except Exception as e: logger.error(e) return jsonify({'message': 'Failed ...'}), 500
def logout(self, request: Any) -> str: try: if request.method != 'DELETE': return jsonify({}) authorization = request.headers["Authorization"] if not authorization: abort(400, {'message': 'Authorization does not exist.'}) token = authorization.split()[1] response = AuthService(self.context).logout(token) if not response: abort(403, {'message': 'Not authorized.'}) return jsonify(response) except Exception as e: self.logger.error(e) abort(500, {'message': 'Failed to logout ...'})
def update(user_service: UserService, file_service: FileService, auth_service: AuthService): try: auth = auth_service.validate(request.headers["Authorization"]) if not auth: return jsonify({"message": "Not authorized"}), 401 fields = json.loads(request.form["fields"]) if request.files: file_ = request.files.get('file') file_model = file_service.create(fields["id"], file_) fields["avatar"] = file_model.path user = user_service.update(fields) return jsonify({"user": UserVo(user).to_dict()}), 200 except Exception as e: logger.error(e) return jsonify({'message': 'Failed ...'}), 500
from django.shortcuts import redirect from app.services.auth_service import AuthService from app.models import Account auth_service = AuthService() paths = { "cr_account": 0xC, "update_contact": 0xF, "view_contact_info": 0xF, "assign_ta_course": 0x8, "assign_ins": 0x8, "view_courses": 0xC, "edit_account": 0xC, "course_details": 0xF, "cr_course": 0xC, "set_password": 0xF, "cr_lab": 0xC, "assign_ta_lab": 0xA, "view_lab_details": 0xC, "my_courses": 0x2, "my_courses_ta": 0x1 } class VerifyPermissions(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path.strip('/') in paths:
class TestAuthService(TestCase): def setUp(self): self.auth_service = AuthService() self.account = Account.objects.create(username="******", password="******", name="thename", is_logged_in=False) def test_login_happy_path(self): expected_response = "Welcome, thename." actual_response = self.auth_service.login("theuser", "thepassword") self.assertEqual(expected_response, actual_response) account = Account.objects.filter(username__iexact="theuser").first() self.assertEqual(account.is_logged_in, True) def test_login_already_logged_in(self): self.account.is_logged_in = True self.account.save() self.auth_service.current_account = self.account expected_response = "Welcome, thename." actual_response = self.auth_service.login("theuser", "thepassword") self.assertEqual(expected_response, actual_response) account = Account.objects.filter(username__iexact="theuser").first() self.assertEqual(account.is_logged_in, True) def test_login_someone_else_already_logged_in(self): self.account.is_logged_in = True self.account.save() self.auth_service.current_account = self.account Account.objects.create(username="******", password="******", name="othername") expected_response = "Welcome, othername." actual_response = self.auth_service.login("otheruser", "thepassword") self.assertEqual(expected_response, actual_response) logged_in_account = Account.objects.filter( username__iexact="theuser").first() logged_out_account = Account.objects.filter( username__iexact="otheruser").first() self.assertEqual(logged_in_account.is_logged_in, True) self.assertEqual(logged_out_account.is_logged_in, True) def test_login_user_does_not_exist(self): expected_response = "Incorrect username." actual_response = self.auth_service.login("esmith", "thepassword") self.assertEqual(expected_response, actual_response) def test_login_wrong_password(self): expected_response = "Incorrect password." actual_response = self.auth_service.login("theuser", "wrongpassword") self.assertEqual(expected_response, actual_response) account = Account.objects.filter(username__iexact="theuser").first() self.assertEqual(account.is_logged_in, False) def test_is_logged_in_true(self): self.account.is_logged_in = True self.account.save() self.auth_service.current_account = self.account expected_response = True actual_response = self.auth_service.is_logged_in("theuser") self.assertEqual(expected_response, actual_response) def test_is_logged_in_false_user_exists(self): expected_response = False actual_response = self.auth_service.is_logged_in("theuser") self.assertEqual(expected_response, actual_response) def test_is_logged_in_false_user_dne(self): expected_response = False actual_response = self.auth_service.is_logged_in("theuser") self.assertEqual(expected_response, actual_response) def test_is_authorized_true(self): self.account.roles = 0xC self.account.save() expected_response = True actual_response = self.auth_service.is_authorized("theuser", 0x8) self.assertEqual(expected_response, actual_response) def test_is_authorized_false(self): self.account.roles = 0x1 self.account.save() expected_response = False actual_response = self.auth_service.is_authorized("theuser", 0x4) self.assertEqual(expected_response, actual_response) def test_is_authorized_user_dne(self): actual_response = self.auth_service.is_authorized("nonuser", 0x4) expected_response = False self.assertEqual(expected_response, actual_response) def test_logout_happy_path(self): self.account.is_logged_in = True self.account.save() self.auth_service.current_account = self.account expected_response = "You are now logged out." actual_response = self.auth_service.logout("theuser") self.assertEqual(expected_response, actual_response) self.assertEqual(self.auth_service.get_current_username(), None) account = Account.objects.filter(username__iexact="theuser").first() self.assertEqual(account.is_logged_in, False) def test_logout_user_does_not_exist(self): expected_response = "Account for user anotheruser does not exist." actual_response = self.auth_service.logout("anotheruser") self.assertEqual(expected_response, actual_response) def test_logout_user_is_none(self): expected_response = "You need to log in first." actual_response = self.auth_service.logout(None) self.assertEqual(expected_response, actual_response) def test_logout_not_logged_in(self): expected_response = "You need to log in first." actual_response = self.auth_service.logout("theuser") self.assertEqual(expected_response, actual_response) def test_set_password_happy_path(self): self.auth_service.current_account = self.account expected_response = "Your password has been updated." actual_response = self.auth_service.set_password( self.account.username, "thepassword", "newpassword") self.assertEqual(expected_response, actual_response) account = Account.objects.filter(username__iexact="theuser").first() self.assertEqual("newpassword", account.password) def test_set_password_wrong_password(self): expected_response = "Incorrect current password." actual_response = self.auth_service.set_password( self.account.username, "password", "newpassword") self.assertEqual(expected_response, actual_response) account = Account.objects.filter(username__iexact="theuser").first() self.assertEqual("thepassword", account.password)
def setUp(self): self.auth_service = AuthService()
class AuthServiceTest(unittest.TestCase): @classmethod def setUpClass(cls): if DatabaseContext.THREADS_MANAGER_CYCLING == False: DatabaseContext.THREADS_MANAGER_CYCLING = True ThreadsManager().start() CollectionsSimulator.build_users_col() def setUp(self): self.auth_service = AuthService() @classmethod def tearDownClass(cls): CollectionsSimulator.clean() DatabaseContext.THREADS_MANAGER_CYCLING = False def test_login_success_with_password(self): result = self.auth_service.login('admin', 'admin') self.assertEqual(result['login'], 'admin') def test_login_fail_with_password(self): try: self.auth_service.login('admin', 'false') self.fail() except AppException as e: self.assertEqual(e.message, 'Authentication failed') def test_get_user_by_token(self): result = self.auth_service.get_user_by_token( 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NzU5OTEwNDUsInN1YiI6MX0._jTMkfDl2RKzY_r6nUDVwFG8xlEuZPFFr7zvqWXJmcM' ) self.assertEqual(result['id'], 1) self.assertEqual(result['login'], 'admin') def test_fail_get_user_by_invalid_token(self): try: self.auth_service.get_user_by_token( 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NzU5OTEwNDUsInN1YiI6MX0._jTMkfDl2RKzY_r6nUDVwFG8xlEuZPFFr7zvqWXJmcN' ) self.fail() except AppException as e: self.assertEqual(e.message, 'Authentication failed') def test_logout(self): token = self.auth_service.login('admin', 'admin')['token'] result = self.auth_service.logout(token) self.assertTrue(token not in result['tokens']) def test_logout_all(self): token = self.auth_service.login('admin', 'admin')['token'] result = self.auth_service.logout_all(token) self.assertEqual(len(result['tokens']), 0) def test_create_user(self): new_user = {'login': '******', 'password': '******'} user = self.auth_service.create_user(new_user) self.assertEqual(new_user['login'], user['login']) self.assertNotEqual(new_user['password'], user['password']) self.assertTrue('id' in user) self.assertTrue('tokens' in user) def suite(): return unittest.TestLoader.loadTestsFromTestCase(AuthServiceTest)
from django.contrib import admin from django.urls import path import app.views from app.services.auth_service import AuthService from app.services.account_service import AccountService from app.services.course_service import CourseService from app.services.ta_service import TaService deps = { 'auth_service': AuthService(), 'account_service': AccountService(), 'course_service': CourseService(), 'ta_service': TaService() } urlpatterns = [ path('admin/', admin.site.urls), path("", app.views.Dashboard.as_view(**deps)), path("dashboard/", app.views.Dashboard.as_view(**deps)), path("view_contact_info/", app.views.ViewAccounts.as_view(**deps)), path("login/", app.views.Login.as_view(**deps)), path("logout/", app.views.Logout.as_view(**deps)), path("cr_account/", app.views.CreateAccount.as_view(**deps)), path("edit_account/", app.views.EditAccount.as_view(**deps)), path("update_contact/", app.views.UpdateContactInfo.as_view(**deps)), path("view_courses/", app.views.ViewCourses.as_view(**deps)), path("my_courses/", app.views.MyCourses.as_view(**deps)), path("course_details/", app.views.CourseDetails.as_view(**deps)), path("assign_ta_course/", app.views.AssignTaCourse.as_view(**deps)), path("cr_lab/", app.views.CreateLab.as_view(**deps)), path("cr_course/", app.views.CreateCourse.as_view(**deps)),