Ejemplo n.º 1
0
def login(request):
    if request.method == "POST":
        user = authenticate(username=request.POST['username'], password=request.POST['password'])
        if user is not None:
            authlogin(request, user)
            return HttpResponseRedirect(reverse('projects:index'))
    return render(request, 'projects/login.html')
Ejemplo n.º 2
0
def login(request):
    """
    ==============

    ``login``
    ----------

    .. py:function:: login(['request'])
    Authemticate users that are already registered.
       :param request: request object
       :type request: request object
    .. note::
    .. todo::
    """
    error = ''
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        error = "An unhandeled error occurred! please contant Kasra that's his fault! ;))"
        try:
            user = authenticate(request, username=username, password=password)
        except KeyError:
            error = 'Fill in all fields!'
        else:
            if user is not None:
                # user is registered
                authlogin(request, user)
                return redirect(reverse('home'))
            else:
                error = "Invalid username and/or password!"
    return render(request, 'registration/login.html', {
        'form': AuthenticationForm(),
        'error': error
    })
Ejemplo n.º 3
0
def register(request):
    controller = "users"
    method = "index"
    if request.method == 'POST':
        tipo_form = request.POST['tipo_form']
        if tipo_form == 'register':
            form = FormUserRegistration(request.POST)
            if form.is_valid():
                new_user = form.save()
                new_user.backend = 'django.contrib.auth.backends.ModelBackend'
                authlogin(request, new_user)
                return HttpResponseRedirect(reverse('core.views.listar_desejos'))
            else:
                return render(request, "system/users/index.html",
                    locals()
                )
        else:
            username = request.POST['username_login']
            password = request.POST['password_login']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    authlogin(request, user)
                    return HttpResponseRedirect(reverse('core.views.listar_desejos'))

    else:
        form = FormUserRegistration()
    return render(request, "system/users/index.html",
        locals()
    )
Ejemplo n.º 4
0
def login(request):

    if request.user.id:
        return render_to_response('logged.html',context_instance = RequestContext(request, {}))

    if request.POST:
        accountUser = request.POST.get('account')
        passwordUser = request.POST.get('password')
        u = authenticate(username = accountUser, password = passwordUser)
        if u is not None:
            if u.is_active:
                authlogin(request, u)
                
                user = User.objects.get(username = accountUser)
                user.self_decorate()
                user.save()
                
                account = BankAccountDecorator.objects.get(number = user)
                account.self_decorate()
                account.save()

                if request.POST.get('next'):
                    return HttpResponseRedirect(request.POST.get('next'))

                return render_to_response('logged.html',locals(),context_instance = RequestContext(request, {}))
        
    return render_to_response('login.html',(),context_instance = RequestContext(request, {}))
Ejemplo n.º 5
0
def login(request):

    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']

        userLoged = authenticate(username=username, password=password)

        if userLoged is not None:

            if userLoged.is_active:

                authlogin(request, userLoged)

                if Teacher.objects.filter(user=userLoged):

                    return redirect('/teacher/')

                if Student.objects.filter(user=userLoged):
                    return redirect("/student/")

                return redirect('/administrator/')

            else:
                return render(request, 'core/index.html', {'error_message': 'Seu usuário está desativado!'})
        else:
            return render(request, 'core/index.html', {'error_message': 'Login ou Senha inválidos!'})
    else:
        return redirect('core_index')
Ejemplo n.º 6
0
def login(request):

    if request.user.id:
        return render_to_response('logged.html',
                                  context_instance=RequestContext(request, {}))

    if request.POST:
        accountUser = request.POST.get('account')
        passwordUser = request.POST.get('password')
        u = authenticate(username=accountUser, password=passwordUser)
        if u is not None:
            if u.is_active:
                authlogin(request, u)

                user = User.objects.get(username=accountUser)
                user.self_decorate()
                user.save()

                account = BankAccountDecorator.objects.get(number=user)
                account.self_decorate()
                account.save()

                if request.POST.get('next'):
                    return HttpResponseRedirect(request.POST.get('next'))

                return render_to_response('logged.html',
                                          locals(),
                                          context_instance=RequestContext(
                                              request, {}))

    return render_to_response('login.html', (),
                              context_instance=RequestContext(request, {}))
