예제 #1
0
    def post(self, request, *args, **kwargs):
        conferencia = self.get_conferencia()
        context = self.get_context_data(**kwargs)
        context['not_found'] = None

        form = LoginForm(request.POST)

        if form.is_valid():
            cpf = form.cleaned_data['cpf'].replace(".", "").replace("-", "")
            data_nascimento = form.cleaned_data['data_nascimento']

            try:
                inscricao = Inscricao.objects.get(
                    cpf=cpf,
                    data_nascimento=data_nascimento,
                    conferencia=conferencia)
                user = inscricao.usuario
            except:
                context['not_found'] = True
                return super().render_to_response(context)

            login(request, user)

            return redirect(
                reverse_lazy('dashboard',
                             kwargs={"conferencia": conferencia.titulo_slug}))

        return super().render_to_response(context)
예제 #2
0
파일: views.py 프로젝트: relique/crm
def login_form(request):
    success_url = reverse('events:index')
    if request.user.is_authenticated():
        return redirect(success_url)

    email = None
    if request.method == 'POST':
        email = request.POST.get('email')
        passw = request.POST.get('password')
        user = authenticate(email=email, password=passw)

        if user is not None:
            if user.is_active:
                login(request, user)
                messages.success(
                    request, "Welcome, {name}!".format(
                        name=user.get_short_name()))
                return redirect(success_url)
            else:
                trial_expired_msg = mark_safe(
                    "Your Trial has expired. Upgrade your "
                    "<a href=\"//www.onekloud.com/pricing/\">subscription "
                    "plan</a>.")
                messages.error(request, trial_expired_msg)
        else:
            messages.error(request, "Your email or password is incorrect.")

    if email is not None:
        form = LoginForm(initial=dict(email=email))
    else:
        form = LoginForm()

    return render(request, 'accounts/login_form.html', dict(form=form))
예제 #3
0
파일: views.py 프로젝트: ericpeng/pythonic
def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
    if request.method == 'GET':
        referer  = request.META.get('HTTP_REFERER','/')
        if 'accounts' or 'notice' or 'message' in str(referer):
            print 'here'
            request.session['referer'] = '/'
        else :
            request.session['referer'] = referer
        form = LoginForm()
        return render(request,'login.html',locals())
    form = LoginForm(request.POST)
    if form.is_valid():
        data = form.clean()
        # 检查email是否存在
        try:
            user = User.objects.get(username=data['email'])
        except User.DoesNotExist:
            messages.error(request,"该邮箱未注册")
            return render(request,'login.html',locals())
        user = authenticate(username=data['email'],password=data['password'])
        if user is not None:
            if user.is_active:
                auth_login(request,user)
                nextpage = request.session.get('referer','/') # 下页地址
                is_auto_login = request.POST.get('auto')
                if not is_auto_login:
                    request.session.set_expiry(0)
                return HttpResponseRedirect(nextpage)
            else:
                return HttpResponseRedirect('/accounts/active/%d/not_active/' % user.id)
        else:
            messages.error(request,'密码错误!')
    return render(request,'login.html',locals())
예제 #4
0
파일: views.py 프로젝트: peicheng/snowflake
def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
    if request.method == 'GET':
        referer  = request.META.get('HTTP_REFERER','/')
        if 'accounts' in str(referer) or 'notice' in str(referer) or 'admin' in str(referer):
            request.session['referer'] = '/'
        else :
            request.session['referer'] = referer
        form = LoginForm()
        return render(request,'login.html',locals())
    form = LoginForm(request.POST)
    if form.is_valid():
        data = form.clean()
        user = User.objects.get(username=data['email'])
        user = authenticate(username=data['email'],password=data['password'])
        #print data['password']
        #print user.check_password(data['password'])
        #if user.check_password(data['password']):
#         print user
        if user is not None:
            if user.is_active:
                auth_login(request, user)
                nextpage = request.session.get('referer','/') # 下页地址
                is_auto_login = request.POST.get('auto')
                if not is_auto_login:
                    request.session.set_expiry(0)
                return HttpResponseRedirect(nextpage)
            else:
                return HttpResponseRedirect('/accounts/active/%s/not_active' % user.get_profile().slug)
        else:
            messages.error(request,'密码不正确!')
            return render(request,'login.html',locals())
    else:
        return render(request,'login.html',{"form":form})        
예제 #5
0
    def test_invalid_password_input(self):
        '''
            tests invalid Signup were password
            has invalid size
        '''

        form = LoginForm({'username': '******', 'password': '******'}, self.my_user)
        self.assertFalse(form.is_valid())
        self.assertIn(UserFormTestData.errors['password_size']['en'],
                      form.errors['password'][0])
