Python django.contrib.auth.get_user() Examples
The following are 30
code examples of django.contrib.auth.get_user().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.contrib.auth
, or try the search function
.
Example #1
Source File: client.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def logout(self): """ Removes the authenticated user's cookies and session object. Causes the authenticated user to be logged out. """ from django.contrib.auth import get_user, logout request = HttpRequest() engine = import_module(settings.SESSION_ENGINE) if self.session: request.session = self.session request.user = get_user(request) else: request.session = engine.SessionStore() logout(request) self.cookies = SimpleCookie()
Example #2
Source File: client.py From python with Apache License 2.0 | 6 votes |
def logout(self): """ Removes the authenticated user's cookies and session object. Causes the authenticated user to be logged out. """ from django.contrib.auth import get_user, logout request = HttpRequest() engine = import_module(settings.SESSION_ENGINE) if self.session: request.session = self.session request.user = get_user(request) else: request.session = engine.SessionStore() logout(request) self.cookies = SimpleCookie()
Example #3
Source File: drf_auth.py From omniport-backend with GNU General Public License v3.0 | 6 votes |
def get_user_jwt(request): """ Process the request to find the user associated with the request :param request: the request which is to be authenticated :return: the user instance if authenticated, AnonymousUser() otherwise """ user = get_user(request) if user.is_authenticated: return user try: user_jwt, _ = JWTAuthentication().authenticate(Request(request)) if user_jwt is not None: return user_jwt except (AuthenticationFailed, InvalidToken, TokenError, TypeError): # There may be other exceptions but these are the only ones I could see pass return user or AnonymousUser()
Example #4
Source File: views.py From channels-obstruction with MIT License | 6 votes |
def dispatch(self, request, *args, **kwargs): # get the game by the id self.game = Game.get_by_id(kwargs['game_id']) user = get_user(request) # check to see if the game is open and available for this user # if this player is the creator, just return if self.game.creator == user or self.game.opponent == user: return super(GameView, self).dispatch(request, *args, **kwargs) # if there is no opponent and the game is not yet completed, # set the opponent as this user if not self.game.opponent and not self.game.completed: self.game.opponent = user self.game.save() return super(GameView, self).dispatch(request, *args, **kwargs) else: messages.add_message(request, messages.ERROR, 'Sorry, the selected game is not available.') return redirect('/lobby/')
Example #5
Source File: middleware.py From django-aws-template with MIT License | 6 votes |
def get_cached_user(request): if not hasattr(request, '_cached_user'): try: key = CACHE_KEY.format(request.session[SESSION_KEY]) cache = caches['default'] user = cache.get(key) except KeyError: user = AnonymousUser() if user is None: user = get_user(request) cache = caches['default'] # 8 hours cache.set(key, user, 28800) logger.debug('No User Cache. Setting now: {0}, {1}'.format(key, user.username)) request._cached_user = user return request._cached_user
Example #6
Source File: test_views.py From django-mfa with MIT License | 6 votes |
def test_verify_second_factor_u2f_view(self): session = self.client.session session['verfied_otp'] = False session['verfied_u2f'] = False session.save() response = self.client.get( reverse('mfa:verify_second_factor_u2f'), follow=True) url = reverse('mfa:verify_second_factor') + \ "?next=" + settings.LOGIN_URL self.assertRedirects( response, expected_url=url, status_code=302) session['u2f_pre_verify_user_pk'] = auth.get_user(self.client).id session['u2f_pre_verify_user_backend'] = 'django.contrib.auth.backends.ModelBackend' session.save() response = self.client.get(reverse('mfa:verify_second_factor_u2f')) self.assertTemplateUsed(response, "u2f/verify_second_factor_u2f.html") # TODO : Need to Implement for Post Method
Example #7
Source File: client.py From python2017 with MIT License | 6 votes |
def logout(self): """ Removes the authenticated user's cookies and session object. Causes the authenticated user to be logged out. """ from django.contrib.auth import get_user, logout request = HttpRequest() engine = import_module(settings.SESSION_ENGINE) if self.session: request.session = self.session request.user = get_user(request) else: request.session = engine.SessionStore() logout(request) self.cookies = SimpleCookie()
Example #8
Source File: users_api_2_3_tests.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
def test_set_password(self): username = 'test_new_user' user = User.objects.create_user(username) password = user.password auth_user = auth.get_user(self.client) self.assertNotEqual(user, auth_user) set_password_url = reverse(set_password, args=[username]) response = self.client.post(set_password_url, content_type='application/json', data=json.dumps({})) self.assertEqual(response.status_code, 400) self.assertEqual(response.reason_phrase, 'Password is required') response = self.client.post(set_password_url, content_type='application/json', data=json.dumps({ 'password': 'password123', 'firstName': 'Test'})) self.assertEqual(response.status_code, 200) user = User.objects.get(username='test_new_user') self.assertEqual(user.first_name, 'Test') self.assertFalse(user.password == password) auth_user = auth.get_user(self.client) self.assertEqual(user, auth_user)
Example #9
Source File: tests.py From OnlineJudge with MIT License | 5 votes |
def test_tfa_login(self): token = self._set_tfa() code = OtpAuth(token).totp() if len(str(code)) < 6: code = (6 - len(str(code))) * "0" + str(code) response = self.client.post(self.login_url, data={"username": self.username, "password": self.password, "tfa_code": code}) self.assertDictEqual(response.data, {"error": None, "data": "Succeeded"}) user = auth.get_user(self.client) self.assertTrue(user.is_authenticated)
Example #10
Source File: tests.py From OnlineJudge with MIT License | 5 votes |
def test_login_with_wrong_info(self): response = self.client.post(self.login_url, data={"username": self.username, "password": "invalid_password"}) self.assertDictEqual(response.data, {"error": "error", "data": "Invalid username or password"}) user = auth.get_user(self.client) self.assertFalse(user.is_authenticated)
Example #11
Source File: tests.py From OnlineJudge with MIT License | 5 votes |
def test_tfa_login_wrong_code(self): self._set_tfa() response = self.client.post(self.login_url, data={"username": self.username, "password": self.password, "tfa_code": "qqqqqq"}) self.assertDictEqual(response.data, {"error": "error", "data": "Invalid two factor verification code"}) user = auth.get_user(self.client) self.assertFalse(user.is_authenticated)
Example #12
Source File: testcases.py From django-graphql-extensions with MIT License | 5 votes |
def request(self, **request): request = WSGIRequest(self._base_environ(**request)) if self.session: request.session = self.session request.user = get_user(request) return request
Example #13
Source File: tests.py From OnlineJudge with MIT License | 5 votes |
def test_login_with_correct_info_upper_username(self): resp = self.client.post(self.login_url, data={"username": self.username.upper(), "password": self.password}) self.assertDictEqual(resp.data, {"error": None, "data": "Succeeded"}) user = auth.get_user(self.client) self.assertTrue(user.is_authenticated)
Example #14
Source File: tests.py From yats with MIT License | 5 votes |
def test_user_already_logged_in(self): USERNAME = PASSWORD = 'myuser' server_user = User.objects.create_user(USERNAME, 'my@user.com', PASSWORD) consumer = self._get_consumer() with UserLoginContext(self, server_user): # try logging in and auto-follow all 302s self.client.get(reverse('simple-sso-login'), follow=True) # check the user client_user = get_user(self.client) self.assertFalse(is_password_usable(client_user.password)) self.assertTrue(is_password_usable(server_user.password)) for key in ['username', 'email', 'first_name', 'last_name']: self.assertEqual(getattr(client_user, key), getattr(server_user, key))
Example #15
Source File: tests.py From OnlineJudge with MIT License | 5 votes |
def test_login_with_correct_info(self): response = self.client.post(self.login_url, data={"username": self.username, "password": self.password}) self.assertDictEqual(response.data, {"error": None, "data": "Succeeded"}) user = auth.get_user(self.client) self.assertTrue(user.is_authenticated)
Example #16
Source File: views.py From devops with MIT License | 5 votes |
def login_user(self): user = self.created_user if settings.ACCOUNT_USE_AUTH_AUTHENTICATE: # call auth.authenticate to ensure we set the correct backend for # future look ups using auth.get_user(). user = auth.authenticate(**self.user_credentials()) else: # set auth backend to ModelBackend, but this may not be used by # everyone. this code path is deprecated and will be removed in # favor of using auth.authenticate above. user.backend = "django.contrib.auth.backends.ModelBackend" auth.login(self.request, user) self.request.session.set_expiry(0)
Example #17
Source File: test_basic.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_get_user(self): created_user = User.objects.create_user('testuser', 'test@example.com', 'testpw') self.client.login(username='testuser', password='testpw') request = HttpRequest() request.session = self.client.session user = get_user(request) self.assertIsInstance(user, User) self.assertEqual(user.username, created_user.username)
Example #18
Source File: test_models.py From django-mfa with MIT License | 5 votes |
def test_u2f_key_user(self): user_u2f = U2FKey.objects.filter( user=auth.get_user(self.client)).first() self.assertEqual(self.u2f_keys.user, user_u2f.user) self.assertEqual(self.u2f_keys.public_key, user_u2f.public_key) self.assertEqual(self.u2f_keys.key_handle, user_u2f.key_handle) self.assertEqual(self.u2f_keys.app_id, user_u2f.app_id)
Example #19
Source File: utils.py From DjangoUnleashed-1.8 with BSD 2-Clause "Simplified" License | 5 votes |
def get_object(self, queryset=None): current_user = get_user(self.request) return current_user.profile
Example #20
Source File: test_models.py From django-mfa with MIT License | 5 votes |
def test_user_data_saved_correctly(self): user_details = auth.get_user(self.client) self.assertEqual(self.user.username, user_details.username) self.assertEqual(self.user.email, user_details.email) self.assertEqual(self.user.password, user_details.password)
Example #21
Source File: test_models.py From django-mfa with MIT License | 5 votes |
def test_u2f_enabled(self): self.assertTrue(is_u2f_enabled(auth.get_user(self.client)))
Example #22
Source File: test_models.py From django-mfa with MIT License | 5 votes |
def test_mfa_enabled(self): self.assertTrue(is_mfa_enabled(auth.get_user(self.client)))
Example #23
Source File: test_views.py From django-mfa with MIT License | 5 votes |
def test_recovery_codes_newcodes_generate_view(self): UserRecoveryCodes.objects.get(user=UserOTP.objects.get( user=auth.get_user(self.client)), secret_code="ABcDg").delete() response = self.client.get(reverse('mfa:recovery_codes')) self.assertTemplateUsed(response, "django_mfa/recovery_codes.html")
Example #24
Source File: test_views.py From ecommerce with GNU Affero General Public License v3.0 | 5 votes |
def assert_authentication_status(self, is_authenticated): """ Verifies the authentication status of the user attached to the test client. """ user = get_user(self.client) self.assertEqual(user.is_authenticated, is_authenticated)
Example #25
Source File: test_cybersource.py From ecommerce with GNU Affero General Public License v3.0 | 5 votes |
def test_sdn_check_match(self): """Verify the endpoint returns an sdn check failure if the sdn check finds a hit.""" self.site.siteconfiguration.enable_sdn_check = True self.site.siteconfiguration.save() basket_id = self._create_valid_basket().id data = self._generate_data(basket_id) expected_response = {'error': 'There was an error submitting the basket', 'sdn_check_failure': {'hit_count': 1}} logger_name = self.CYBERSOURCE_VIEW_LOGGER_NAME with mock.patch.object(SDNClient, 'search', return_value={'total': 1}) as sdn_validator_mock: with mock.patch.object(User, 'deactivate_account', return_value=True): with LogCapture(logger_name) as cybersource_logger: response = self.client.post(self.path, data) self.assertTrue(sdn_validator_mock.called) self.assertEqual(response.json(), expected_response) self.assertEqual(response.status_code, 403) cybersource_logger.check_present( ( logger_name, 'INFO', 'SDNCheck function called for basket [{}]. It received 1 hit(s).'.format(basket_id) ), ) # Make sure user is logged out self.assertEqual(get_user(self.client).is_authenticated, False)
Example #26
Source File: views.py From devops with MIT License | 5 votes |
def get_user(self): try: uid_int = base36_to_int(self.kwargs["uidb36"]) except ValueError: raise Http404() return get_object_or_404(get_user_model(), id=uid_int)
Example #27
Source File: views.py From devops with MIT License | 5 votes |
def after_change_password(self): user = self.get_user() signals.password_changed.send(sender=PasswordResetTokenView, user=user) if settings.ACCOUNT_NOTIFY_ON_PASSWORD_CHANGE: self.send_email(user) if self.messages.get("password_changed"): messages.add_message( self.request, self.messages["password_changed"]["level"], self.messages["password_changed"]["text"] )
Example #28
Source File: views.py From devops with MIT License | 5 votes |
def change_password(self, form): user = self.get_user() user.set_password(form.cleaned_data["password"]) user.save()
Example #29
Source File: views.py From devops with MIT License | 5 votes |
def get(self, request, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) ctx = self.get_context_data(form=form) if not self.check_token(self.get_user(), self.kwargs["token"]): return self.token_fail() return self.render_to_response(ctx)
Example #30
Source File: auth.py From yats with MIT License | 5 votes |
def __call__(self, request): for url in self.public_urls: if url.match(request.path[1:]): return self.get_response(request) # lookup, if user was already authenticated request.user = get_user(request) if request.user.is_authenticated: try: request.organisation = UserProfile.objects.get(user=request.user).organisation except Exception: pass return self.get_response(request) if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() if len(auth) == 2: # NOTE: We only support basic authentication for now. # if auth[0].lower() == "basic": auth_data = auth[1] auth_data += "=" * ((4 - len(auth_data) % 4) % 4) auth_data = base64.b64decode(auth_data).decode('utf-8') uname, passwd = auth_data.split(':', 1) user = authenticate(username=uname, password=passwd) if user: if user.is_active: request.user = user try: request.organisation = UserProfile.objects.get(user=user).organisation except Exception: pass login(request, user) return self.get_response(request) return self.get_response(request)