Ejemplo n.º 7
0
def register(request):
    if request.method == 'POST':
        #    form = UserCreationForm(request.POST)
        #    if form.is_valid():
        #        form.save()
        #        username = form.cleaned_data.get('username')
        #        raw_password = form.cleaned_data.get('password1')
        #        user = authenticate(username=username, password=raw_password)
        #        authlogin(request, user)
        #        return redirect('index')
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            keranjang = models.Keranjang(total=0)
            keranjang.save()
            user.keranjang = keranjang
            user.save()
            form.save_m2m()

            # username = form.cleaned_data.get('username')
            email = form.cleaned_data.get('email')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=email, password=raw_password)
            authlogin(request, user)
            return redirect('index')
    else:
        #    form = UserCreationForm()
        form = SignUpForm()
        # return render(request, 'registered.html')
        return render(request, 'registration/register.html', {'form': form})
Ejemplo n.º 8
0
def login(request):
    #Note this internal class is local to the logMein namespace
    def errorHandle(error):
        form = LoginForm()
        return render_to_response('login.html', {
            'error' : error,
            'form' : form,
        })
    if request.method == 'POST': # If the form has been submitted...
        form = LoginForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    # Uses the built in 
                    authlogin(request, user)
                    return HttpResponseRedirect('searches')
                else:
                    # Return a 'disabled account' error message
                    error = u'account disabled'
                    return errorHandle(error)
            else:
                # Return an 'invalid login' error message.
                error = u'sorry, invalid login - could you try again?'
                return errorHandle(error)
        else: 
            error = u'form is invalid'
            return errorHandle(error)		
    else:
        form = LoginForm() # An unbound form
        return render_to_response('buzzlogin.html', {
            'form': form,
        })
Ejemplo n.º 9
0
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.name = form.cleaned_data.get('name')
            user.profile.emp_id = form.cleaned_data.get('emp_id')
            user.profile.circle = form.cleaned_data.get('circle')
            user.profile.designation = form.cleaned_data.get('designation')
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            authlogin(request, user)
            user.refresh_from_db()
            if (user.profile.designation == 'DCP'):
                g = Group.objects.get(name='dcp')
                g.user_set.add(user)
            if (user.profile.designation == 'ACP'):
                g = Group.objects.get(name='acp')
                g.user_set.add(user)
            if (user.profile.designation == 'INS'):
                g = Group.objects.get(name='ins')
                g.user_set.add(user)
            if (user.profile.designation == 'ARC'):
                user.is_superuser = True
                user.is_staff = True
                user.save()
                g = Group.objects.get(name='arc')
                g.user_set.add(user)
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})
Ejemplo n.º 10
0
def ajaxlogin(request):
    print("vidit")
    print(request.POST)
    success = False
    error = ''
    up = UserProfile.objects.filter(ip=get_ip(request))
    print(get_ip(request))
    try:
        t = Team.objects.get(Q(user1=up) | Q(user2=up))
        if t.user2 is None:
            error = "Your teammate hasn't registered"
            return JsonResponse({'error': error, 'success': success})
    except:
        error = "Something happened"
    if up.exists() == True:
        print("reached0")
        form = loginform(request.POST)
        print(form)
        if request.method == 'POST':
            if form.is_valid():
                formdata = form.cleaned_data
                print(formdata)
                username = formdata['id']
                password = formdata['password']
                u = User.objects.filter(username=formdata['id'])
                if u.count() > 0 and u[0] != up[0].user:
                    error = "ID registered from other pc"
                elif u.count() == 0:
                    error = "ID not registered"
                else:
                    user = authenticate(username=username, password=password)
                    if user is not None:
                        authlogin(request, user)
                        try:
                            u1 = UserProfile.objects.get(user=user)
                            t = Team.objects.filter(Q(user1=u1)
                                                    | Q(user2=u1))[0]
                            if t.time < time.mktime(
                                    datetime.now().timetuple()):
                                t.time = time.mktime(
                                    datetime.now().timetuple()) + randint(
                                        12 * 60, 17 * 60)
                                t.save()
                            success = True
                        except:
                            error = "Something went wrong"

                    else:
                        error = "Invalid Password"

            else:
                error = "Invalid ID"
            data = {'error': error, 'success': success}
            print(data)
            return JsonResponse(data)
        else:
            return JsonResponse({'error': "Something went wrong"})
    else:
        return JsonResponse({'error': "This PC is not registered"})