예제 #6
0
파일: views.py 프로젝트: tarvitz/IseeYou
def login(request):
    form = LoginForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            user = form.cleaned_data['user']
            auth.login(request, user)
            return {'redirect': 'core:index'}
    return {
        'form': form
    }
예제 #7
0
    def test_empty_data_input(self):
        '''
            tests invalid Sign Up form with
            empty fields
        '''

        form = LoginForm({'username': '', 'password': ''}, self.my_user)
        self.assertFalse(form.is_valid())
        self.assertIn(UserFormTestData.errors['null_field']['en'],
                      form.errors['username'])
        self.assertIn(UserFormTestData.errors['null_field']['en'],
                      form.errors['password'])
예제 #8
0
파일: views.py 프로젝트: pelong82/truckpro
def userLogin(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            user = authenticate(username=form.cleaned_data['username'],
                                password=form.cleaned_data['password'])
            if user is not None:
                login(request, user)
                return redirect(reverse('orders:panel_index'))
    form = LoginForm()
    context = {'form': form}
    return render(request, 'login.html', context)
예제 #9
0
    def test_valid_data_input(self):
        '''
            tests Login form with valid data
        '''

        form = LoginForm(
            {
                'username': self.my_user.username,
                'password': self.my_user.password
            }, self.my_user)
        self.assertTrue(form.is_valid())
        self.assertEqual(form.data['username'], self.my_user.username)
        self.assertEqual(form.data['password'], self.my_user.password)
예제 #10
0
def login (request):
    """
        This view handles the login and signup related stuff
        
    """ 
    loginpage = True
    
    # Create the basic forms which will be rendered in get requests
    loginform = LoginForm()
    signupform = SignUpForm()
    
    if request.user.is_authenticated(): # If user logged in : Redirect to home
        return HttpResponseRedirect(reverse('home'))
    
    # If the form has been submitted, get the form data and handle the appropriate way
    if request.method == 'POST':
        postdata = request.POST.copy()
        if 'signup' in postdata: # SIGNUP FORM
            signupform = SignUpForm(postdata)
            if signupform.is_valid():
                # If the form is valid, save the user using the inbuilt function
                try:
                    signupform.save()   
                    messages.success(request,'<strong>Hi!</strong> Your account has been made, but is not yet activated. We will review and activate your account soon !',extra_tags='alert-success')
                    return HttpResponseRedirect(reverse('home'))
                except IntegrityError: # The username (email) already exists
                    messages.error(request,'<strong>Oops!</strong> That email id has already been signed up. Try logging in !',extra_tags='alert-danger')
            else:
                print signupform.errors
        elif 'login' in postdata: # LOGIN FORM
            loginform = LoginForm(postdata)
            if loginform.is_valid():
                try:
                    user = User.objects.get(username=loginform.cleaned_data.get('username'))
                    print user
                    user = auth.authenticate(username=user.username, password=loginform.cleaned_data.get('password'))
                    
                    if user is not None and user.is_active:
                        auth.login(request, user) # Successful login
                        if 'next' in request.POST:
                            return HttpResponseRedirect(request.POST['next'])
                        else:
                            return HttpResponseRedirect(reverse('profile'))
                except User.DoesNotExist:
                    messages.error(request,'<strong>Oops!</strong> You don\'t seem to be registered. Please Sign Up first!',extra_tags='alert-error')
            else:
                print signupform.errors
        
    return render_to_response('pages/login.html', locals(), context_instance= global_context(request))
예제 #11
0
파일: views.py 프로젝트: stden/colortek
def login(request):
    form = LoginForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            user = form.cleaned_data['user']
            auth.login(request, user)
            _next = request.GET.get('next', None)
            if _next:
                return {'redirect': _next}
            if request.user.is_operator:
                return {'redirect': 'catalog:service-orders'}
            return {'redirect': 'core:index'}
    return {
        'form': form
    }
예제 #12
0
파일: views.py 프로젝트: nurlan/Testing
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username = cd.get('username'),password=cd.get('password'))
            if user:
                _login(request,user)
                next=request.REQUEST.get('next','/tests/')
                return HttpResponseRedirect(next)
            else:
                return HttpResponseRedirect(reverse('login'))
    else:
        form = LoginForm()
    rc = RequestContext(request,{'form':form})
    return render_to_response('accounts/login.html',rc)
예제 #13
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['conferencia'] = Conferencia.objects.get(
            titulo_slug=kwargs.get('conferencia'))

        form = LoginForm(self.request.POST or None)  # instance= None
        context["form"] = form
        context["redirect_to"] = self.request.GET.get("redirect_to", "None")
        context["next"] = self.request.GET.get("next", "None")

        return context
