Python django.contrib.auth 模块,authenticate() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.auth.authenticate()

项目:til    作者:amitsaha    | 项目源码 | 文件源码
def signup(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('/post/')
    if request.method == 'GET':
        form = UserCreationForm()
        return render(request, 'tilweb/signup.html', {'form': form})
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            # https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#the-save-method
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            return HttpResponseRedirect('/post/')
        else:
            # If there were errors, we render the form with these
            # errors
            return render(request, 'tilweb/signup.html', {'form': form})
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def user_login(request):
    """
    Logins user if he passed authentication.
    """
    log_in_form = LogInForm(request.POST)

    if log_in_form.is_valid():
        user = authenticate(username=log_in_form.cleaned_data['username'],
                            password=log_in_form.cleaned_data['passw'])
        if user:
            login(request, user)
            logger.info("User '{}' logged in.".format(user.username))

            return redirect('index')
        else:
            return render(request, 'index.html', {'invalid_authentication': True})


# ----------------------------------------------------------------------------------------------------------------------
项目:django-simplestore    作者:martinstastny    | 项目源码 | 文件源码
def form_valid(self, form):
        self.profile = form.save()
        self.request.session['user_cart'] = self.request.session.session_key

        user = authenticate(
            email=self.profile.email,
            password=self.request.POST['password1']
        )

        messages.add_message(
            self.request, messages.SUCCESS,
            'You were successfully logged in.'
        )

        login(self.request, user)
        return super(RegistrationFormView, self).form_valid(form)
项目:docker-box    作者:MicroPyramid    | 项目源码 | 文件源码
def index(request):
    if request.method == "POST":
        user = authenticate(username=request.POST.get('email'), password=request.POST.get('password'))
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(request.GET.get('next') or '/')
            else:
                response_data = {'message': "Your account has been disabled!"}
        else:
            response_data = {'message': 'The username and password are incorrect.'}
        return render(request, 'login.html', response_data)

    elif request.user.is_authenticated():
        host_name, kernel = uname()[1:3]
        return render(request, 'dashboard.html', {'host_name': host_name, 'kernel': kernel, 'ip_addr': HOST_IP_ADDR})

    else:
        return render(request, 'login.html')
项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
def clean(self):
        #Get login data
        username=self.cleaned_data.get("username")
        password=self.cleaned_data.get("password")

        #Checking authentication
        if username and password:
            user=authenticate(username=username, password=password)
            """
            The following bunch of if, else if statements will return errors if the following
            cases are met
            -- Login is not valid
            -- Login is currently not active
            -- If the user does not have groups associated with them
            """
            if ((not user) or (not user.check_password(password))):
                raise forms.ValidationError("The login details are incorrect")
            elif (not user.is_active):
                raise forms.ValidationError("Please contact your system administrator. Your account has been disabled")
            elif (user_groups.objects.filter(username_id=user.id, is_deleted='FALSE').count() == 0):
                raise forms.ValidationError("Please contact your system administrator. Your account has no group access")
        return super(login_form, self).clean()
项目:drf-simple-auth    作者:nickromano    | 项目源码 | 文件源码
def post(self, request):  # noqa
        username = request.data.get('username')
        password = request.data.get('password')
        device_id = request.data.get('device_id') or ''

        if not username or not password:
            return Response(
                {'error': 'Missing username or password'},
                status=status.HTTP_400_BAD_REQUEST
            )

        user = authenticate(
            username=username.lower(), password=password
        )
        if not user:
            raise InvalidEmailOrPasswordAPIException()

        auth_token, _ = AuthToken.objects.get_or_create(
            user=user, device_id=device_id
        )

        return Response({'token': auth_token.key})
项目:django-fieldbook    作者:bsab    | 项目源码 | 文件源码
def form_valid(self, form):
        user = form.save(commit=False);
        user.set_password(form.cleaned_data['password']);
        user.username = form.cleaned_data['username'].lower();
        user.email = form.cleaned_data['email'].lower();
        user.is_active = True;
        user.save();

        fbuserprofile = FieldBookUser();
        fbuserprofile.user = user;
        # saving the fieldbook key and password
        fbuserprofile.fieldbook_api_key = form.cleaned_data['username'].lower();
        fbuserprofile.fieldbook_api_secret = form.cleaned_data['password'];
        fbuserprofile.fieldbook_book= form.cleaned_data['fieldbook_book'];
        fbuserprofile.save();

        # execute login
        user_logged = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']);
        login(self.request, user_logged);

        return HttpResponseRedirect(self.get_success_url())
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def clean(self):
        # clean()???? ??? ???? dict? ???
        # cleaned_data = super().clean()
        # username, password? ??? ????? ??
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        # username, password? ??? ??? authenticate
        user = authenticate(
            username=username,
            password=password
        )
        # ??? ??? ??, Form? cleaned_data? 'user'
        # ?? ??? User??? ??
        if user is not None:
            self.cleaned_data['user'] = user
        # ??? ??? ??, is_valid()? ???? ????
        # ValidationError? ????
        else:
            raise forms.ValidationError(
                'Login credentials not valid'
            )
        return self.cleaned_data
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def user_login(request):
    """
    Authenticates user and returns the token which uses to access to the API.
    """
    user = authenticate(username=request.data.get('username'),
                        password=request.data.get('password'))
    if user:
        user_token = TheUser.objects.get(id_user=user).auth_token

        login(request, user)
        logger.info("User '{}' logged in.".format(user.username))

        return Response({'status': 200,
                         'detail': 'successful',
                         'data': {'token': user_token}})

    return Response({'status': 404,
                     'detail': 'not authenticated',
                     'data': {'token': None}})


# ----------------------------------------------------------------------------------------------------------------------
项目:webtzite    作者:materialsproject    | 项目源码 | 文件源码
def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            code = LoginCode.objects.filter(**{
                'user__email': request.POST.get('username')
            })[0]
            code.next = reverse('webtzite_register')
            code.save()
            code.send_login_code(
                secure=request.is_secure(),
                host=request.get_host(),
            )
            return render(request, 'registration/sent_mail.html')

    jpy_user = os.environ.get('JPY_USER')
    if jpy_user:
        from django.contrib.auth import authenticate
        code = authenticate(code=None, username=jpy_user+'@users.noreply.github.com')
        user = authenticate(code=code.code, username=code.user.username)
        auth_login(request, user)
        return redirect(reverse('webtzite_register'))

    return django_login(request, authentication_form=AuthenticationForm)
项目:django-simplestore    作者:martinstastny    | 项目源码 | 文件源码
def form_valid(self, form):

        cart = get_cart(self.request, create=True)
        user = authenticate(email=self.request.POST['email'], password=self.request.POST['password'])

        if user is not None and user.is_active:
            self.request.session['user_cart'] = self.request.session.session_key
            login(self.request, user)

            if cart is not None:
                cart.user = Profile.objects.get(id=user.id)
                cart.save()
                messages.add_message(self.request, messages.SUCCESS, 'You were successfully logged in.')

            return super(AuthenticationForm, self).form_valid(form)

        else:
            response = super(AuthenticationForm, self).form_invalid(form)
            messages.add_message(self.request, messages.WARNING, 'Wrong email or password. Please try again')
            return response


# Logout View
项目:Peru    作者:ESEGroup    | 项目源码 | 文件源码
def post(self, request):
        form_busca = formBusca()
        form = self.form_class(request.POST)
        if form.is_valid():
            user      = form.save(commit=False)
            nome      = form.cleaned_data['nome']
            username  = form.cleaned_data['username']
            email     = form.cleaned_data['email']
            celular   = form.cleaned_data['celular']
            descricao = form.cleaned_data['descricao']
            password  = form.cleaned_data['password']
            user.set_password(password)
            user.save()

            user = authenticate(username=username, password=password)

            if user is not None:

                if user.is_active:
                    login(request, user)
                    return redirect('../')
        return render(request, self.template_name, {'form': form, 'formBusca':form_busca, 'localidade':"Localidade "})
项目:Peru    作者:ESEGroup    | 项目源码 | 文件源码
def post(self, request):
        form_busca = formBusca()
        form = self.form_class(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('../')
                else:
                    print("Sua conta foi desabilitada!")
            else:
                print("Seu nome de usuario e/ou senha estao incorretos.")
        return render(request, self.template_name, {'form': form, 'formBusca':form_busca, 'localidade':"Localidade "})
项目:byro    作者:byro    | 项目源码 | 文件源码
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)

        if user is None:
            messages.error(request, _('No user account matches the entered credentials.'))
            return redirect('common:login')

        if not user.is_active:
            messages.error(request, _('User account is deactivated.'))
            return redirect('common:login')

        login(request, user)
        url = urllib.parse.unquote(request.GET.get('next', ''))
        if url and is_safe_url(url, request.get_host()):
            return redirect(url)

        return redirect('/')
项目:lightning-coindesk    作者:lightninglabs    | 项目源码 | 文件源码
def verify(request):

    assert 'login_signature' in request.POST, "No signature supplied"
    kwargs = {
        'username': request.POST.get('login_username'),
        'signature': request.POST.get('login_signature'),
        'csrf_token': str(request.POST.get('csrfmiddlewaretoken'))
    }

    user = authenticate(request=request, **kwargs)
    if user is None:
        raise Exception("Failed to log in")
        # return HttpResponseRedirect('/login')
    else:
        login(request, user)
        return HttpResponseRedirect("/")
项目:OpsManage    作者:welliamcao    | 项目源码 | 文件源码
def login(request):
    if request.session.get('username') is not None:
        return HttpResponseRedirect('/',{"user":request.user})
    else:
        username = request.POST.get('username')
        password = request.POST.get('password') 
        user = auth.authenticate(username=username,password=password)
        if user and user.is_active:
            auth.login(request,user)
            request.session['username'] = username
            return HttpResponseRedirect('/user/center/',{"user":request.user})
        else:
            if request.method == "POST":
                return render(request,'login.html',{"login_error_info":"???????????????"},)  
            else:
                return render(request,'login.html')
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def login(self, **credentials):
        """
        Sets the Factory to appear as if it has successfully logged into a site.

        Returns True if login is possible; False if the provided credentials
        are incorrect, or the user is inactive, or if the sessions framework is
        not available.
        """
        from django.contrib.auth import authenticate
        user = authenticate(**credentials)
        if (user and user.is_active and
                apps.is_installed('django.contrib.sessions')):
            self._login(user)
            return True
        else:
            return False
项目:OJ    作者:nishantcoder97    | 项目源码 | 文件源码
def post(self, request):
        form1=self.form_class1(request.POST)
        form2 = self.form_class2(request.POST)
        if form1.is_valid() and form2.is_valid():
            user = form1.save(commit=False)
            coder = form2.save(commit=False)
            username = form1.cleaned_data['username']
            password = form1.cleaned_data['password']
            email = form1.clean_email()
            user.set_password(password)
            user.save()
            coder.user = user
            coder.save()

            user = authenticate(username = username,password = password)
            if user is not None:

                if user.is_active:
                    login(request, user)
                    return redirect('/')
        return render(request, self.template_name, {'form1': form1, 'form2': form2})
项目:django-rest-framework-sso    作者:namespace-ee    | 项目源码 | 文件源码
def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if username and password:
            user = authenticate(username=username, password=password)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg)
            else:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg)
        else:
            msg = _('Must include "username" and "password".')
            raise serializers.ValidationError(msg)

        attrs['user'] = user
        return attrs
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def create_password(request, token):
    if request.user.is_authenticated:
        return redirect('order:details', token=token)
    order = get_object_or_404(Order, token=token)
    email = order.user_email
    form_data = request.POST.copy()
    if form_data:
        form_data.update({'email': email})
    register_form = PasswordForm(form_data or None)
    if User.objects.filter(email=email).exists():
        login_form = LoginForm(initial={'login': email})
    else:
        login_form = None
    if register_form.is_valid():
        register_form.save()
        password = register_form.cleaned_data.get('password')
        user = auth.authenticate(request=request, email=email,
                                 password=password)
        auth.login(request, user)
        attach_order_to_user(order, user)
        return redirect('order:details', token=token)
    ctx = {'form': register_form, 'email': email, 'order': order,
           'login_form': login_form}
    return TemplateResponse(request, 'order/create_password.html', ctx)