Ejemplo n.º 11
0
def login(request):
	error = '' 
	if request.method =='POST':
		form = UserLoginForm(request.POST)
		if (user := form.is_valid(request)):
				authlogin(request ,user)
				return HttpResponseRedirect(reverse('home:feed'))
		else : 
			error = "incorrect password or username "
Ejemplo n.º 12
0
def signup(request):
    if request.method == "POST":
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save()
            authlogin(request, user)
            return HttpResponseRedirect("/")
    else:
        form = SignupForm()
    return render(request, "signup.html", {"form": form})
Ejemplo n.º 13
0
def login(request):
    if request.method == 'GET':
        return render(request, 'writer/login.html', locals())
    username = request.data.get('username')
    password = request.data.get('password')
    user = authenticate(username=username, password=password)
    if user and user.has_perm('writable'):
        authlogin(request, user)
        return JsonResponse({'retcode': 0})
    return JsonResponse({'retcode': 1})
Ejemplo n.º 14
0
def login(request):
    if request.method == "POST":
        user = authenticate(username=request.POST["usuario"], password=request.POST["clave"])
        if user is None:
            mensaje = "Usuario y/o clave incorrecto"
            return render_to_response("polls/login.html", locals(), context_instance=RequestContext(request))
        else:
            authlogin(request, user)
            return redirect("/polls/publish/")
    else:
        return render_to_response("polls/login.html", locals(), context_instance=RequestContext(request))
Ejemplo n.º 15
0
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            u = form.save()
            url = '/'
            authlogin(request, u)
            return HttpResponseRedirect(url)
    else:
        form = SignupForm()
    return render(request, 'qa/signup.html', {'form': form})
Ejemplo n.º 16
0
    def post(self, request):
        form = AuthenticationForm(request.POST)
        if request.user.is_authenticated():
            return redirect('profile:profile', username=request.user.username)

        if form.is_valid():
            user = form.get_user()
            authlogin(request, user)
            return redirect('profile:profile', username=user.username)

        return render(request, 'user_manager/login.html', {'form': form})
Ejemplo n.º 17
0
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            authlogin(request, user)
            return HttpResponseRedirect('/')
    else:
        form = LoginForm()
    return render(request, 'qa/login.html', {'form': form})
Ejemplo n.º 18
0
def UserCreate(request):
    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid():
            new_user = User.objects.create_user(**form.cleaned_data)
            user = authenticate(username=request.POST['username'], password=request.POST['password'])
            if user is not None:
                Profile(user=user).save()
                authlogin(request, user)
                return HttpResponseRedirect(reverse('projects:index'))
    else:
        form = UserForm()
    return render(request, 'projects/user_form.html', {'form': form})
Ejemplo n.º 19
0
def login(request):

    if request.method == "POST":
        email = request.POST['email']
        password = request.POST['password']
        user = authenticate(request, username=email, password=password)
        if user is not None:
            authlogin(request, user)
            # return HttpResponse(request.user.is_authenticated)
            return redirect('about:about')
        else:
            return HttpResponse("something's off")
    return render(request, "userauth/login.html")
Ejemplo n.º 20
0
def loginpage(request):
    print(request)
    if request.method == 'POST':
        print("request.POST")
        user = authenticate(username=request.POST['username'],
                            password=request.POST['password'])
        print('USER ='******'/Home/')
    else:
        print('เขายังไม่ได้กรอก login/password (ครั้งแรกที่เข้าหน้านี้)')
    return render(request, 'Webcashier/login.html')
Ejemplo n.º 21
0
def login(request):
    if request.user.id:
        return render(request, 'agendas_rest_api/dashboard.html', {})
    if request.POST:
        usuario = request.POST.get('usuario')
        senha = request.POST.get('senha')
        u = authenticate(request, username=usuario, password=senha)

        if (u is not None):
            if (u.is_active):
                authlogin(request, u)
                return redirect('agendas_rest_api:dashboard')

    return render(request, 'agendas_rest_api/login.html', {})
