Exemplo n.º 1
0
    def post(self, *args, **kwargs):
        username = self.request.POST.get('username')
        password = self.request.POST.get('password')

        if not username or not password:
            messages.error(self.request, 'Usuário ou senha inválidos.')
            return redirect('perfil:criar')

        autenticacao = authenticate(self.request,
                                    username=username,
                                    password=password)

        if not autenticacao:
            messages.error(
                self.request,
                'Usuário não existe. Gentileza realizar o cadastro.')
            return redirect('perfil:criar')

        login(self.request, user=autenticacao)

        messages.success(
            self.request,
            f'Login efetuado com sucesso. Olá, {self.request.user.first_name}!'
        )
        if not self.request.session.get('cart'):

            return redirect('produto:lista')

        return redirect('produto:cart')
Exemplo n.º 2
0
def admin_profile_save(request):
    if request.method == "POST":
        first_name = request.POST.get("first_name")
        last_name = request.POST.get("last_name")
        # profile_pic = request.FILES.get("profile_pic")
        try:
            customuser = CustomUser.objects.get(id=request.user.id)
            customuser.first_name = first_name
            customuser.last_name = last_name
            # if password!=None and password!="":
            #     customuser.set_password(password)
            customuser.save()
            admin_user = AdminUser.objects.get(auth_user_id=request.user.id)

            fs = FileSystemStorage()
            filename = fs.save(profile_pic.name, profile_pic)
            profile_pic_url = fs.url(filename)
            admin_user.profile_pic = profile_pic_url
            admin_user.save()
            messages.success(request, "Successfully Updated Profile")
            return HttpResponseRedirect(reverse("admin_profile"))
        except:
            messages.error(request, "Failed to Update Profile")
            return HttpResponseRedirect(reverse("admin_profile"))
    return HttpResponseRedirect(reverse("admin_profile"))
Exemplo n.º 3
0
 def post(self, request):
     form = RegistrationForm(request.POST)
     if form.is_valid():
         form.save()
     else:
         messages.error(request, 'Registration fail..')
         return render(request, 'accounts/registrations.html',
                       {'form': form})
     messages.info(request, 'Registration successfully..')
     return redirect('accounts:login')
Exemplo n.º 4
0
 def post(self,request):
     form1=LoginForm(data=request.POST)
     if form1.is_valid():
         contact=form1.cleaned_data.get('contact')
         password=form1.cleaned_data.get('password')
         user=authenticate(contact=contact,password=password)
         if user is not None: 
             login(request,user)
             # print(request.user)
             return redirect ('bookcleaning:profile',pk=user.id)
         else:
             messages.error(request,'User Not Found please Enter Valid data'+str(form1.errors))
     return render(request,'login.html',{'form':form1})
Exemplo n.º 5
0
 def post(self, request):
     form1 = LoginForm(data=request.POST)
     print(form1.is_valid())
     if form1.is_valid():
         phone = form1.cleaned_data.get('phone')
         password = form1.cleaned_data.get('password')
         user = authenticate(phone=phone, password=password)
         if user is not None:
             login(request, user)
             return redirect('home')
         else:
             messages.error(
                 request, 'User Does Not Exists Please Enter Valid Data' +
                 str(form1.errors))
     return render(request, 'accounts/login.html', {'form': form1})
Exemplo n.º 6
0
 def post(self, request):
     form1 = LoginForm(request.POST)
     if form1.is_valid():
         username = form1.cleaned_data['username']
         password = form1.cleaned_data['password']
         mobile = form1.cleaned_data['phonenumber']
         user = authenticate(username=username, password=password)
         if user is not None:
             if ProfileModel.objects.filter(phonenumber=mobile).exists():
                 login(request, user)
                 return redirect('registration')
             else:
                 messages.error(request, 'Mobile Number Not Found')
         else:
             messages.error(request,
                            'User Not Found please Enter Valid data')
     return render(request, 'cleaning/login.html', {'form': form1})
Exemplo n.º 7
0
 def post(self, request):
     form = LoginForm(data=request.POST)
     if form.is_valid():
         email = form.cleaned_data.get('email')
         password = form.cleaned_data.get('password')
         user = authenticate(email=email, password=password)
         if user is not None:
             if user.is_staff:
                 login(request, user)
                 return redirect('book:approval')
             login(request, user)
             return redirect('book:booksearch')
         else:
             messages.error(
                 request, 'User Not Found please Enter Valid data' +
                 str(form.errors))
     return render(request, 'accounts/login.html', {'form': form})
Exemplo n.º 8
0
 def clean(self):
     data = self.cleaned_data
     email = data.get('email')
     password = data.get('password')
     qs = User.objects.filter(email=email)
     if qs.exists():
         not_active = qs.filter(is_active=False)
         if not_active.exists():
             msg = messages.error(self.request, "This user is not active!")
             raise forms.ValidationError(msg)
     user = authenticate(self.request, email=email, password=password)
     if user is None:
         msg = messages.error(self.request, "Invalid credentials.")
         raise forms.ValidationError(msg)
     login(self.request, user)
     user_logged_in.send(user.__class__,
                         instance=user,
                         request=self.request)
     return data