项目:BioQueue    作者:liyao001    | 项目源码 | 文件源码
def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=cd['username'], password=cd['password'])

            if user is not None:
                if user.is_active:
                    login(request, user)
                    return success('Authenticated successfully', '/ui')
                else:
                    return error('Disabled account')
            else:
                return error('Wrong username or password')
        else:
            return error(str(form.errors))
    else:
        form = LoginForm()
    return render(request, 'accounts/login.html', {'form': form})
项目:BioQueue    作者:liyao001    | 项目源码 | 文件源码
def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.POST)
        if form.is_valid():
            username = request.user.username
            cd = form.cleaned_data
            user = authenticate(username=username, password=cd['old_password'])
            if user is not None and user.is_active:
                new_password = cd['new_password_1']
                user.set_password(new_password)
                user.save()
                update_session_auth_hash(request, username)
                return success('Your password had been updated.', 'accounts:login')
            else:
                return error('Password doesn\'t match.')
        else:
            return error('Your form is illegal.')
    else:
        return error('Please confirm your approaching method.')
项目:consilium    作者:DrSLDR    | 项目源码 | 文件源码
def auth(request):
    try:
        username = request.POST['username']
        password = request.POST['password']
    except (KeyError):
        # Be very upset and just throw the fool back
        return index(request)
    else:
        # Attempt authentication
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/login')
        else:
            # Login failed
            return render(request, 'login/index.html', {
                'version' : settings.VERSION,
                'authfail' : True,
            })