Ejemplo n.º 22
0
def login(request):
    username = request.POST['username']
    pw = request.POST['password']
    usuario = authenticate(username=username, password=pw)
    if usuario is not None:
        authlogin(request=request, user=usuario)
        # Redirect to a success page.
        print('ok')
        return redirect('home')
    else:
        # Return an 'invalid login' error message.
        form = AuthenticationForm(request.POST or None)
        print('not ok')
        return render(request, 'index.html', {'form': form, 'erro': True})
Ejemplo n.º 23
0
def login(request):
    if request.user.id:
        return render(request, 'gestorbases/logado.html', {})
    if request.POST:
        usuario = request.POST.get('usuario')
        senha = request.POST.get('senha')
        u = authenticate(request, username=usuario, password=senha)

        if (u is not None):
            if (u.is_active):
                authlogin(request, u)
                return redirect('gestorbases:dashboard')
                #return render(request, 'gestorbases/dashboard.html',{'user': u})
    return render(request, 'gestorbases/login.html', {})
Ejemplo n.º 24
0
def checkLogin (request):
    form = LoginForm(request.POST)
    if request.method == 'POST' :
        uname = request.POST.get('username')
        passwd = request.POST.get('password')
        user = authenticate(username=uname,password=passwd)
        if user is not None:
            authlogin(request,user)
            return render(request,"books/index.html")
        else :
            regForm = RegistrationForm()
            return render(request,'books/index.html',{'rform':regForm, 'lform':form, 'error':'Either Usernme or Password is not correct'})
    else:
        return redirect('books:register')
Ejemplo n.º 25
0
def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = auth(username=username, password=password)
        if user is not None:
            if user.is_active:
                authlogin(request, user)
                return render_to_response('users/login/success.html', context_instance = RequestContext(request))
            else:
                return render_to_response('users/login/disabled.html', context_instance = RequestContext(request))
        else:
            return render_to_response('users/login/invalid.html', context_instance = RequestContext(request))
    return render_to_response('users/login/login.html', context_instance = RequestContext(request))
Ejemplo n.º 26
0
def signin(request):
    if request.method == "POST":
        form = SigninForm(request.POST)
        if form.is_valid():
            form.save()
            newUser=authenticate(username=form.cleaned_data["username"],
                                 password=form.cleaned_data["password1"])
            authlogin(request, newUser)
            return HttpResponseRedirect("/")
    else :
        form  = SigninForm()
    data={
        "form":form,
    }
    return render(request,"blog/mobile/registration/signin.html",data)
Ejemplo n.º 27
0
def login(request):
    if request.method != 'POST':
        return HttpResponseForbidden('Methond not supported')

    args = json.loads(request.body.decode())
    username = args['username']
    password = args['password']

    user = authenticate(username=username, password=password)
    if user is None:
        return HttpResponseForbidden('Authentication failed')

    authlogin(request, user)
    refreshSession(request)
    return HttpResponse("success")
Ejemplo n.º 28
0
def login(request):
    try:
        logout(request)
    except:
        pass
    if request.method == "POST":
        body = json.loads(request.body.decode('utf-8'))
        username = body.get('username')
        password = body.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            authlogin(request, user)
            if user.is_active:
                return HttpResponse('{"value":"yes"}',
                                    content_type="application/json")
    return HttpResponse('{"value":"no"}', content_type="application/json")
Ejemplo n.º 29
0
def register(request):
    if request.method == 'POST':

        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            authlogin(request, user)
            return redirect('home')
    else:

        form = UserCreationForm()
    context = {'form': form}
    return render(request, 'registration/register.html', context)
Ejemplo n.º 30
0
def signin(request):
	#TODO : show error messages
	if request.method == 'POST' :
		form = UserForm(request.POST)
		if form.is_valid():
			username = form.cleaned_data['username'] 
			password = form.cleaned_data['password1']
			user = User(username = username , password = password)
			user.save()
			profile = ProfileModel(user = user)
			profile.save()
			authlogin(request , user) 
			return HttpResponseRedirect(reverse('home:feed'))
	else : 
		form = UserForm()
	return render(request , 'user/signin.html' , {'form' : form})
