Python django.contrib.auth.forms.AuthenticationForm() Examples

The following are 24 code examples of django.contrib.auth.forms.AuthenticationForm(). 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.forms , or try the search function .
Example #1
Source File: views.py    From python-monitoring-talk with Apache License 2.0 8 votes vote down vote up
def login_view(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('/post/')
    if request.method == 'GET':
        form = AuthenticationForm()
        return render(request, 'tilweb/login.html', {'form': form})
    if request.method == 'POST':
        form = AuthenticationForm(request=request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                print(user)
                login(request, user)
                return HttpResponseRedirect('/post/')
            else:
                print('User not found')
        else:
            # If there were errors, we render the form with these
            # errors
            return render(request, 'tilweb/login.html', {'form': form}) 
Example #2
Source File: views.py    From yats with MIT License 6 votes vote down vote up
def login(request):
    if request.user.is_authenticated:
        if 'next' in request.GET:
            return HttpResponseRedirect(request.GET['next'])
        else:
            return HttpResponseRedirect('/')

    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
        if user:
            auth_login(request, user)
            return HttpResponseRedirect('/')
        else:
            messages.add_message(request, messages.ERROR, _(u'Data invalid'))
    form = AuthenticationForm()
    if hasattr(settings, 'SSO_PRIVATE_KEY') and settings.SSO_PRIVATE_KEY:
        sso = True
    else:
        sso = False
    return render(request, 'login.html', {'form': form, 'sso': sso}) 
Example #3
Source File: views.py    From python-monitoring-talk with Apache License 2.0 6 votes vote down vote up
def login_view(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('/post/')
    if request.method == 'GET':
        form = AuthenticationForm()
        return render(request, 'tilweb/login.html', {'form': form})
    if request.method == 'POST':
        form = AuthenticationForm(request=request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                print(user)
                login(request, user)
                return HttpResponseRedirect('/post/')
            else:
                print('User not found')
        else:
            # If there were errors, we render the form with these
            # errors
            return render(request, 'tilweb/login.html', {'form': form}) 
Example #4
Source File: views.py    From djacket with MIT License 6 votes vote down vote up
def user_login(request):
    """
        View for logging users in.
    """

    redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME, ''))
    login_form = AuthenticationForm(request, data=request.POST)
    if login_form.is_valid():
        # Ensure the user-originating redirection url is safe.
        if not is_safe_url(url=REDIRECT_FIELD_NAME, host=request.get_host()):
            redirect_to = settings.LOGIN_REDIRECT_URL
        # Okay, security check complete. Log the user in.
        auth_login(request, login_form.get_user())
        return redirect(settings.LOGIN_REDIRECT_URL if redirect_to == '' else redirect_to)
    else:
        return render(request, 'index.html', {'login_form': login_form, 'display': 'block', 'active': 'login'}) 
Example #5
Source File: user.py    From GetTogether with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def login(request):
    if request.user.is_authenticated:
        messages.add_message(
            request, messages.INFO, message=_("You are already logged in.")
        )
        return redirect("home")

    context = {"login_form": AuthenticationForm(), "signup_form": UserCreationForm()}
    if request.method == "POST":
        if request.POST.get("action") == "login":
            login_form = AuthenticationForm(data=request.POST)
            if login_form.is_valid():
                username = login_form.cleaned_data.get("username")
                raw_password = login_form.cleaned_data.get("password")
                user = authenticate(username=username, password=raw_password)
                login_user(request, user, backend=user.backend)
                return redirect("home")
            else:
                context["login_form"] = login_form
                context["action"] = "login"
        elif request.POST.get("action") == "signup":
            signup_form = UserCreationForm(data=request.POST)
            if signup_form.is_valid():
                signup_form.save()
                username = signup_form.cleaned_data.get("username")
                raw_password = signup_form.cleaned_data.get("password1")
                user = authenticate(username=username, password=raw_password)
                login_user(request, user, backend=user.backend)
                return redirect("home")
            else:
                context["signup_form"] = signup_form
                context["action"] = "signup"

    return render(request, "get_together/users/login.html", context) 
Example #6
Source File: views.py    From c3nav with Apache License 2.0 6 votes vote down vote up
def login_view(request):
    if request.user.is_authenticated:
        return close_response(request)

    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            login(request, form.user_cache)
            redeem_token_after_login(request)
            return close_response(request)
    else:
        form = AuthenticationForm(request)

    ctx = {
        'title': _('Log in'),
        'form': form,
    }

    if settings.USER_REGISTRATION:
        ctx.update({
            'bottom_link_url': reverse('site.register'),
            'bottom_link_text': _('Create new account')
        })

    return render(request, 'site/account_form.html', ctx) 
Example #7
Source File: views.py    From django-bananas with MIT License 6 votes vote down vote up
def create(self, request):
        """
        Log in django staff user
        """
        # TODO: Decorate api with sensitive post parameters as Django admin do?
        # from django.utils.decorators import method_decorator
        # from django.views.decorators.debug import sensitive_post_parameters
        # sensitive_post_parameters_m = method_decorator(sensitive_post_parameters())

        login_form = AuthenticationForm(request, data=request.data)

        if not login_form.is_valid():
            raise serializers.ValidationError(login_form.errors)

        auth_login(request, login_form.get_user())

        serializer = UserSerializer(request.user)
        return Response(serializer.data, status=status.HTTP_200_OK) 
Example #8
Source File: account.py    From c3nav with Apache License 2.0 6 votes vote down vote up
def login_view(request):
    redirect_path = request.GET['r'] if request.GET.get('r', '').startswith('/editor/') else reverse('editor.index')
    if request.user.is_authenticated:
        return redirect(redirect_path)

    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            login(request, form.user_cache)
            return redirect(redirect_path)
    else:
        form = AuthenticationForm(request)

    return render(request, 'editor/account_form.html', {
        'title': _('Log in'),
        'form': form,
        'bottom_link_url': reverse('site.register'),
        'bottom_link_text': _('Create new account')
    }) 
Example #9
Source File: views.py    From 2buntu-blog with Apache License 2.0 6 votes vote down vote up
def login(request):
    """
    Log a user in.
    """
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            login_user(request, form.get_user())
            return redirect(request.GET['next'] if 'next' in request.GET else 'home')
    else:
        form = AuthenticationForm()
    return render(request, 'accounts/login.html', {
        'title': 'Login',
        'form': form,
        'action': 'Login',
    }) 
Example #10
Source File: views.py    From medadfeshari with GNU General Public License v3.0 6 votes vote down vote up
def login_request(request):
	if request.method == "POST":
		form = AuthenticationForm(request, data=request.POST)
		if form.is_valid():
			username = form.cleaned_data.get('username')
			password = form.cleaned_data.get('password')
			user = authenticate(username=username,password=password)
			if user is not None:
				login(request,user)
				messages.info(request, _("You are now logged in as ") + username)
				return redirect("main:homepage")

			else:
				messages.error(request, _("Invalid ysername or password or recaptcha"))

		else:
			messages.error(request, _("Invalid ysername or password or recaptcha"))

	form = AuthenticationForm()
	return render(request,
					"main/login.html",
					{"form":form}) 
Example #11
Source File: test_views.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_disable_signups_has_special_instructions(self):
        with TempSiteID(2):
            Site.objects.create(id=2)
            response = self.client.get(self.login_url)
        self.assertIsInstance(response.context["form"], AuthenticationForm)
        self.assertContains(response, "You should have gotten an email") 
Example #12
Source File: account.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def login(request):
    if request.method == "POST":
        if request.user.is_authenticated:
            return HttpResponse(status=204)
        form = AuthenticationForm(data=request.POST, request=request)
        if form.is_valid():
            auth_login(request, form.get_user())
            create_audit_event(
                EVENT_TYPES.AUTHORISATION,
                ENDPOINT.UI,
                request,
                None,
                description=(
                    "Logged in %s."
                    % ("admin" if request.user.is_superuser else "user")
                ),
            )
            return HttpResponse(status=204)
        return HttpResponseBadRequest(
            json.dumps(form.errors), content_type="application/json"
        )
    return JsonResponse(
        {
            "authenticated": request.user.is_authenticated,
            "external_auth_url": request.external_auth_info.url
            if request.external_auth_info
            else None,
            "no_users": not UserProfile.objects.all_users().exists(),
        }
    ) 
Example #13
Source File: views.py    From cryptofolio with GNU General Public License v3.0 5 votes vote down vote up
def login(request):
    redirect_to = request.GET.get(REDIRECT_FIELD_NAME, '')

    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(django_settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            return HttpResponseRedirect(redirect_to)
        else:
            messages.warning(request, 'Wrong username and/or password!')
    else:
        form = AuthenticationForm(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        REDIRECT_FIELD_NAME: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }

    return render(request, 'login.html', context) 
Example #14
Source File: views.py    From SOMS with GNU General Public License v3.0 5 votes vote down vote up
def login(request, redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm):
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))
    verify_err = ''
    if request.method == "POST":
        if request.POST.has_key('login'):
            form = authentication_form(request, data=request.POST)
            if form.is_valid():
                verify_code = request.POST.get('verify_code')
                if form.get_user() and form.get_user().is_active:
                    if form.get_user().mfa:
                        result = soms_mfa(form.get_user().mfa, str(verify_code))
                    else:
                        result = True
                    if not result:
                        verify_err = u'验证码错误'
                    else:
                        # Ensure the user-originating redirection url is safe.
                        if not is_safe_url(url=redirect_to, host=request.get_host()):
                            redirect_to = resolve_url(djsettings.LOGIN_REDIRECT_URL)
                        auth_login(request, form.get_user())
                        Message.objects.create(type=u'用户登录', user=request.user, action=u'用户登录',
                                               action_ip=UserIP(request), content='用户登录 %s'%request.user)
                        return HttpResponseRedirect(redirect_to)
            else:
                Message.objects.create(type=u'用户登录', user=request.POST.get('username'), action=u'用户登录',
                                       action_ip=UserIP(request), content=u'用户登录失败 %s'%request.POST.get('username'))
    else:
        form = authentication_form(request)
    return render(request, 'registration/login.html', {'form': form, 'verify_err': verify_err, 'title': '用户登录'}) 
Example #15
Source File: views.py    From ecommerce-2-api with MIT License 5 votes vote down vote up
def get_context_data(self, *args, **kwargs):
		context = super(CheckoutView, self).get_context_data(*args, **kwargs)
		user_can_continue = False
		user_check_id = self.request.session.get("user_checkout_id")
		if self.request.user.is_authenticated():
			user_can_continue = True
			user_checkout, created = UserCheckout.objects.get_or_create(email=self.request.user.email)
			user_checkout.user = self.request.user
			user_checkout.save()
			context["client_token"] = user_checkout.get_client_token()
			self.request.session["user_checkout_id"] = user_checkout.id
		elif not self.request.user.is_authenticated() and user_check_id == None:
			context["login_form"] = AuthenticationForm()
			context["next_url"] = self.request.build_absolute_uri()
		else:
			pass

		if user_check_id != None:
			user_can_continue = True
			if not self.request.user.is_authenticated(): #GUEST USER
				user_checkout_2 = UserCheckout.objects.get(id=user_check_id)
				context["client_token"] = user_checkout_2.get_client_token()
		
		#if self.get_cart() is not None:
		context["order"] = self.get_order()
		context["user_can_continue"] = user_can_continue
		context["form"] = self.get_form()
		return context 
Example #16
Source File: views.py    From python101 with MIT License 5 votes vote down vote up
def loguj(request):
    """Logowanie użytkownika"""
    from django.contrib.auth.forms import AuthenticationForm
    if request.method == 'POST':
        form = AuthenticationForm(request, request.POST)
        if form.is_valid():
            login(request, form.get_user())
            messages.success(request, "Zostałeś zalogowany!")
            return redirect(reverse('czat:index'))

    kontekst = {'form': AuthenticationForm()}
    return render(request, 'czat/loguj.html', kontekst) 
Example #17
Source File: views.py    From python101 with MIT License 5 votes vote down vote up
def loguj(request):
    """Logowanie użytkownika"""
    from django.contrib.auth.forms import AuthenticationForm
    if request.method == 'POST':
        form = AuthenticationForm(request, request.POST)
        if form.is_valid():
            login(request, form.get_user())
            messages.success(request, "Zostałeś zalogowany!")
            return redirect(reverse('czat:index'))

    kontekst = {'form': AuthenticationForm()}
    return render(request, 'czat/loguj.html', kontekst) 
Example #18
Source File: views.py    From iguana with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        logged_out = 0
        if request.user.is_active:
            # the user gets logged out in the super() call later
            logged_out = 1
        self.extra_context = {'form': AuthenticationForm(), 'logged_out': logged_out}
        return D_LOV.dispatch(self, request, *args, **kwargs)


# https://docs.djangoproject.com/en/1.10/topics/forms/
# https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/
# TODO FormView might help to simplify this class
# this view creates an account which is not activated until the confirmation link send via email has been requested
# NOTE: This view can be used to leak usernames and email addresses that are already in use.
#       Those leaks are limited to requests where the captcha has been solved successfully. 
Example #19
Source File: views.py    From django-example-channels with MIT License 5 votes vote down vote up
def log_in(request):
    form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            login(request, form.get_user())
            return redirect(reverse('example:user_list'))
        else:
            print(form.errors)
    return render(request, 'example/log_in.html', {'form': form}) 
Example #20
Source File: test_views.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_displays_login_form(self):
        response = self.client.get(self.login_url)
        self.assertIsInstance(response.context["form"], AuthenticationForm) 
Example #21
Source File: api.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def get_token(self, request, *args, **kwargs):
        # django-rest-framework doesn't do this for logged out requests
        SessionAuthentication().enforce_csrf(request)

        data = get_api_post_data(request)

        form = AuthenticationForm(request, data=data)
        if not form.is_valid():
            raise ParseError(form.errors)

        token = form.user_cache.login_tokens.create()

        return Response({
            'token': token.get_token(),
        }) 
Example #22
Source File: api.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def login(self, request, *args, **kwargs):
        # django-rest-framework doesn't do this for logged out requests
        SessionAuthentication().enforce_csrf(request)

        if request.user.is_authenticated:
            raise ParseError(_('Log out first.'))

        data = get_api_post_data(request)

        if 'token' in data:
            try:
                token = Token.get_by_token(data['token'])
            except Token.DoesNotExist:
                raise PermissionDenied(_('This token does not exist or is no longer valid.'))
            user = token.user
        elif 'username' in data:
            form = AuthenticationForm(request, data=data)
            if not form.is_valid():
                raise ParseError(form.errors)
            user = form.user_cache
        else:
            raise ParseError(_('You need to send a token or username and password.'))

        login(request, user)

        return Response({
            'detail': _('Login successful.'),
            'csrf_token': csrf.get_token(request),
        }) 
Example #23
Source File: views.py    From rdmo with Apache License 2.0 5 votes vote down vote up
def home(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect(reverse('projects'))
    else:
        if settings.SHIBBOLETH:
            return render(request, 'core/home.html')
        elif settings.ACCOUNT or settings.SOCIALACCOUNT:
            from allauth.account.forms import LoginForm
            return render(request, 'core/home.html', {'form': LoginForm()})
        else:
            from django.contrib.auth.forms import AuthenticationForm
            return render(request, 'core/home.html', {'form': AuthenticationForm()}) 
Example #24
Source File: views.py    From Politikon with GNU General Public License v2.0 4 votes vote down vote up
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        response = {}
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())
            return JsonResponse({'redirect_to': redirect_to})
        else:
            if hasattr(form, 'errors'):
                response['errors'] = {}
                for field_name, error_message in form.errors.items():
                    response['errors'][field_name] = error_message
            else:
                pass
        return JsonResponse(response)

    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)

    if current_app is not None:
        request.current_app = current_app

    return TemplateResponse(request, template_name, context)