项目:django_velespi    作者:aysedilekk    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")

        if not username or not password:
            return self.cleaned_data

        user = authenticate(username=username,
                            password=password)

        if user:
            self.user = user
        else:
            raise ValidationError("Yanlis kullanici adi veya sifre!")

        return self.cleaned_data
项目:docker-grader    作者:elsys    | 项目源码 | 文件源码
def process_request(self, request):
        if request.method == 'POST' and \
           request.POST.get('lti_message_type') == 'basic-lti-launch-request':
            logger.debug('received a basic-lti-launch-request - '
                         'authenticating the user')

            # authenticate and log the user in
            user = auth.authenticate(request=request)

            if user is not None:
                # User is valid.
                # Set request.user and
                # persist user in the session by logging the user in.

                logger.debug('user was successfully authenticated; '
                             'now log them in')
                request.user = user
                auth.login(request, user)
                return HttpResponseRedirect(request.get_full_path())
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def login_auth(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    goto_page = request.POST.get('next')
    logger.debug('try to login, username: '+username+', password: '+password+', goto_page: '+str(goto_page))
    # TODO: ??????‘???’?????????
    if not username or not password:
        return login(request, {'errors': '?????????'})
    # ????????
    newUser=auth.authenticate(username=username,password=password)
    if newUser is not None:
        if not is_manager(newUser):
            return login(request, {'errors': '???????'})
        auth.login(request, newUser)
        if goto_page:
            return redirect(goto_page)
        else:
            return redirect('staff:index')
    return login(request, {'errors': '????????'})
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def post(self, request):
        var = ('username', 'password',)
        vard = {}

        for k in var:
            v = request.POST.get(k, '')
            if not v:
                return JsonResponse({'error': k + ' is empty'})
            vard[k] = v

        user = auth.authenticate(
            username=vard['username'], password=vard['password'])
        if user is None:
            return JsonResponse({'error': 'username or password incorrect'})
        if not is_lecturer(user):
            return JsonResponse({'error': 'you are not authorized'})

        auth.login(request, user)
        return redirect('lecturer:index')
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def test_get_token_key(self):
        client = Client()
        request_url = "/api/v1/token-auth"
        username = "parent1"
        password = "123123"
        user = authenticate(username=username, password=password)
        self.assertNotEqual(user, None)
        parent_user = User.objects.get(username=username)
        self.assertEqual(parent_user.is_active, 1)
        response = client.post(request_url, {"username": username,
                                             "password": password})
        self.assertEqual(response.status_code, 200)

        client2 = Client()
        response2 = client2.post(request_url, {"username": username,
                                               "password": password})
        self.assertEqual(response.content, response2.content)
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def new_student() -> User:
        # ????
        username = random_string()[:30]
        salt = random_string()[:5]
        password = "malalaoshi"
        user = User(username=username)
        user.email = ""
        user.password = make_password(password, salt)
        user.save()
        student_group = Group.objects.get(name="??")
        user.groups.add(student_group)
        # ??????
        profile = Profile(user=user)
        profile.save()
        student = Student(user=user)
        student.save()
        # ????
        user.save()
        profile.save()
        student.save()
        ret_user = authenticate(username=username, password=password)
        return ret_user
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    User = get_user_model()
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        return self.cleaned_data
项目:nostray_prototype    作者:nostray    | 项目源码 | 文件源码
def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return render(request, 'index.html')
                else:
                    return render(request, 'login.html', {'msg':'??????', 'login_form':login_form})
            else:
                return render(request, 'login.html', {'msg':'?????????', 'login_form':login_form})
        else:
            return render(request, 'login.html', {'msg':'???????????', 'login_form':login_form})
项目:postix    作者:c3cashdesk    | 项目源码 | 文件源码
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)

        if user is None:
            messages.error(request, _('No user account matches the entered credentials.'))
            return redirect('backoffice:login')

        if not user.is_active:
            messages.error(request, _('User account is deactivated.'))
            return redirect('backoffice:login')

        if not is_backoffice_user(user):
            messages.error(request, _('User does not have permission to access backoffice data.'))
            return redirect('backoffice:login')

        login(request, user)
        url = request.GET.get('next')
        if url and is_safe_url(url, request.get_host()):
            return redirect(url)

        return redirect('backoffice:main')