Ejemplo n.º 31
0
def handleLogin(request):
    if request.method == 'POST':
        loginusername = request.POST['loginusername']
        loginpassword = request.POST['loginpassword']

        user = authenticate(request,
                            username=loginusername,
                            password=loginpassword)
        if user is not None:
            authlogin(request, user)
            messages.success(request, "you are successfully logged in")
            return redirect('home')
        else:
            messages.error(request, "invalid credentials")
            return redirect('login')

    return HttpResponse("logeed in")
Ejemplo n.º 32
0
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            conta = authenticate(username=form.cleaned_data['login'],
                                 password=form.cleaned_data['senha'])     
            authlogin(request, conta)
            return redireciona_usuario(request)
        else:
            return render_to_response("login_erro.html",
                              {'form' : form},
                              context_instance=RequestContext(request))
            
    else:
        form = LoginForm()
    return render_to_response("login.html",
                              {'form' : form},
                              context_instance=RequestContext(request))
Ejemplo n.º 33
0
def login_view(request):

    if request.method == 'POST':

        user = auth(request, 
        username=request.POST.get('username'),
        password=request.POST.get('password'))

        if user is not None:
            authlogin(request, user)
            return redirect('system:home')
        else:
            return HttpResponse('You have failed to login.')
    elif request.method == 'GET':
        if request.user.is_authenticated:
            return redirect('system:home')

    return render(request, 'login.html')
Ejemplo n.º 34
0
def validacao(request):
    if request.user.id:
        return render(request, 'index.html')

    if request.POST:
        emailUser = request.POST.get('email')
        senhaUser = request.POST.get('senha')

        u = authenticate(username=emailUser, password=senhaUser)
        if u is not None:
            if u.is_active:
                authlogin(request, u)

                if request.POST.get('next'):
                    return HttpResponseRedirect(request.POST.get('next'))

                return index(request)
    return login(request)