예제 #14
0
파일: views.py 프로젝트: pengyuan/snowflake
def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    if request.method == 'GET':
        referer = request.META.get('HTTP_REFERER', '/')
        if 'accounts' in str(referer) or 'notice' in str(
                referer) or 'admin' in str(referer):
            request.session['referer'] = '/'
        else:
            request.session['referer'] = referer
        form = LoginForm()
        return render(request, 'login.html', locals())
    form = LoginForm(request.POST)
    if form.is_valid():
        data = form.clean()
        user = User.objects.get(username=data['email'])
        user = authenticate(username=data['email'], password=data['password'])
        #print data['password']
        #print user.check_password(data['password'])
        #if user.check_password(data['password']):
        #         print user
        if user is not None:
            if user.is_active:
                auth_login(request, user)
                nextpage = request.session.get('referer', '/')  # 下页地址
                is_auto_login = request.POST.get('auto')
                if not is_auto_login:
                    request.session.set_expiry(0)
                return HttpResponseRedirect(nextpage)
            else:
                return HttpResponseRedirect('/accounts/active/%s/not_active' %
                                            user.get_profile().slug)
        else:
            messages.error(request, '密码不正确!')
            return render(request, 'login.html', locals())
    else:
        return render(request, 'login.html', {"form": form})
예제 #15
0
def checkout_home(request):

    print('checkout_home_1')

    cart_obj, cart_created = Cart.objects.new_or_get(request)
    order_obj = None
    if cart_created or cart_obj.products.count() == 0:
        return redirect('cart:home')
    login_form = LoginForm(request=request)
    guest_form = GuestForm(request=request)
    address_form = AddressForm()
    billing_address_id = request.session.get('billing_address_id', None)

    shipping_address_required = not cart_obj.is_digital
    shipping_address_id = request.session.get('shipping_address_id', None)

    billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(
        request)

    address_qs = None
    has_card = False
    if billing_profile is not None:

        print('checkout_home_2')

        if request.user.is_authenticated():
            address_qs = Address.objects.filter(
                billing_profile=billing_profile)

        order_obj, order_obj_created = Order.objects.new_or_get(
            billing_profile, cart_obj)

        if shipping_address_id:
            order_obj.shipping_address = Address.objects.get(
                id=shipping_address_id)
            del request.session['shipping_address_id']
        if billing_address_id:
            order_obj.billing_address = Address.objects.get(
                id=billing_address_id)
            del request.session['billing_address_id']
        if billing_address_id or shipping_address_id:
            order_obj.save()
        has_card = billing_profile.has_card

    if request.method == 'POST':

        print('checkout_home_3')

        # check that order is done
        is_prepared = order_obj.check_done()
        if is_prepared:
            is_charged, crg_msg = billing_profile.charge(order_obj)
            if is_charged:
                order_obj.mark_paid()
                request.session['cart_items'] = 0
                del request.session['cart_id']
                if not billing_profile.user:
                    billing_profile.set_cards_inactive()
                return redirect('cart:success')
            else:
                print(crg_msg)
                return redirect('cart:checkout')

    context = {
        'object': order_obj,
        'billing_profile': billing_profile,
        'login_form': login_form,
        'guest_form': guest_form,
        'address_form': address_form,
        'address_qs': address_qs,
        # 'billing_address_form': billing_address_form,
        'has_card': has_card,
        'publish_key': STRIPE_PUB_KEY,
        'shipping_address_required': shipping_address_required,
    }
    return render(request, 'carts/checkout.html', context)
예제 #16
0
def checkout_home(request):
    # Create or Grab the cart object
    print(request)
    cart_obj, cart_created = Cart.objects.new_or_get(request)
    # initalize order_obj to null
    order_obj = None
    if cart_created or cart_obj.products.count() == 0:
        return redirect('cart:home')

    # Initalize Forms
    login_form = LoginForm()
    guest_form = GuestForm()
    address_form = AddressForm()

    # Retrieve address from session
    billing_address_id = request.session.get("billing_address_id", None)
    shipping_address_id = request.session.get("shipping_address_id", None)
    # Get or Initalize a Billing Profile with current logged in or guest user
    billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)
    # Default value of ADDRESS QUERY SET
    address_qs = None

    # IF billing profile already exists
    if billing_profile is not None:
        if request.user.is_authenticated():
            # Create a query for selecting ADDRESS (shipping or billing) 
            address_qs = Address.objects.filter(billing_profile=billing_profile)
            # shipping_address_qs = address_qs.filter(address_type='shipping')
            # billing_address_qs  = address_qs.filter(address_type='billing')

        order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj)
        # IF shipping_address exists
        if shipping_address_id:
            # Associate ORDER OBJECT to shipping address
            order_obj.shipping_address = Address.objects.get(id=shipping_address_id)
            # Remove shipping_address_id from session 
            del request.session["shipping_address_id"]
        # IF billing_address exists
        if billing_address_id:
            # Associate ORDER OBJECT to billing address
            order_obj.billing_address = Address.objects.get(id=billing_address_id)
            # Remove billing_address_id from session
            del request.session["billing_address_id"]
        # IF either exist -> save()
        if billing_address_id or shipping_address_id:
            order_obj.save()

    if request.method == 'POST':
        # create variable to run method to verify ORDER contains all needed information 
        is_done = order_obj.check_done()
        if is_done:
            order_obj.mark_paid()
            # reset cart_items in session 
            request.session['cart_items'] = 0
            # remove from session 
            del request.session['cart_id']
            return redirect("cart:success")

    context = {
        "object": order_obj,
        "billing_profile" : billing_profile,
        "login_form" : login_form,
        "guest_form" : guest_form,
        "address_form" : address_form,
        "address_qs" : address_qs,
    }

    return render(request, 'carts/checkout.html', context)