项目:postix    作者:c3cashdesk    | 项目源码 | 文件源码
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)

        if user is None:
            messages.error(request, _('No user account matches the entered credentials.'))
            return redirect('troubleshooter:login')

        if not user.is_active:
            messages.error(request, _('User account is deactivated.'))
            return redirect('troubleshooter:login')

        if not troubleshooter_user(user):
            messages.error(request, _('User does not have permission to access troubleshooter data.'))
            return redirect('troubleshooter:login')

        login(request, user)
        return redirect('troubleshooter:main')
项目:postix    作者:c3cashdesk    | 项目源码 | 文件源码
def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponseRedirect:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if not user.is_active:
                messages.error(request, _('User account is deactivated.'))
                return redirect('desk:login')

            session = user.get_current_session()
            if session is None:
                messages.error(request, _('You do not have an active session.'))
                return redirect('desk:login')

            if session.cashdesk != self.cashdesk:
                messages.error(request, _('Your session is scheduled for a different cashdesk. Please go to '
                                          '{desk}').format(desk=str(session.cashdesk)))
                return redirect('desk:login')

            login(request, user)
            session.cashdesk.signal_next()
            return redirect('desk:main')
        else:
            messages.error(request, _('No user account matches the entered credentials.'))
        return redirect('desk:login')