Ejemplo n.º 35
0
def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = LoginForm(request.REQUEST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']

            try:
                userr = User.objects.get(email=email)
                userauth = authenticate(email=email, password=password)
                if userauth is not None :  #caso login valido
                    authlogin(request, userauth)
                    return HttpResponseRedirect('/')
                else:  #login nao valido
                    msg = gettext("The login and/or password you specified are not correct.")
                    context = {'form': form, 'erros': msg}
                    return render_to_response('account/signup_univ.html', context, context_instance=RequestContext(request))

            except User.DoesNotExist:  # email ainda nao existe, cria
                user = get_adapter().populate_new_user(email=email)
            user.has_usable_password()
            user.set_password(password)
            account = SocialAccount(uid=email,
                                    provider=UniversityProvider.id,
                                    user=user,
                                    extra_data='{"university":"%s"}' % email.split('@')[1])
            login = SocialLogin(account)
            #login.state = SocialLogin.unmarshall_state(request.REQUEST.get('state'))

            u = login.account.user
            u.has_usable_password()
            u.set_password(password)
            login.account.user = u
            ret = complete_social_login(request, login)
            return ret
        else:
            context = {'form': form}
            return render_to_response('account/signup_univ.html',context, context_instance=RequestContext(request))
    else:
        form = LoginForm()
        context = {'form': form}
        return render_to_response('account/signup_univ.html',context, context_instance=RequestContext(request))
Ejemplo n.º 36
0
def finalizar_cadastro(request):
    try:
        conta = request.session['conta']
        usuario = request.session['usuario_cadastro']
    except KeyError:
        return HttpResponseRedirect("/cadastro/")
    dados = template_data(request)
    if request.method == 'POST':
        form = EnderecoForm(request.POST, auto_id=False, error_class=DivErrorList)
        if form.is_valid():
            conta.is_active = True
            conta.save()
            usuario.conta = conta
            usuario.save()
            endereco = EnderecoUsuario(logradouro=form.cleaned_data['logradouro'],
                                       numero=form.cleaned_data['numero'],
                                       complemento=form.cleaned_data['complemento'],
                                       bairro=form.cleaned_data['bairro'],
                                       cep=form.cleaned_data['cep'],
                                       cidade=form.cleaned_data['cidade'],
                                       estado=form.cleaned_data['estado'],
                                       referencia=form.cleaned_data['referencia'],
                                       usuario=usuario)
            endereco.save()
#            from django.core.mail import EmailMessage
#            email = EmailMessage("Obrigado por se cadastrar no Preguiça Delivery",
#                                 mensagem_email % usuario.chave_de_ativacao,
#                                 to=[usuario.conta.email])
#            email.send()
            del request.session['conta']
            del request.session['usuario_cadastro']
            conta_logada = authenticate(username=conta.username,
                                        password=request.session['pass'])
            authlogin(request, conta_logada)
            del request.session['pass']
            return painel(request)
        else:
            dados['form'] = form
            return render_to_response('finalizar_cadastro.html', dados,
                              context_instance=RequestContext(request))
    else:
        form = EnderecoForm()
        dados['form'] = form
    return render_to_response('finalizar_cadastro.html', dados, context_instance=RequestContext(request))
Ejemplo n.º 37
0
def login(request):

    if request.user.id:
        return render_to_response("siteT/login.html", (), context_instance=RequestContext(request, ()))

    if request.POST:
        name_user = request.POST.get("name_user")
        senha = request.POST.get("senha")
        u = authenticate(username=name_user, password=senha)
        if u is not None:
            if u.is_active:
                authlogin(request, u)

                if request.POST.get("next"):
                    return HttpResponseRedirect(request.POST.get("next"))

                return render_to_response("siteT/logado.html", (), context_instance=RequestContext(request, ()))

    return render_to_response("siteT/login.html", (), context_instance=RequestContext(request, ()))
Ejemplo n.º 38
0
def login(request):
    if request.user.is_authenticated:
        #If user logged in, redirect to home page
        return HttpResponseRedirect('/')
    else:
        if request.method == 'POST':
            form = loginform(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                username1 = cd['username']
                password1 = cd['password']
                user = authenticate(username=username1, password=password1)
                #Login credentials verification
                if user is not None:
                    authlogin(request, user)
                    #if next page is mentioned
                    url = re.compile(r'next=/(\w+)')
                    temp = url.search(request.get_full_path())
                    if temp is None:
                        return HttpResponseRedirect('/')
                    else:
                        return HttpResponseRedirect('/' + temp.group(1) + '/')
                else:
                    #error if username/password incorrect
                    form.add_error('username', 'Incorrect login credentials')
                    return render(request, 'login.html', {'form': form})
        else:
            form = loginform()
            url = re.compile(r'next=/(\w+)')
            temp = url.search(request.get_full_path())

            if temp is None:
                status = ''
            elif temp.group(1) == 'pr' or temp.group(1) == 'signup':
                status = 'Only admin can access this'
            else:
                status = 'You need to sign in to view that page'
            return render(request, 'login.html', {
                'form': form,
                'status': status
            })
        return render(request, 'login.html', {'form': form})
Ejemplo n.º 39
0
def login(request, *args, **kwargs):

    next = ""
    if request.method == "GET":
        login_form = LoginForm(None)
        next = request.GET.get("next", "/")

    elif request.method == "POST":
        login_form = LoginForm(request.POST)
        next = request.POST.get("next", "/")
        if login_form.is_valid():
            user = login_form.login(request)
            if user:
                authlogin(request, user)
                return HttpResponseRedirect(next)

    return render(request, 'contents/user/login.html', {
        'login_form': login_form,
        'next': next
    })
Ejemplo n.º 40
0
def login(request):
    if request.method == "POST":
        from django.contrib.auth import authenticate

        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            passw = form.cleaned_data["password"]
            u = authenticate(username=username, password=passw)
            if u is not None:
                authlogin(request, u)
                return HttpResponseRedirect("/upload")
            else:
                return HttpResponseRedirect("/")
        else:
            return HttpResponseRedirect("/")
    elif request.method == "GET":
        form = LoginForm()
        template = "login.html"
        return render_to_response(template, {"form": form}, context_instance=RequestContext(request))
Ejemplo n.º 41
0
def Login(request):
    if request.method == 'POST':
        msg = {}
        username = request.POST['username']
        psw = request.POST['password']
        if username and psw:
            user = authenticate(username=username, password=psw)
            if user is not None:
                if user.is_active:
                    authlogin(request, user)
                    return HttpResponseRedirect('/')
                else:
                    msg['error'] = 'Cuenta inhabilitada'
                    return HttpResponseRedirect('/')
            else:
                msg['error'] = 'Datos incorrectos'
                return HttpResponseRedirect('/')
        else:
            HttpResponseRedirect('/')
    return render(request, 'index.html')
Ejemplo n.º 42
0
def ativar_usuario(request, chave):
    if request.user.is_authenticated():
        return HttpResponseRedirect("/")
    try:
        usuario = Usuario.objects.get(chave_de_ativacao=chave)
    except Usuario.DoesNotExist:
        return HttpResponseRedirect("/")
    if usuario.conta.is_active:
        return HttpResponseRedirect("/")
    if usuario.expiracao_chave < datetime.datetime.today():
        return HttpResponse("expirou!")
    conta = usuario.conta
    conta.is_active = True
    conta.save()
    usuario.chave_de_ativacao = ""
    usuario.save()
    conta = authenticate(username=conta.username,
                         password=conta.password)
    authlogin(request, conta)
    return HttpResponseRedirect("/adicionar_endereco")
Ejemplo n.º 43
0
def login(request):
    if request.method == 'POST':
        purpose = request.POST.get('purpose',None)
        if purpose == 'login':
            username = request.POST.get('username',None)
            password = request.POST.get('pd',None)
            count = User.objects.filter(username=username).count()
            if count == 0:
                messages.error(request,'用户不存在!')#在请求信息中加入messages消息内容,下次请求时会被提取并清除(基于会话)
                return HttpResponse(render(request, APP_TEMPLETE_ROOT+'login.html'))
            user = authenticate(username=username, password=password)#在后台认证此用户
            if user is None:
                messages.error(request,'登录失败!')#在请求信息中加入messages消息内容,下次请求时会被提取并清除(基于会话)
                return HttpResponse(render(request, APP_TEMPLETE_ROOT+'login.html'))
            authlogin(request, user)#登录,将在session中保持登录状态
            return HttpResponseRedirect(reverse('index'))
        elif purpose == 'logout':
            authlogout(request)
            return JsonResponse({"status":"logout"})
    else:
        return HttpResponse(render(request, APP_TEMPLETE_ROOT+'login.html'))
Ejemplo n.º 44
0
def login(request):
    if request.method == "GET":
        pass
    elif request.method == "POST":
        username = request.POST.get('Id')
        password = request.POST.get('Password')
        remember = request.POST.get('remember')
        user = authenticate(username=username, password=password)
        if user is not None:
            authlogin(request, user)
            # return HttpResponseRedirect("/")
            next_value = request.GET.get("next")
            if next_value:
                return redirect(next_value)
            else:
                return redirect("/")
        else:
            messages.info(request, "user not exists!")
            return redirect("/client/login")
    ctx = {}
    return render(request, "login.html", ctx)
Ejemplo n.º 45
0
  def post(self, request):
    form = self.formclass(request.POST)

    if form.is_valid():
      user = form.save(commit=False)

      #cleaning the data(nomalize)
      username =  form.cleaned_data['username']
      password =  form.cleaned_data['password']
      user.set_password(password)
      user.save()

      #return user object if authentication is success
      user = authenticate(username=username, password=password)

      if user is not None:
        if user.is_active:
          authlogin(request, user)
          return redirect('/')
   
    return render(request, self.templatename, {'form': form})
Ejemplo n.º 46
0
def auth_and_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                authlogin(request,user)
                user_id = User.objects.get(username= username).id
                request.session['user_id'] = user_id
                output_ticket = Ticket.objects.filter(created_by = request.user)
                context = {
                    'username': username,
                    'user_id': user_id,
                    'output_ticket': output_ticket
                }
                return render_to_response('tickets/user_view.html', context)
            else:
                error = "Account Disabled"
                return errorHandler(error)
        else:
            error = "Invalid username password combination"
            return errorHandler(error)
Ejemplo n.º 47
0
def login(request):
  if request.method == 'POST':
    print request.POST
    name = request.POST[u'username']
    word = request.POST[u'password']
    user = authenticate(username=name, password=word)

    if user is not None:
      if user.is_active:
        authlogin(request, user)
        return redirect('/account/')
    else:
      return render_to_response('templates/account/login.html', 
                             Context({"error": "invalid login"}),
                             context_instance=RequestContext(request))

  else:
    if not request.user.is_authenticated():
      print "not authenticated?"
      return render_to_response('templates/account/login.html', 
                             context_instance=RequestContext(request))

    else:
      return redirect('/account')