예제 #17
0
def manage_login(request):
    """
    Handle s ajax request from login-dialog.
    returns a json object with a code.
    Or renders the dedicated login page if manually enterd url.
    code 
       -1 - invalid request
        0 - invalid form input
        1 - bad login credentials
        2 - subscription is not active
        3 - success
        4 - employee with no access
        5 - employee pending
        6 - invalid recaptcha response
    """
    data = {"code": -1}
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            c = login(request, request.POST.dict().copy())
            c_type = type(c)
            if c_type is int:
                if c == 0:  # bad login credentials
                    data['code'] = 1
                elif c == 1:
                    data['code'] = 2
                elif c == 2:
                    data['code'] = 4
                elif c == 3:
                    data['code'] = 5
                elif c == 4:  # recaptcha response fail
                    data['code'] = 6
            else:
                data['code'] = 3

                # manually check the next parameter
                next = request.GET.get("next")
                if not next:
                    next = reverse("store_index")
                data['redirect_url'] = next
                # user may try to login on another tab when already in
                try:
                    CometSessionIndex.objects.create(session_key=\
                        request.session.session_key,
                        store_id=request.session['store'].objectId,
                        last_updated=timezone.now())
                except IntegrityError:
                    pass

        else:
            data['code'] = 0
    else:
        if request.session.get('account'):
            return redirect(reverse('store_index'))
        data['form'] = LoginForm()
        return render(request, 'manage/login.djhtml', data)

    if data['code'] in (1, 6):
        data['display_recaptcha'] =\
            RECAPTCHA_TOKEN in request.session and request.session[\
            RECAPTCHA_TOKEN] >= RECAPTCHA_ATTEMPTS

    return HttpResponse(json.dumps(data), content_type="application/json")
예제 #18
0
def manage_login(request):
    """
    Handle s ajax request from login-dialog.
    returns a json object with a code.
    Or renders the dedicated login page if manually enterd url.
    code 
       -1 - invalid request
        0 - invalid form input
        1 - bad login credentials
        2 - subscription is not active
        3 - success
        4 - employee with no access
        5 - employee pending
        6 - invalid recaptcha response
    """
    data = {"code":-1}
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid(): 
            c = login(request, request.POST.dict().copy())
            c_type = type(c)
            if c_type is int:
                if c == 0: # bad login credentials
                    data['code'] = 1 
                elif c == 1:
                    data['code'] = 2
                elif c == 2:
                    data['code'] = 4
                elif c == 3:
                    data['code'] = 5
                elif c == 4: # recaptcha response fail
                    data['code'] = 6
            else:
                data['code'] = 3
                        
                # manually check the next parameter
                next = request.GET.get("next")
                if not next:
                    next = reverse("store_index")
                data['redirect_url'] = next
                # user may try to login on another tab when already in
                try:
                    CometSessionIndex.objects.create(session_key=\
                        request.session.session_key, 
                        store_id=request.session['store'].objectId,
                        last_updated=timezone.now())
                except IntegrityError:
                    pass
                            
        else:
            data['code'] =  0        
    else:
        if request.session.get('account'):
            return redirect(reverse('store_index'))
        data['form'] = LoginForm()
        return render(request, 'manage/login.djhtml', data)
        
    if data['code'] in (1, 6):
        data['display_recaptcha'] =\
            RECAPTCHA_TOKEN in request.session and request.session[\
            RECAPTCHA_TOKEN] >= RECAPTCHA_ATTEMPTS

    return HttpResponse(json.dumps(data), 
        content_type="application/json")