项目:quora-django    作者:hndrxr    | 项目源码 | 文件源码
def post(self, request):
        form = self.form_class(request.POST)
        if form.is_valid():
            username, password = form.cleaned_data['username'], form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                if user.is_active:
                    login(request, user)
                    return redirect("/")
                else:
                    form.add_error("username", "Please confirm your password")
                    return render(request, "account/login.html", {"form": form})
            else:
                form.add_error("password", "Invalid username or password")
                return render(request, "account/login.html", {"form": form})
        else:
            return render(request, "account/login.html", {"form": form})
项目:dream_blog    作者:fanlion    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    User = get_user_model()
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        return self.cleaned_data
项目:MxOnline    作者:myTeemo    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    User = get_user_model()
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        return self.cleaned_data
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def login(request):
    username = auth.get_user(request).username
    if (username):
        return redirect('/')
    else:
        args = {}
        args.update(csrf(request))
        if request.POST:
            username = request.POST.get('username','')
            password = request.POST.get('password','')
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                if not request.POST.get('remember-me', ''):
                    request.session.set_expiry(0)
                auth.login(request, user)
                return redirect('/')
            else:
                args['login_error'] = format_html("<div class=\"main-error alert alert-error\">???????????? ??? ???????????? ??? ??????</div>")
                return render_to_response('login.html', args)
        else:
            return render_to_response('login.html', args)
