def login(request, user): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: if _get_user_session_key(request) != user.pk or ( session_auth_hash and request.session.get(HASH_SESSION_KEY) != session_auth_hash): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) request.session[BACKEND_SESSION_KEY] = user.backend request.session[HASH_SESSION_KEY] = session_auth_hash if hasattr(request, 'user'): request.user = user rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
def rate_wrap(request, *args, **kwargs): if request.method == 'POST': session = request.session now = time() k_timeout = '{}_timeout'.format(scope) k_attempts = '{}_attempts'.format(scope) # Reset expired counter if (k_timeout in session and k_attempts in session and session[k_timeout] <= now): session[k_attempts] = 0 # Get current attempts attempts = session.get(k_attempts, 0) # Did we hit the limit? if attempts >= get_rate_setting(scope, 'ATTEMPTS'): # Rotate session token rotate_token(request) # Logout user if request.user.is_authenticated: logout(request) messages.error( request, _('Too many attempts, you have been logged out!') ) return redirect('login') session[k_attempts] = attempts + 1 if k_timeout not in session: window = get_rate_setting(scope, 'WINDOW') session[k_timeout] = now + window return function(request, *args, **kwargs)
def collection(request): ren = None if request.method == "POST": curr.execute("delete from reader_user_token where token=(%s)", (get_token(request),)) conn.commit() rotate_token(request) else: if request.method == "GET": curr.execute("select user_id from reader_user_token where token=(%s)", (get_token(request),)) if curr.rowcount == 1: curr.execute("update reader_user_token set last_use=(select clock_timestamp()) where token=(%s)", (get_token(request),)) conn.commit() curr.execute("""select user_email from reader_user where id = (select user_id from reader_user_token where token=(%s))""", (get_token(request),)) content = {"email" : curr.fetchone()[0]} curr.execute("select id, title, url, favicon, is_active from reader_site where user_id = (select user_id from reader_user_token where token=(%s)) order by id", (get_token(request),)) rows = curr.fetchall() rowarray = [] for row in rows: d = collections.OrderedDict() d['id'] = row[0] if row[1] is None: d['title'] = "" else: d['title'] = row[1] d['url'] = row[2] dd = row[2].split('/') d['favicon'] = row[3] or (('http://' + dd[0] if dd[0] != 'http:' else dd[0] + '//' + dd[2]) + '/favicon.ico') d['is_active'] = row[4] rowarray.append(d) content.update({"sites" : rowarray}) ren = render(request, 'collection.html', content) if ren is None: ren = redirect('index') return ren
def get(self, request): logout(request) csrf.rotate_token(request) if request.META["HTTP_REFERER"].find("/panel/") > -1 or request.META["HTTP_REFERER"].find("/admin/") > -1 or \ request.META["HTTP_REFERER"].find("/api/") > -1: return redirect("/") return redirect(request.META["HTTP_REFERER"])
def custom_login(request, user): session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: if _get_user_session_key(request) != user.pk or ( session_auth_hash and request.session.get(HASH_SESSION_KEY) != session_auth_hash): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) request.session[BACKEND_SESSION_KEY] = user.backend request.session[HASH_SESSION_KEY] = session_auth_hash if hasattr(request, 'user'): request.user = user try: from django.middleware.csrf import rotate_token rotate_token(request) except ImportError: pass
def user_remove(request): is_confirmation = 'remove_confirm' in request.session if is_confirmation: if request.method == 'POST': remove_user(request.user, request) rotate_token(request) logout(request) messages.success( request, _('Your account has been removed.') ) return redirect('home') confirm_form = EmptyConfirmForm(request) elif request.method == 'POST': confirm_form = PasswordConfirmForm(request, request.POST) if confirm_form.is_valid(): store_userid(request, remove=True) request.GET = {'email': request.user.email} return social_complete(request, 'email') else: confirm_form = PasswordConfirmForm(request) return render( request, 'accounts/removal.html', { 'confirm_form': confirm_form, 'is_confirmation': is_confirmation, } )
def client_login(self,request,backend=None): SESSION_KEY = 'client_id' BACKEND_SESSION_KEY = 'client_backend' HASH_SESSION_KEY = 'client_hash' REDIRECT_FIELD_NAME = 'next' session_auth_hash = '' if self is None: self = request.user if hasattr(self, 'get_session_auth_hash'): session_auth_hash = self.get_session_auth_hash() if SESSION_KEY in request.session: if self._meta.pk.to_python(request.session[SESSION_KEY]) != self.pk or (session_auth_hash and request.session.get(HASH_SESSION_KEY) != session_auth_hash): request.session.flush() # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. else: request.session.cycle_key() request.session[SESSION_KEY] = self._meta.pk.value_to_string(self) request.session[BACKEND_SESSION_KEY] = backend request.session[HASH_SESSION_KEY] = session_auth_hash if hasattr(request, 'user'): # request.session['user']=self. request.user = self rotate_token(request) user_logged_in.send(sender=self.__class__, request=request, user=self)
def doToken(self, request): # If CSRF token is lost from django.middleware.csrf import rotate_token rotate_token(request) o = request.GET["rel"] if not o: o = Main().url return self.resp("<script>location.href='%s';</script>" % (o))
def test_django_csrf(self): request = self.factory.get('/browserid/csrf/') rotate_token(request) token = get_token(request) response = self.view.get(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, six.b(token))
def create(self, request): """ Prove the user has a CSRF token (by just guaranteeing it). """ if 'django.middleware.csrf.CsrfViewMiddleware' in settings.MIDDLEWARE_CLASSES: rotate_token(request) return response.Response()
def login(request, user,schema = None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ if schema == None or not type(schema) in [str, unicode]: # add schema import inspect fx = inspect.stack() error_detail = "" for x in fx: error_detail += "\n\t {0}, line {1}".format(fx[1], fx[2]) raise ( Exception( "can not call ''{1}'' without schema in '{0}'.\nDetail:\n{2}".format( __file__, "login", error_detail ))) import threading ct = threading.currentThread() setattr(ct,"__current_schema__",schema) current_schema_in_request=schema if hasattr(request,"__current_schema__"): current_schema_in_request=request.__current_schema__ if user is None: user = request.user # TODO: It would be nice to support different login methods, like signed cookies. if SESSION_KEY in request.session: if request.session[SESSION_KEY] != user.pk: # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush(schema = request.user.schema) else: if request.user.is_anonymous() and not hasattr(request.user,"schema"): import threading request.session.cycle_key(schema=threading.current_thread().tenancy_code) else: request.session.cycle_key(schema=request.user.schema) request.session[SESSION_KEY] = user.pk request.session[BACKEND_SESSION_KEY] = user.backend if hasattr(request, 'user'): request.user = user rotate_token(request) user_logged_in.send( sender=user.__class__, request=request, user=user, schema=schema ) setattr(user,"schema",schema) setattr(request,"__current_schema__",schema) delattr(ct, "__current_schema__") request._cached_user = user
def csrf_exempt_dummy(request, template_name=None): global money money = request.POST.get('money', money) message = 'your money is {money}'.format(money=money) rotate_token(request) if request.method == "POST": form = forms.UserForm(request.POST) if not form.is_valid(): message = "your data get problem" return render(request, template_name, {'message': message})
def dispatch(self, request, *args, **kwargs): if not self.user_pass_test(request): raise PermissionDenied # if not request.is_ajax(): # raise PermissionDenied rotate_token(request) if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs)
def clean_password(self): cur_password = self.cleaned_data['password'] if self.request.user.has_usable_password(): valid = self.request.user.check_password(cur_password) else: valid = (cur_password == '') if not valid: rotate_token(self.request) raise forms.ValidationError( _('You have entered an invalid password.') )
def login(request, user): try: user_id = request.session[SESSION_KEY] if user.pk != user_id: #We're logging in as a different user, start a clean session request.session.flush() except KeyError: #Logging in a formerly-anonymous session, change the key but keep session data request.session.cycle_key() request.session[SESSION_KEY] = user.pk request.user = user rotate_token(request)
def login(request, user, expiration=True): """ Persist token into database. Token is stored inside cookie therefore is not necessary reauthenticate user for every request. """ if user is None: user = request.user token = Token.objects.create(user=user, user_agent=request.META.get('HTTP_USER_AGENT'), expiration=expiration) if hasattr(request, 'user'): request.user = user request.token = token rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
def rate_wrap(request, *args, **kwargs): attempts = request.session.get('auth_attempts', 0) if request.method == 'POST': if attempts >= settings.AUTH_MAX_ATTEMPTS: rotate_token(request) if request.user.is_authenticated: logout(request) messages.error( request, _('Too many attempts, you have been logged out!') ) return redirect('login') request.session['auth_attempts'] = attempts + 1 return function(request, *args, **kwargs)
def login(request, user, backend=None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() # session已经保存了用户id,当然这里不能保证是当前用户的用户id, # 如果是当前用户id,密码也可能已经变了,这两种情况都彻底清空session # 这里的SESSION_KEY是session中user_id的键值 if SESSION_KEY in request.session: if _get_user_session_key(request) != user.pk or ( session_auth_hash and request.session.get(HASH_SESSION_KEY) != session_auth_hash): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: #session没有保存用户id,也就是如果用户从匿名状态登录到非匿名,sessionid会刷新,但是session的其他数据不会丢失 #cycle_key 维持session的数据不变,但是更改sessionid request.session.cycle_key() try: backend = backend or user.backend except AttributeError: backends = _get_backends(return_tuples=True) if len(backends) == 1: _, backend = backends[0] else: raise ValueError( 'You have multiple authentication backends configured and ' 'therefore must provide the `backend` argument or set the ' '`backend` attribute on the user.' ) # 这里的SESSION_KEY和middleware的session_key不一样,这里是一个固定的键值,可以直接理解为'user_id',里面保存user_id # BACKEND_SESSION_KEY 保存session具体储存实现引擎如 'django.contrib.auth.backends.ModelBackend' # HASH_SESSION_KEY 保存加盐密码的hash,如果用户密码更换了,就是依靠这个字段判断 request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) request.session[BACKEND_SESSION_KEY] = backend request.session[HASH_SESSION_KEY] = session_auth_hash if hasattr(request, 'user'): request.user = user rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
def get(self, request, *args, **kwargs): try: #rotate csrf token on login page rotate_token(request) if request.session['access_token']: if request.session['path_previous']: return self.redirect(request.session['path_previous']) else: return self.redirect('/dashboard/') except: # This localization feature has been done . The implementation of the same will be provided by Adaptive Team. # Currently we are hardcoding the session language to english request.session['django_language'] = 'en' return self.render_template(self.template_name)
def logout(request): """ Removes the authenticated user's ID from the request, flushes their session data, and rotates the CSRF token. """ # This function was lifted almost verbatim from Django's implementation of logout() user = getattr(request, 'user', None) if hasattr(user, 'is_authenticated') and not user.is_authenticated(): user = None # Dispatch the signal before the user is logged out so the receivers have a chance to find out *who* logged out. user_logged_out.send(sender=user.__class__, request=request, user=user) request.session.flush() if hasattr(request, 'user'): request.user = AnonymousUser() csrf.rotate_token(request)
def clean_password(self): cur_password = self.cleaned_data['password'] if self.request.user.has_usable_password(): valid = self.request.user.check_password(cur_password) else: valid = (cur_password == '') if valid: self.request.session['auth_attempts'] = 0 else: attempts = self.request.session.get('auth_attempts', 0) self.request.session['auth_attempts'] = attempts + 1 rotate_token(self.request) raise forms.ValidationError( _('You have entered an invalid password.') )
def login(request, token, send_signal=True): if AUTH_SESSION_KEY in request.session: if request.session[AUTH_SESSION_KEY] != token: request.session.flush() else: request.session.cycle_key() request.session[AUTH_SESSION_KEY] = token user = get_user(request, token) if hasattr(request, 'user'): request.user = user request.account = get_account_from_request(request) rotate_token(request) if send_signal: user_logged_in.send(sender=user.__class__, request=request, user=user)
def post(self, request): bt_data = solitude.api().braintree.token.generate.post({}) # Generate a new token for added security. csrf.rotate_token(request) # This view returns a CSRF token to the client so that it can # initialize API usage for anonymous payments (e.g. donations). # For added security, we could restrict the scope of that CSRF # tokens only to views relating to products that support # anonymous payments. return Response({ 'token': bt_data['token'], 'csrf_token': csrf.get_token(request), })
def user_register(request): if request.user.is_authenticated(): auth.logout(request) if request.method == 'POST': # form = CustomUserCreationForm(request.POST, request.FILES) form = CustomUserCreationForm(request.POST) if form.is_valid(): # check if the image for the user is here try: profile_picture_old_path = NewProfilePicture.objects.get(csrftoken=request.META["CSRF_COOKIE"]) new_user = form.save(commit=False) new_user.save() # put the picture to the right place and save it for the user basic_path = settings.MEDIA_ROOT + '/profile_pictures/' profile_picture_new_path = basic_path + str(new_user.id) + '.jpg' if not os.path.exists(basic_path): os.makedirs(basic_path) shutil.copy2(str(profile_picture_old_path), profile_picture_new_path) # delete the old folder containing the pictures of that user shutil.rmtree(settings.MEDIA_ROOT + '/new_pictures/' + request.META["CSRF_COOKIE"]) new_user.profile_picture = profile_picture_new_path new_user.save() default_group = UserGroup.objects.get(id=1) new_user.user_group.add(default_group) form.save_m2m() except NewProfilePicture.DoesNotExist: print 'There is no profile picture for this user' return render(request, 'BlueHive/user/register.html', {'form': form, 'picturemissing': 'Please upload a profile picture!'}) return HttpResponseRedirect('/user/register_success') else: # render_to_response('BlueHive/user/register.html', {'form': form}) print form.errors # To see the form errors in the console. return render(request, 'BlueHive/user/register.html', {'form': form}) rotate_token(request) args = {} args.update(csrf(request)) args['form'] = CustomUserCreationForm() return render_to_response('BlueHive/user/register.html', args)
def rate_wrap(request, *args, **kwargs): if (request.method == 'POST' and not check_rate_limit(scope, request)): # Rotate session token rotate_token(request) # Logout user do_logout = request.user.is_authenticated if do_logout: logout(request) messages.error( request, render_to_string( 'ratelimit.html', {'do_logout': do_logout} ) ) return redirect('login') return function(request, *args, **kwargs)
def login(request, user, backend=None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: if _get_user_session_key(request) != user.pk or ( session_auth_hash and not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() try: backend = backend or user.backend except AttributeError: backends = _get_backends(return_tuples=True) if len(backends) == 1: _, backend = backends[0] else: raise ValueError( 'You have multiple authentication backends configured and ' 'therefore must provide the `backend` argument or set the ' '`backend` attribute on the user.' ) else: if not isinstance(backend, str): raise TypeError('backend must be a dotted import path string (got %r).' % backend) request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) request.session[BACKEND_SESSION_KEY] = backend request.session[HASH_SESSION_KEY] = session_auth_hash if hasattr(request, 'user'): request.user = user rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: if not check_rate_limit(self.request): raise forms.ValidationError( _('Too many authentication attempts!') ) self.user_cache = authenticate( username=username, password=password ) if self.user_cache is None: try: notify_account_activity( try_get_user(username), self.request, 'failed-auth', method='Password', name=username, ) except User.DoesNotExist: pass rotate_token(self.request) raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', ) elif not self.user_cache.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', ) else: notify_account_activity( self.user_cache, self.request, 'login', method='Password', name=username, ) reset_rate_limit(self.request) return self.cleaned_data
def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: if not check_rate_limit('login', self.request): raise forms.ValidationError( _('Too many authentication attempts from this location!') ) self.user_cache = authenticate( self.request, username=username, password=password ) if self.user_cache is None: for user in try_get_user(username, True): notify_account_activity( user, self.request, 'failed-auth', method=ugettext('Password'), name=username, ) rotate_token(self.request) raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', ) elif not self.user_cache.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', ) else: notify_account_activity( self.user_cache, self.request, 'login', method=ugettext('Password'), name=username, ) reset_rate_limit('login', self.request) return self.cleaned_data
def driver_new(request): from td.forms import DriverForm from django.middleware.csrf import rotate_token if request.method == 'GET': form = DriverForm(new=True) context = {'form': form} return render(request, 'td/driver/driver_new.html', context) elif request.method == 'POST': rotate_token(request) form = DriverForm(request.POST, request.FILES, new=True) if form.is_valid(): driver = form.save() messages.success(request, 'Водитель добавлен') return redirect(to='td:driver_info', did=driver.id) else: context = {'form': form} return render(request, 'td/driver/driver_new.html', context)
def department_new(request): from main.forms import DepartmentForm from django.middleware.csrf import rotate_token if request.method == 'GET': form = DepartmentForm() context = {'form': form} return render(request, 'main/department/department_new.html', context) elif request.method == 'POST': rotate_token(request) form = DepartmentForm(request.POST) if form.is_valid(): dep = form.save() messages.success(request, 'Подразделение добавлено') return redirect(to='main:department_info', did=dep.id) else: context = {'form': form} return render(request, 'main/department/department_new.html', context)
def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: if not check_rate_limit(self.request): raise forms.ValidationError( _('Too many authentication attempts!')) self.user_cache = authenticate(username=username, password=password) if self.user_cache is None: try: notify_account_activity( try_get_user(username), self.request, 'failed-auth', method='Password', name=username, ) except User.DoesNotExist: pass rotate_token(self.request) raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', ) elif not self.user_cache.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', ) else: notify_account_activity( self.user_cache, self.request, 'login', method='Password', name=username, ) reset_rate_limit(self.request) return self.cleaned_data
def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: if not check_rate_limit('login', self.request): raise forms.ValidationError( _('Too many authentication attempts from this location!')) self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: for user in try_get_user(username, True): audit = AuditLog.objects.create( user, self.request, 'failed-auth', method='Password', name=username, ) audit.check_rate_limit(self.request) rotate_token(self.request) raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', ) elif not self.user_cache.is_active: raise forms.ValidationError( self.error_messages['inactive'], code='inactive', ) else: AuditLog.objects.create( self.user_cache, self.request, 'login', method='Password', name=username, ) reset_rate_limit('login', self.request) return self.cleaned_data
def clean_captcha(self): """Validation for CAPTCHA.""" if self.fresh or not self.captcha.validate(self.cleaned_data['captcha']): self.generate_captcha() rotate_token(self.request) raise forms.ValidationError( # Translators: Shown on wrong answer to the mathematics-based CAPTCHA _('That was not correct, please try again.') ) if self.form.is_valid(): mail = self.form.cleaned_data['email'] else: mail = 'NONE' LOGGER.info( 'Passed captcha for %s (%s = %s)', mail, self.captcha.question, self.cleaned_data['captcha'] )
def clean_captcha(self): """Validation for CAPTCHA.""" if (self.fresh or not self.captcha.validate(self.cleaned_data['captcha'])): self.generate_captcha() rotate_token(self.request) raise forms.ValidationError( _('Please check your math and try again with new expression.') ) if self.form.is_valid(): mail = self.form.cleaned_data['email'] else: mail = 'NONE' LOGGER.info( 'Passed captcha for %s (%s = %s)', mail, self.captcha.question, self.cleaned_data['captcha'] )
def login(request, user): """ Persist a user id in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ if user is None: user = request.app_user if SESSION_KEY in request.session: if request.session[SESSION_KEY] != user.pk: # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() request.session[SESSION_KEY] = user.pk if hasattr(request, 'app_user'): request.app_user = user rotate_token(request) app_user_logged_in.send(sender=user.__class__, request=request, user=user)
def customer_logout(request): session_key = f'customer_auth_id:{request.organizer.pk}' hash_session_key = f'customer_auth_hash:{request.organizer.pk}' # Remove user session customer_id = request.session.pop(session_key, None) request.session.pop(hash_session_key, None) # Remove carts tied to this user carts = request.session.get('carts', {}) for k, v in list(carts.items()): if v.get('customer') == customer_id: carts.pop(k) request.session['carts'] = carts # Cycle session key and CSRF token request.session.cycle_key() rotate_token(request) request.customer = None request._cached_customer = None
def car_new(request): from td.forms import CarNewForm from django.middleware.csrf import rotate_token if request.method == 'GET': form = CarNewForm() context = {'form': form} return render(request, 'td/car/car_new.html', context) elif request.method == 'POST': rotate_token(request) form = CarNewForm(request.POST) if form.is_valid(): car = form.save() messages.success(request, 'Автомобиль добавлен') return redirect(to='td:car_list') #return redirect(to='td:car_info', cid=car.id) else: context = {'form': form} return render(request, 'td/car/car_new.html', context)
def clean_captcha(self): """Validation for captcha.""" if (self.fresh or not self.captcha.validate(self.cleaned_data['captcha'])): self.generate_captcha() rotate_token(self.request) raise forms.ValidationError( _('Please check your math and try again with new expression.') ) if self.form.is_valid(): mail = self.form.cleaned_data['email'] else: mail = 'NONE' LOGGER.info( 'Passed captcha for %s (%s = %s)', mail, self.captcha.question, self.cleaned_data['captcha'] )
def clean_captcha(self): """Validation for CAPTCHA.""" if self.fresh or not self.captcha.validate( self.cleaned_data["captcha"]): self.generate_captcha() rotate_token(self.request) raise forms.ValidationError( # Translators: Shown on wrong answer to the mathematics-based CAPTCHA _("That was not correct, please try again.")) if self.form.is_valid(): mail = self.form.cleaned_data["email"] else: mail = "NONE" LOGGER.info( "Correct CAPTCHA for %s (%s = %s)", mail, self.captcha.question, self.cleaned_data["captcha"], )
def sim_new(request): from django.middleware.csrf import rotate_token from mobile.forms import SimForm return_path = request.GET.get('return', None) sim_number = request.GET.get('num', None) if request.method == 'GET': form = SimForm(initial={'number': sim_number}) context = {'form': form} return render(request, 'mobile/sim/new.html', context) elif request.method == 'POST': rotate_token(request) form = SimForm(request.POST) if form.is_valid(): sim = form.save() messages.success(request, 'SIM-карта добавлена') return redirect(to='mobile:sim_list') else: context = {'form': form} return render(request, 'mobile/sim/new.html', context)
def xlogin(request, user, backend=None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() # Hack to init the session request.session._get_session() request.session.cycle_key() try: backend = backend or user.backend except AttributeError: backends = _get_backends(return_tuples=True) if len(backends) == 1: _, backend = backends[0] else: raise ValueError( 'You have multiple authentication backends configured and ' 'therefore must provide the `backend` argument or set the ' '`backend` attribute on the user.') logged_in_user = { SESSION_KEY: user._meta.pk.value_to_string(user), BACKEND_SESSION_KEY: backend, HASH_SESSION_KEY: session_auth_hash } request.session.setdefault(LOGGED_USERS_KEY, []).append(logged_in_user) request.session.update(logged_in_user) if hasattr(request, 'user'): request.user = user rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
def visitor_edit(request, vid): from td.forms import VisitorsParkingForm from td.models import VisitorsParking from django.middleware.csrf import rotate_token if request.method == 'GET': visitor = get_object_or_404(VisitorsParking, id=vid) form = VisitorsParkingForm(instance=visitor) context = {'form': form} return render(request, 'td/visitor/visitor_edit.html', context) elif request.method == 'POST': rotate_token(request) visitor = get_object_or_404(VisitorsParking, id=vid) form = VisitorsParkingForm(request.POST, instance=visitor) if form.is_valid(): form.save() messages.success(request, 'Запись изменена') return redirect(to='td:visitor_info', vid=vid) else: context = {'form': form} return render(request, 'td/visitor/visitor_edit.html', context)
def accident_doc_new(request): from django.middleware.csrf import rotate_token from td.forms import AccidentDocForm from td.models import AccidentDoc return_path = request.GET.get('return', None) if request.method == 'GET': accident = request.GET.get('accident', None) form = AccidentDocForm(initial={'accident': accident}) context = {'form': form} return render(request, 'td/accident_doc/accident_doc_new.html', context) elif request.method == 'POST': rotate_token(request) form = AccidentDocForm(request.POST, request.FILES) if form.is_valid(): accident_doc = form.save() messages.success(request, 'Объект добавлен') return redirect(to='td:accident_info', aid=accident_doc.accident.id) else: context = {'form': form} return render(request, 'td/accident_doc/accident_doc_new.html', context)
def department_edit(request, did): from main.forms import DepartmentForm from main.models import Department from django.middleware.csrf import rotate_token if request.method == 'GET': dep = get_object_or_404(Department, id=did) form = DepartmentForm(instance=dep) context = {'form': form} return render(request, 'main/department/department_edit.html', context) elif request.method == 'POST': rotate_token(request) dep = get_object_or_404(Department, id=did) form = DepartmentForm(request.POST, instance=dep) if form.is_valid(): form.save() messages.success(request, 'Подразделение изменено') return redirect(to='main:department_info', did=did) else: context = {'form': form} return render(request, 'main/department/department_edit.html', context)
def transition_edit(request, uid): from mobile.models import Transition from mobile.forms import TransitionForm transition = get_object_or_404(Transition, id=uid) if request.method == 'GET': form = TransitionForm(instance=transition, initial={'date_field': transition.date}) context = {'form': form} return render(request, 'mobile/transition/edit.html', context) elif request.method == 'POST': rotate_token(request) form = TransitionForm(request.POST, instance=transition) if form.is_valid(): transition = form.save(commit=False) transition.date = form.cleaned_data['date_field'] transition.save() messages.success(request, 'Изменения применены') return redirect(to='mobile:sim_transitions', uid=transition.sim.id) else: context = {'form': form} return render(request, 'mobile/transition/edit.html', context)
def expense_edit(request, eid): from td.forms import ExpenseForm from td.models import Expense from django.middleware.csrf import rotate_token if request.method == 'GET': expense = get_object_or_404(Expense, id=eid) form = ExpenseForm(instance=expense) context = {'form': form} return render(request, 'td/expense/expense_edit.html', context) elif request.method == 'POST': rotate_token(request) expense = get_object_or_404(Expense, id=eid) form = ExpenseForm(request.POST, instance=expense) if form.is_valid(): form.save() messages.success(request, 'Запись изменена') return redirect(to='td:expense_info', eid=eid) else: context = {'form': form} return render(request, 'td/expense/expense_edit.html', context)
def parking_edit(request, pid): from td.forms import ParkingForm from td.models import Parking from django.middleware.csrf import rotate_token if request.method == 'GET': parking = get_object_or_404(Parking, id=pid) form = ParkingForm(instance=parking) context = {'form': form} return render(request, 'td/parking/parking_edit.html', context) elif request.method == 'POST': rotate_token(request) parking = get_object_or_404(Parking, id=pid) form = ParkingForm(request.POST, instance=parking) if form.is_valid(): form.save() messages.success(request, 'Запись изменена') return redirect(to='td:parking_info', pid=pid) else: context = {'form': form} return render(request, 'td/parking/parking_edit.html', context)
def login(request, user): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ if user is None: user = request.user # TODO: It would be nice to support different login methods, like signed cookies. if SESSION_KEY in request.session: if request.session[SESSION_KEY] != user.pk: # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() request.session[SESSION_KEY] = user.pk request.session[BACKEND_SESSION_KEY] = user.backend if hasattr(request, 'user'): request.user = user rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
def test_handle_backend_exception(): rf = APIRequestFactory(enforce_csrf_checks=True) params = { 'postcode': '3531 WR', 'number': '1', } request = rf.post('/', data=params, format='json') csrf.rotate_token(request) request.COOKIES['csrftoken'] = request.META['CSRF_COOKIE'] request.META['HTTP_X_CSRFTOKEN'] = request.META['CSRF_COOKIE'] def throw_error(postcode, number): raise PostcodeLookupException() views.PostcodeLookupView.backend = stub(lookup=throw_error) view = views.PostcodeLookupView.as_view() response = view(request) assert response.status_code == 400, response.rendered_content assert response.data == { 'error': 'No valid response received from backend' }
def login(request, user): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. 将一个用户的ID和认证后端持久化.之前的session会保持. """ session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: # 必须session的主键和user的pk一致,并且保存的hash和计算出来的hash一致,否则清空session if _get_user_session_key(request) != user.pk or ( session_auth_hash and request.session.get(HASH_SESSION_KEY) != session_auth_hash): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() # 创建session.使用之前的key else: request.session.cycle_key() # 保存了ID,后端,HASH,以便下次使用ID后端计算判断HASH是否有效 request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) request.session[BACKEND_SESSION_KEY] = user.backend request.session[HASH_SESSION_KEY] = session_auth_hash if hasattr(request, 'user'): request.user = user # 调用的CSRF的rotate_token,在登录之后使用新的csrf_cookie.TODO:如果使用旧的会怎样 rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
def jwtlogin(request, user): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: if request.session[SESSION_KEY] != user.pk or ( session_auth_hash and request.session.get(HASH_SESSION_KEY) != session_auth_hash): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() request.session[SESSION_KEY] = user.pk request.session[BACKEND_SESSION_KEY] = user.backend request.session[HASH_SESSION_KEY] = session_auth_hash if hasattr(request, 'user'): request.user = user monitorHook.loginMonitor(user) rotate_token(request) response_data = jwt_response_payload_handler(rotate_token, user, request) if api_settings.JWT_AUTH_COOKIE: expiration = (datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA) response_data.set_cookie(api_settings.JWT_AUTH_COOKIE, rotate_token, expires=expiration, httponly=True)
def profile(request): user = request.user data = { 'id': user.id, 'user': user.username, 'authenticated': user.is_authenticated(), 'admin': user.is_staff, } if data['authenticated']: rotate_token(request) data['csrf_token'] = get_token(request) try: data['first_name'] = user.first_name data['last_name'] = user.last_name data['extra'] = user.socialaccount_set.extra_data except: pass response = HttpResponse(json.dumps(data), content_type="application/json") return response
def json_login(request, redirect_field_name=REDIRECT_FIELD_NAME): redirect_to = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '/')) form = TicketAuthenticationForm(request, data=request.POST) if form.is_valid(): #if not is_safe_url(url=redirect_to, host=request.get_host()): #redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL) rotate_token(request) data = { 'code': 0, 'msg': u'成功', 'ticket': form.cleaned_data['ticket'], 'redirect_to': redirect_to, } return json_response(data) # response.set_cookie('ticket', form.cleaned_data['ticket']) # response = HttpResponseRedirect(redirect_to) # return response else: data = { 'code': 1, 'msg': ErrorDic2str(form.errors), } return json_response(data)
def accident_doc_edit(request, did): from td.models import AccidentDoc from td.forms import AccidentDocForm from django.middleware.csrf import rotate_token return_path = request.GET.get('return', None) doc = get_object_or_404(AccidentDoc, id=did) if request.method == 'GET': form = AccidentDocForm(instance=doc) context = {'form': form} return render(request, 'td/accident_doc/accident_doc_edit.html', context) elif request.method == 'POST': rotate_token(request) form = AccidentDocForm(request.POST, request.FILES, instance=doc) if form.is_valid(): form.save() messages.success(request, 'Объект изменен') return redirect(to='td:accident_info', aid=doc.accident.id) else: context = {'form': form} return render(request, 'td/accident_doc/accident_doc_edit.html', context)
def mileage_edit(request, mid): from td.models import Mileage from td.forms import MileageForm from django.middleware.csrf import rotate_token return_path = request.GET.get('return', None) if request.method == 'GET': mileage = get_object_or_404(Mileage, id=mid) form = MileageForm(instance=mileage) context = {'form': form} return render(request, 'td/mileage/mileage_edit.html', context) elif request.method == 'POST': rotate_token(request) mileage = get_object_or_404(Mileage, id=mid) form = MileageForm(request.POST, instance=mileage) if form.is_valid(): if Mileage.objects.filter( year=form.cleaned_data['year'], month=form.cleaned_data['month'], car=form.cleaned_data['car']).exclude(id=mid).count() > 0: messages.warning( request, 'Невозмоно добавить два значения пробега за один период') context = {'form': form} return render(request, 'td/mileage/mileage_edit.html', context) else: form.save() messages.success(request, 'Пробег изменен') if return_path == 'car_mileage': return redirect(to='td:car_mileage', cid=mileage.car.id) else: return redirect(to='td:mileage_info', mid=mid) else: context = {'form': form} return render(request, 'td/mileage/mileage_edit.html', context)
def login(request, user, expiration=True, auth_slug=None, related_objs=None, backend=None, allowed_cookie=True, allowed_header=True): """ Persist token into database. Token is stored inside cookie therefore is not necessary reauthenticate user for every request. """ from auth_token.models import Token related_objs = related_objs if related_objs is not None else () if user is None: user = request.user try: backend = backend or user.backend except AttributeError: backends = _get_backends(return_tuples=True) if len(backends) == 1: _, backend = backends[0] else: raise ValueError( 'You have multiple authentication backends configured and ' 'therefore must provide the `backend` argument or set the ' '`backend` attribute on the user.' ) token = Token.objects.create(user=user, user_agent=request.META.get('HTTP_USER_AGENT', '')[:256], expiration=expiration, auth_slug=auth_slug, ip=get_ip(request), backend=backend, allowed_cookie=allowed_cookie, allowed_header=allowed_header) for related_obj in related_objs: token.related_objects.create(content_object=related_obj) if hasattr(request, 'user'): request.user = user request.token = token rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user)
def clean(self): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username and password: if not check_rate_limit("login", self.request): raise forms.ValidationError( _("Too many authentication attempts from this location.") ) self.user_cache = authenticate( self.request, username=username, password=password ) if self.user_cache is None: for user in try_get_user(username, True): audit = AuditLog.objects.create( user, self.request, "failed-auth", method="password", name=username, ) audit.check_rate_limit(self.request) rotate_token(self.request) raise forms.ValidationError( self.error_messages["invalid_login"], code="invalid_login" ) if not self.user_cache.is_active: raise forms.ValidationError( self.error_messages["inactive"], code="inactive" ) AuditLog.objects.create( self.user_cache, self.request, "login", method="password", name=username ) adjust_session_expiry(self.request) reset_rate_limit("login", self.request) return self.cleaned_data
def user_remove(request): is_confirmation = 'remove_confirm' in request.session if is_confirmation: if request.method == 'POST': remove_user(request.user, request) rotate_token(request) logout(request) messages.success(request, _('Your account has been removed.')) return redirect('home') confirm_form = EmptyConfirmForm(request) elif request.method == 'POST': confirm_form = PasswordConfirmForm(request, request.POST) if confirm_form.is_valid(): store_userid(request, remove=True) request.GET = {'email': request.user.email} return social_complete(request, 'email') else: confirm_form = PasswordConfirmForm(request) return render(request, 'accounts/removal.html', { 'confirm_form': confirm_form, 'is_confirmation': is_confirmation, })
def login_view(request: HttpRequest) -> HttpResponse: """Login user from username/password and get information about the authorized orgs for this user. If the user is already logged in return this information. If the user has only a session cookie and no csrf cookie set a csrf cookie :param request: the post request :type request: HttpRequest :return: the json response :rtype: HttpResponse """ print("Login view", request.method) if request.method == "POST": if request.user.is_authenticated: # type: ignore csrf: Union[str, None] = request.COOKIES.get(settings.CSRF_COOKIE_NAME, None) # print("Csrf:", csrf) # reset the csrf token cookie if needed if csrf is None: print( "Renewing csrf token because user does not have any csrf cookie" ) rotate_token(request) return JsonResponse({"ok": True}) # print("POST", request.body) json_data = json.loads(request.body) print("LOGIN", json_data) username = json_data["username"] password = json_data["password"] print("Authenticate", username, password) user = authenticate(username=username, password=password) if user is not None: login(request, user) return JsonResponse({"ok": True}) return HttpResponseForbidden()
def bill_file_edit(request, uid): from mobile.models import BillFile, Bill from mobile.forms import BillFileEditForm from datetime import date bill_file = get_object_or_404(BillFile, id=uid) if request.method == 'GET': form = BillFileEditForm(instance=bill_file) context = {'form': form} return render(request, 'mobile/bill/file_edit.html', context) elif request.method == 'POST': rotate_token(request) form = BillFileEditForm(request.POST, instance=bill_file) if form.is_valid(): bill_file = form.save() for bill in bill_file.bill_set.all(): if bill.contract.mts: bill.period = date(bill_file.year, bill_file.month, 1) bill.save() messages.success(request, 'Изменения применены') return redirect(to='mobile:bill_file_info', uid=bill_file.id) else: context = {'form': form} return render(request, 'mobile/bill/file_edit.html', context)