10 examples of 'django get current user' in Python

Every line of 'django get current user' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
81def get_user(request):
82 """authorize user based on API key if it was passed, otherwise just use the request's user.
83
84 :param request:
85 :return: django.contrib.auth.User
86 """
87 if 'api_key' in request.REQUEST:
88 api_key = ApiKey.objects.get(key=request.REQUEST['api_key'])
89 return api_key.user
90 elif request.user.is_authenticated():
91 return User.objects.get(pk=request.user.pk)
92 else:
93 return request.user
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

34def get_user_from_request(request):
35 """ Checks the current session and returns a :class:`~horizon.users.User`.
36
37 If the session contains user data the User will be treated as
38 authenticated and the :class:`~horizon.users.User` will have all
39 its attributes set.
40
41 If not, the :class:`~horizon.users.User` will have no attributes set.
42
43 If the session contains invalid data,
44 :exc:`~horizon.exceptions.NotAuthorized` will be raised.
45 """
46 if 'user_id' not in request.session:
47 return User()
48 try:
49 return User(id=request.session['user_id'],
50 token=request.session['token'],
51 user=request.session['user_name'],
52 tenant_id=request.session['tenant_id'],
53 tenant_name=request.session['tenant'],
54 service_catalog=request.session['serviceCatalog'],
55 roles=request.session['roles'])
56 except KeyError:
57 # If any of those keys are missing from the session it is
58 # overwhelmingly likely that we're dealing with an outdated session.
59 LOG.exception("Error while creating User from session.")
60 request.session.clear()
61 raise exceptions.NotAuthorized(_("Your session has expired. "
62 "Please log in again."))
34def get_user(request):
35 return getattr(request, settings.REQUEST_USER)
25def get_user():
26 uid = request.session.get('uid', None)
27 if not uid:
28 return None
29
30 try:
31 user = SiteUser.objects.select_related(
32 *SOCIAL_LOGIN_SITEUSER_SELECT_RELATED).get(id=int(uid))
33 except SiteUser.DoesNotExist:
34 return None
35
36 if not user.is_active:
37 user = None
38 return user
22def authenticate(self, request, username=None, password=None, **kwargs):
23 try:
24 # 使用get是因为不希望用户存在两个, Q:使用并集查询
25 user = UserProfile.objects.get(Q(username=username)|Q(email=username))
26 # 判断密码是否匹配时,django的后台中密码加密:所以不能password==password
27 # UserProfile继承的AbstractUser中有check_password(self, raw_password)方法
28 if user.check_password(password):
29 return user
30 except BaseException as e:
31 return None
14def get_user_model():
15 """
16 Get the Django user model class in a backwards compatible way to previous
17 Django version that don't provide this functionality. The result is cached
18 after the first call.
19
20 Returns the user model class.
21 """
22 global _user_model
23
24 if not _user_model:
25 # we have to import the user model here because we can't be sure
26 # that the app providing the user model is fully loaded.
27 try:
28 from django.contrib.auth import get_user_model
29 except ImportError:
30 from django.contrib.auth.models import User
31 else:
32 User = get_user_model()
33 _user_model = User
34 return _user_model
39def get_current_user(self):
40 return users.get_current_user()
39def _default_get_user(request, **kwargs):
40 try:
41 return request.user
42 except AttributeError:
43 return None
32def get_user(request):
33 """Based on django.contrib.auth.middleware.get_user
34
35 Adds handling of anonymous user which is stored in database.
36 """
37 # pylint: disable=protected-access
38 if not hasattr(request, '_cached_user'):
39 user = auth.get_user(request)
40 if isinstance(user, AnonymousUser):
41 user = get_anonymous()
42 # Set short expiry for anonymous sessions
43 request.session.set_expiry(2200)
44 else:
45 request.session.set_expiry(None)
46
47 request._cached_user = user
48 return request._cached_user
98def get_user(self):
99 """get current user"""
100 request = self._get_request()
101 if request and getattr(request, 'user', None):
102 if isinstance(request.user, self._get_user_model()):
103 return request.user
104 # AnonymousUser
105 return self.get_system_user()

Related snippets