项目:SPBU-DBMS-Project    作者:Betekhtin    | 项目源码 | 文件源码
def register(request):
    username = auth.get_user(request).username
    if not (username):
        args={}
        args.update(csrf(request))
        args['form']=UserCreationForm()
        if request.POST:
            newuser_form=UserCreationForm(request.POST)
            if newuser_form.is_valid():
                newuser_form.save()
                newuser = auth.authenticate(username=newuser_form.cleaned_data['username'],password=newuser_form.cleaned_data['password2'])
                auth.login(request, newuser)
                return redirect('/')
            else:
                args['errors'] = format_html('<div class="main-error alert alert-error">?????? ??? ???????????</div>')
                args['form'] = newuser_form
        return render_to_response('register.html',args)
    else:
        return redirect('/')
项目:healthchecks_asgards    作者:andela    | 项目源码 | 文件源码
def set_password(request, token):
    profile = request.user.profile
    if not check_password(token, profile.token):
        return HttpResponseBadRequest()

    if request.method == "POST":
        form = SetPasswordForm(request.POST)
        if form.is_valid():
            password = form.cleaned_data["password"]
            request.user.set_password(password)
            request.user.save()

            profile.token = ""
            profile.save()

            # Setting a password logs the user out, so here we
            # log them back in.
            u = authenticate(username=request.user.email, password=password)
            auth_login(request, u)

            messages.success(request, "Your password has been set!")
            return redirect("hc-profile")

    return render(request, "accounts/set_password.html", {})
项目:lti-demo-haiku    作者:open-craft    | 项目源码 | 文件源码
def authentication_hook(self, request, user_id=None, username=None, email=None, extra_params=None):
        extra = extra_params if extra_params else {}

        # automatically generate password from user_id
        password = self._generate_password(user_id, settings.PASSWORD_GENERATOR_NONCE)

        # username and email might be empty, depending on how edX LTI module is configured:
        # there are individual settings for that + if it's embedded into an iframe it never sends
        # email and username in any case
        # so, since we want to track user for both iframe and non-iframe LTI blocks, username is completely ignored
        uname = self._compress_user_name(user_id)
        email = email if email else user_id+'@localhost'
        try:
            User.objects.get(username=uname)
        except User.DoesNotExist:
            try:
                User.objects.create_user(username=uname, email=email, password=password)
            except IntegrityError as e:
                # A result of race condition of multiple simultaneous LTI requests - should be safe to ignore,
                # as password and uname are stable (i.e. not change for the same user)
                logger.info("IntegrityError creating user - assuming result of race condition: %s", e.message)

        authenticated = authenticate(username=uname, password=password)
        login(request, authenticated)