Exemplo n.º 9
0
 def clean(self):
     data = self.cleaned_data
     email = data.get('email')
     password = data.get('password')
     qs = User.objects.filter(email=email)
     if qs.exists():
         user = authenticate(self.request, email=email, password=password)
         if user is None:
             msg = messages.error(self.request, "Invalid credentials.")
             raise forms.ValidationError(msg)
         login(self.request, user)
         return data
Exemplo n.º 10
0
    def form_valid(self, form):
        """ Begin reCAPTCHA validation """
        recaptcha_response = self.request.POST.get('g-recaptcha-response')
        url = 'https://www.google.com/recaptcha/api/siteverify'
        values = {
            'secret': os.environ.get('CAPTCHA_SECRET'),
            'response': recaptcha_response
        }
        data = urllib.parse.urlencode(values).encode()
        req = urllib.request.Request(url, data=data)
        response = urllib.request.urlopen(req)
        result = json.loads(response.read().decode())
        """ End reCAPTCHA validation """
        if result['success']:
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(self.request)
            mail_subject = f'Activate your account at {current_site.name}.'
            message = render_to_string('blog/acc_activate_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(
                mail_subject, message, to=[to_email]
            )
            email.send()
            messages.success(self.request, message='Please confirm your email address to complete the registration!')

            # user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password1'], )
            # login(self.request, user, backend='django.contrib.auth.backends.ModelBackend')
            return HttpResponseRedirect(reverse('login'))
        else:
            messages.error(self.request, 'Invalid reCAPTCHA. Please try again.')
            return HttpResponseRedirect(reverse('signup'))
Exemplo n.º 11
0
 def clean(self):
     data = self.cleaned_data
     email = data.get('email')
     password = data.get('password')
     qs = User.objects.filter(email=email)
     if qs.exists():
         # user email is registered, check email is active or email activation
         not_active = qs.filter(is_active=False)
         if not_active.exists():
             # check email activation
             confirm_email = EmailActivation.objects.filter(email=email)
             is_conformable = confirm_email.conformable().exists()
             if is_conformable:
                 msg = messages.info(
                     self.request,
                     "Please check your email and confirm activation.")
                 raise forms.ValidationError(msg)
             email_confirm_exists = EmailActivation.objects.email_exists(
                 email).exists()
             if email_confirm_exists:
                 msg = messages.info(
                     self.request, "Please resend your conformation email.")
                 raise forms.ValidationError(msg)
             if not is_conformable and not email_confirm_exists:
                 msg = messages.error(self.request,
                                      "This user is not active!")
                 raise forms.ValidationError(msg)
     user = authenticate(self.request, email=email, password=password)
     if user is None:
         msg = messages.error(self.request, "Invalid credentials.")
         raise forms.ValidationError(msg)
     login(self.request, user)
     self.user = user
     user_logged_in.send(user.__class__,
                         instance=user,
                         request=self.request)
     return data
Exemplo n.º 12
0
    def post(self, *args, **kwargs):

        http_referer = self.request.META.get('HTTP_REFERER',
                                             reverse('produto:lista'))

        if not self.userform.is_valid() or not self.perfilform.is_valid():
            messages.error(
                self.request,
                'Existem erros no formulário de cadastro. Verifique se os campos foram preenchidos corretamente.'
            )
            return self.renderizar

        username = self.userform.cleaned_data.get('username')
        password = self.userform.cleaned_data.get('password')
        email = self.userform.cleaned_data.get('email')
        first_name = self.userform.cleaned_data.get('first_name')
        last_name = self.userform.cleaned_data.get('last_name')

        # Usuário logado: atualização
        if self.request.user.is_authenticated:
            usuario = get_object_or_404(User,
                                        username=self.request.user.username)
            usuario.username = username

            if password:
                usuario.set_password(password)

            usuario.email = email
            usuario.first_name = first_name
            usuario.last_name = last_name
            usuario.save()

            messages.success(self.request, 'Usuário atualizado com sucesso.')

            if not self.perfil:
                self.perfilform.cleaned_data['usuario'] = usuario
                print(self.perfilform.cleaned_data)
                perfil = models.Perfil(**self.perfilform.cleaned_data)
                perfil.save()
            else:
                perfil = self.perfilform.save(commit=False)
                perfil.usuario = usuario
                perfil.save()

        # Usuário não logado (novo):
        else:
            usuario = self.userform.save(commit=False)
            usuario.set_password(password)
            usuario.save()

            perfil = self.perfilform.save(commit=False)
            perfil.usuario = usuario
            perfil.save()

            messages.success(self.request,
                             f'O usuário {usuario} foi criado com sucesso.')

        if password:
            autenticacao = authenticate(
                self.request,
                username=usuario,
                password=password,
            )
            if autenticacao:
                login(self.request, user=usuario)

        self.request.session['cart'] = self.carrinho
        self.request.session.save()
        if not self.request.session.get('cart'):
            return redirect('produto:lista')

        return redirect('produto:cart')