项目:VManagePlatform    作者:welliamcao    | 项目源码 | 文件源码
def login(request):
    if request.session.get('username') is not None:
        return HttpResponseRedirect('/profile',{"user":request.user})
    else:
        username = request.POST.get('username')
        password = request.POST.get('password') 
        user = auth.authenticate(username=username,password=password)
        if user and user.is_active:
            auth.login(request,user)
            request.session['username'] = username
            return HttpResponseRedirect('/profile',{"user":request.user})
        else:
            if request.method == "POST":
                return render_to_response('login.html',{"login_error_info":"???????????????"},
                                                        context_instance=RequestContext(request))  
            else:
                return render_to_response('login.html',context_instance=RequestContext(request))
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def change_password(request):

    if request.method == 'POST':
        user = request.user
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')

        if authenticate(username=user.username, password=old_password):
            if new_password == confirm_password:
                user.set_password(new_password)
                user.save()
                messages.success(request, 'Password Updated')
            else:
                messages.warning(request, 'Passwords do not match')
        else:
            messages.warning(request, 'Invalid Password')

    return render(request,
                  'taskManager/change_password.html',
                  {'user': request.user})
项目:registration    作者:HackAssistant    | 项目源码 | 文件源码
def signup(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        form = forms.RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            name = form.cleaned_data['name']

            if models.User.objects.filter(email=email).first() is not None:
                messages.error(request, 'An account with this email already exists')
            else:
                user = models.User.objects.create_user(email=email, password=password, name=name)
                user = auth.authenticate(email=email, password=password)
                auth.login(request, user)
                return HttpResponseRedirect(reverse('root'))
    else:
        form = forms.RegisterForm()

    return render(request, 'signup.html', {'form': form})
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    User = get_user_model()
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        return self.cleaned_data
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
def register(request):
    if request.method == 'POST':
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user = register_form.save()
            if user is not None:
                user = authenticate(username=register_form.cleaned_data['username'],password=register_form.cleaned_data['password'])
                auth_login(request,user)
                return HttpResponseRedirect(reverse('index-view'))
        else:
            auth_logout(request)
            return render(request, 'users/register.html', {'errors': register_form.errors})
    else:
        register_form = RegisterForm()
        user = None
    return render(request, 'users/register.html')
项目:django-username-email    作者:tmm    | 项目源码 | 文件源码
def clean(self):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')

        if email and password:
            if django.VERSION >= (1, 11):
                self.user_cache = authenticate(self.request, email=email, password=password)
            else:
                self.user_cache = authenticate(email=email, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data
项目:autostew    作者:Autostew    | 项目源码 | 文件源码
def login_view(request):
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                messages.add_message(request, messages.SUCCESS, "Login successful.", extra_tags='success')
                return redirect('account:home')
            else:
                messages.add_message(request, messages.ERROR, "You account is disabled.", extra_tags='danger')
                return redirect('account:login')
        else:
            messages.add_message(request, messages.ERROR, "Your username and/or your password is incorrect.", extra_tags='warning')
            return redirect('account:login')
    else:
        if request.user.is_authenticated():
            return redirect('account:home')
        else:
            return render(request, 'autostew_web_account/login.html')
项目:django-ecom    作者:lamenezes    | 项目源码 | 文件源码
def login_view(request):
    if request.method == "GET":
        return render(request, 'carrinho/login.html', {})
    elif request.method == "POST":
        if request.user.is_authenticated():
            return redirect('/')

        nome_usuario = request.POST.get('usuario')
        senha = request.POST.get('senha')
        usuario = authenticate(username=nome_usuario, password=senha)
        if usuario is not None:
            login(request, usuario)
            return redirect('/')
        return redirect('/login/')
    else:
        raise Http404()
项目:attendance    作者:gaikwadabhishek    | 项目源码 | 文件源码
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            #user.profile.birth_date = form.cleaned_data.get('birth_date')
            user.teacher.teacher_name = form.cleaned_data.get('teacher_name')
            user.teacher.subjects = form.cleaned_data.get('subjects')
            user.refresh_from_db()
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})