Ejemplo n.º 1
0
def get_user(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            uname = request.POST.get('username')
            passw = request.POST.get('password')
            login_attempt = LoginAttempt(username=uname)
            user = authenticate(username=uname, password=passw)
            if user.groups.all().count() == 0:
                login(request, user)
                login_attempt.success = True
                login_attempt.save()
                return HttpResponseRedirect(reverse('admin:index'))
            if user is not None:
                login(request, user)
                login_attempt.success = True
                login_attempt.save()
                redir_path = user.employee.department.lower()
                return HttpResponseRedirect("../" + redir_path)
            else:
                login_attempt.success = False
                login_attempt.save()
                variables = {
                    'form': form,
                    'error_text': 'Invalid username or password'
                }
                return render(request, 'login/index.html', variables)

    else:
        form = LoginForm()
    return render(request, 'login/index.html', {'form': form})
Ejemplo n.º 2
0
def handle_login(request):
    if not request.method == 'POST':
        return HttpResponse('fail')
    resp = dict()
    form = LoginForm(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:
            login(request, user)
            resp['status'] = 'LOGGED_IN'
        else:
            if len(User.objects.filter(username=username)) > 0:
                resp['status'] = 'BAD_PASS'
            else:
                user = User.objects.create_user(username, '', password)
                user_authed = authenticate(username=username, password=password)
                login(request, user_authed)
                resp['status'] = 'NEW_USER'
    else:
        resp['status'] = 'FORM_ERROR'
        form_errors = dict()
        for key, val in form.errors.items():
            form_errors[key] = str(val.as_text())
        resp['errors'] = form_errors
    return HttpResponse(simplejson.dumps(resp))
Ejemplo n.º 3
0
def login_view(request):
    # if user is already logged in go to home page
    if request.user.is_authenticated():
        return redirect("home_url")

    # if method is GET render login page else authenticate user
    if request.method == "GET":
        loginform = LoginForm()
        return render(request, 'home.html', {'loginform': loginform})

    if request.method == 'POST':
        form = LoginForm(request.POST)
        # check if the fields are valid
        if form.is_valid():
            name = form.cleaned_data['username']
            pwd = form.cleaned_data['password']
            # authenticates user return None if doesn't exist
            if not UserLogin.objects.filter(username=name):
                return render(request, 'login.html', {'msg': "此用户不存在"})
            else:
                pwd = hash_code(pwd)
                if not UserLogin.objects.filter(password=pwd):
                    return render(request, 'login.html', {'msg': "密码错误!"})
                else:
                    user = authenticate(username=name, password=pwd)
                    login(request, user)
                    return render(request, 'home.html')

        else:
            return render(request, 'login.html', {'msg': "填写格式出错!"})
Ejemplo n.º 4
0
def login_validate(request):

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

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

            if user:
                all_user = UserImage.objects.filter(
                    username=form.cleaned_data['username'])
                image_link = ''
                for i in all_user:
                    image_link += str(i.contest_photo)
                likes = LikedPhotos.objects.filter(image_link=image_link)
                login(request, user)
                return render(request, 'home_page.html', {
                    'image_link': image_link,
                    'number_of_likes': likes.count()
                })
            else:
                messages.info(request, 'Register Yourself')
                return redirect('/register_user/')
        else:
            return render(request, 'login.html', {'form': form})
    else:
        return render(request, 'user.html', {'username': '******'})
Ejemplo n.º 5
0
 def test_TC_Login_001_fail3(self):
     # test for invalid field input, password and username left blank case
     invalid_data = {"username": None, "password": None}
     form = LoginForm(data=invalid_data)
     self.assertFalse(form.is_valid(),
                      "Username and Password field is empty")
     self.assertEqual(form.errors['username'], ["This field is required."])
Ejemplo n.º 6
0
def login():
    if session.get('username'):
        return redirect(url_for('home'))

    form = LoginForm()
    if request.method == 'GET':

        return render_template('login.html', form=form)

    if request.method == 'POST':
        email = form.email.data.strip()
        password = form.password.data.strip()

        if form.validate_on_submit():
            qs = User.select().where(User.email == email)
            if len(qs) > 0:
                qs = qs[0]
                if qs.password == password:

                    session['username'] = qs.fname
                    session['id'] = qs.id
                    session.permanent = True
                    return redirect(url_for('home'))

            return render_template('login.html',
                                   form=form,
                                   error="Wrong password or email")
        print(form.errors)
        return render_template('login.html',
                               form=form,
                               error="Wrong password or email")
Ejemplo n.º 7
0
def Login(request):
    error = ''
    access_token = ''
    if_logout = ''
    if request.method == 'POST':
        if request.user.is_authenticated:
            if 'logout' in request.POST:
                Logout(request)
            else:
                error = Get_Image(request)
                return render(request, 'login.html', {'error': error})

        else:
            form = LoginForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                try:
                    access_token = get_access_token(cd['username'],
                                                    cd['password'])
                    data = get_user_info(access_token)
                    user = check_user(data)
                    login(request, user)
                except Exception:
                    error = '登录申请失败!请确认用户名与密码是否正确,以及学号与姓名信息是否完整!'
    else:
        form = LoginForm()  #首次登陆,GET请求
    return render(request, 'login.html', {'error': error})
Ejemplo n.º 8
0
def login_view(request):
    def errorHandle(error):
        form = LoginForm()
        return render_to_response('login.html', {
            'error' : error,
            'form' : form,
            }, context_instance=RequestContext(request))
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)

                    return HttpResponseRedirect('/')

                else:
                    error = 'Account disabled!'
                    return errorHandle(error)
            else:
                error = 'Wrong username/password!'
                return errorHandle(error)
        else:
            error = 'Invalid input!'
            return errorHandle(error)
    else:
        form = LoginForm()
        return render_to_response('login.html', {
            'form' : form,
            }, context_instance=RequestContext(request))
Ejemplo n.º 9
0
 def test_login_con_campos_validos(self):
     crear_usuario(self)
     form = LoginForm(data={
         'username': '******',
         'password': '******',
     })
     self.assertTrue(form.is_valid())
Ejemplo n.º 10
0
def login(request):
    if request.session.get('is_login', None):
        return redirect(reverse('user:index'))
    if request.method == 'POST':
        form = LoginForm(request.POST)
        message = "所有字段都必须填写"
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            try:
                user = User.objects.get(name=username)
                if not user.has_confrimed:
                    message = '该用户还未通过邮件确认!'
                    return render(request, 'login/login.html', locals())
                if user.password == hash_code(password):
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.name
                    return redirect(reverse('user:index'))
                else:
                    message = "password error"
            except:
                message = "user is no exit"
        return render(request, 'login/login.html', locals())
    form = LoginForm()
    return render(request, 'login/login.html', locals())
Ejemplo n.º 11
0
def login(request):   #登录页面
    if request.method == "POST":
        #表单验证
        form = LoginForm(request.POST)
        if form.is_valid(): #验证成功
        #接收数据
            phone = request.POST.get("mobile")
            password = request.POST.get("password")
            pwd = hashlib.md5(password.encode("utf-8"))
            #处理数据
            try:
                user = Users.objects.get(phone=phone)
            except Users.DoesNotExist:  #结果不存在错误
                return redirect("login:登录界面")
            except Users.MultipleObjectsReturned: #多个结果错误
                return redirect("login:登录界面")
            if user.pwd == pwd.hexdigest(): #判断密码
                return redirect("login:个人中心界面")
            else:
                return redirect("login:登录界面")
            #返回结果
        else:   #验证失败
            context = {
                "errors": form.errors,
                "data": form
            }
            return render(request, "login/login.html", context)
    else:
        return render(request, "login/login.html")
Ejemplo n.º 12
0
def login(request):
    user = request.user
    if user.is_active:
        return HttpResponseRedirect('/')

    if request.method == 'POST':
        form = LoginForm(request.POST)

        if form.is_valid():
            login_form = form.cleaned_data['login']
            password_form = form.cleaned_data['senha']

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

            if user is not None:
                auth_login(request, user)
                messages.success(request, 'Logged succefully!')
                return HttpResponseRedirect('/consumptions')
            else:
                messages.error(request, 'Invalid user or password!')
    else:
        form = LoginForm()

    context_dict = {'title': 'Klee', 'form': form}

    return render(request, 'login/login.pug', context=context_dict)
Ejemplo n.º 13
0
def login(request):
    error_message = ""
    if not request.user.is_authenticated:
        if request.method == "POST":
            # Añadimos los datos recibidos al formulario
            form = LoginForm(request.POST)
            # Si el formulario es válido...
            if form.is_valid():
                # Recuperamos las credenciales validadas
                usuario = form.cleaned_data['nombre_usuario']
                contrasena = form.cleaned_data['contrasena']

                # Verificamos las credenciales del usuario
                user = authenticate(request=request, username=usuario, password=contrasena)
                # Si existe un usuario con ese nombre y contraseña
                error = get_error_login(request)
                if error == 1:
                    error_message = "Usuario y/o contraseña incorrectos"
                elif error == 2:
                    error_message = "No tiene permiso para entrar a este portal"
                elif error == 3:
                    error_message = "Su usuario se encuentra desactivado en el momento"
                elif user is not None:
                    # Hacemos el login manualmente
                    do_login(request, user)
                    # Y le redireccionamos a la portada
                    return redirect('board')
    else:
        return redirect('board')
    args = {'title': 'Inicio de Sesion', 'error_message':error_message}
    return render(request, "login/login.html", args)
Ejemplo n.º 14
0
def login(request):
    # form=LoginForm()
    if 'UserName' in request.session:
        return render(request, 'login/login.html',
                      {"UserName": request.session.get("UserName")})
    else:
        if request.method == "POST":
            form = LoginForm(data=request.POST)
            if form.is_valid():
                if SignUp.objects.filter(
                        UserName=request.POST.get('UserName')).exists():
                    profile = SignUp.objects.get(
                        UserName=request.POST.get('UserName'))
                    if profile.Password == request.POST.get('Password'):
                        request.session['UserName'] = profile.UserName
                        # request.session['Test']=0
                        return redirect("login")
                    else:
                        return render(request, 'login/login.html', {
                            'form': form,
                            'msg': "Incorrect Password"
                        })
                else:
                    return render(request, 'login/login.html', {
                        'form': form,
                        'msg': "User does not exists."
                    })
        else:
            form = LoginForm()
        return render(request, 'login/login.html', {'form': form})
Ejemplo n.º 15
0
    def post(self, request):
        form = LoginForm(request, data=request.POST)
        redirect_to = "task_list"
        if form.is_valid():
            login(request, form.get_user())
            return HttpResponseRedirect(reverse(redirect_to))

        return HttpResponse(render(request, "woodpecker/index.html", {"login_form": form}))
Ejemplo n.º 16
0
def login():
    genericData = {"title": "Sign In", "heading": "Login"}
    form = LoginForm()
    if form.validate_on_submit():
        flash('Login requested for user {}, remember_me={}'.format(
            form.username.data, form.remember_me.data))
        return redirect(url_for('home'))

    return render_template("login.html", data=genericData, form=form)
Ejemplo n.º 17
0
 def test_login_con_password_menor_a_8_caracteres(self):
     crear_usuario(self)
     form = LoginForm(data={
         'username': '******',
         'password': '******',
     })
     self.assertFalse(form.is_valid())
     self.assertEqual(form.errors['password'][0],
                      'La longitud minima es de 8')
Ejemplo n.º 18
0
 def test_login_con_username_mayor_a_50_caracteres(self):
     crear_usuario(self)
     form = LoginForm(
         data={
             'username':
             '******',
             'password': '******',
         })
     self.assertFalse(form.is_valid())
     self.assertEqual(form.errors['username'][0],
                      'La longitud maxima es de 50')
Ejemplo n.º 19
0
def login():
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User.select_by_email(form.email.data)
        if user and user.validate_password(form.password.data):
            login_user(user)
            next = request.args.get('next')
            if not next:
                next = url_for('app.welcome')
            return redirect(next)
    return render_template('login.html', form=form)
Ejemplo n.º 20
0
def validateForm(request):
	form = LoginForm(request.POST)
	if form.is_valid():
		data = form.cleaned_data
		user = auth.authenticate(username=data['username'], password=data['password'])
		if user is not None and user.is_active:
			auth.login(request, user)
			return HttpResponseRedirect('/index/news')
	t = get_template('login.html')
	html = t.render(Context({'form' : form}))
	return StreamingHttpResponse(html)
Ejemplo n.º 21
0
 def post(self, request, *args, **kwargs):
     form = LoginForm(request.POST or None)
     if form.is_valid():
         username = form.cleaned_data['username']
         password = form.cleaned_data['password']
         user = authenticate(username=username, password=password)
         if user:
             login(request, user)
             return HttpResponseRedirect('/')
     categories = Category.objects.all()
     context = {'form': form, 'categories': categories, 'cart': self.cart}
     return render(request, 'login.html', context)
Ejemplo n.º 22
0
def login(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            user = auth.authenticate(
                username=form.cleaned_data.get("username"),
                password=form.cleaned_data.get("password"),
            )
            auth.login(request, user)
            return HttpResponseRedirect(reverse("welcome"))
    else:
        form = LoginForm()
    return render(request, "login/login.html", {"form": form})
Ejemplo n.º 23
0
def loginView(request):
    username = "******"

    if request.method == "POST":
        MyLoginForm = LoginForm(request.POST)
        if MyLoginForm.is_valid():
            if MyLoginForm.cleaned_data['username'] == 'admin':
                if MyLoginForm.cleaned_data['password'] == '123':
                    username = MyLoginForm.cleaned_data['username']
                    request.session['username'] = username
                    request.session.set_expiry(15)
    else:
        MyLoginForm = LoginForm()
    return render(request, 'loggedin.html', {'username': username})
Ejemplo n.º 24
0
def login(request):
    if request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            try:
                # file_upload(request.FILES['file'])
                return HttpResponse(
                    "<h1>" +
                    "Hello, Welcome to Django and File uploaded successfully!"
                    + "</h2>")
            except:
                pass
    else:
        login_form = LoginForm()
    return render(request, 'registration/login.html', {'form': login_form})
Ejemplo n.º 25
0
def register(request):
    if request.method == "POST":
        login_form = LoginForm(data=request.POST)

        if login_form.is_valid():
            user = login_form.save()
            print(user.password)
            user.set_password(user.password)
            user.save()

            messages.success(request, "Successfully registered")
            return HttpResponseRedirect("/login")

    messages.error(request, "Error while registering")
    return HttpResponseRedirect("/login")
Ejemplo n.º 26
0
    def post(self, request):
        form = LoginForm(request.POST or None)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return redirect('/jurnal/')
            else:
                messages.add_message(request, messages.WARNING,
                                     'Username dan Password salah!!!')

        return redirect('/login/')
Ejemplo n.º 27
0
def login_page(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            u = form.cleaned_data['username']
            p = form.cleaned_data['password']
            user = authenticate(request, username=u, password=p)
            if user is not None:
                login(request, user)
                return HttpResponseRedirect('/czat/')
            else:
                return HttpResponseRedirect('/nie/')
    else:
        form = LoginForm()
    return render(request, 'login.html', {'form': form})
Ejemplo n.º 28
0
def process_login(request):
    """
    View function for loging in a site.
    """

    if request.user.is_authenticated():
        return redirect('login:logedin')

    if request.method == 'POST':

        form = LoginForm(request.POST)

        if form.is_valid():
            #return HttpResponse('THE FORM IS VALID!')
            #return HttpResponse(form.cleaned_data['username'])
            # Assigning & clearing input values.
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            #return HttpResponse('username is: %s' % username)
            #return HttpResponse('password is: %s' % password)

            # Checking username with database username value.
            #return HttpResponse('AUTHENTICATING!')
            user = auth.authenticate(username=username, password=password)
            #return HttpResponse('AUTHENTICATED!')
            #return HttpResponse('user is: %s' % user)

            if user is not None and user.is_active:
                #return HttpResponse('TRYING TO LOGIN!')
                auth.login(request, user)
                #return HttpResponse('LOGGED IN!')
                return HttpResponseRedirect(reverse('login:logedin'))

            else:
                # This is fired if javascript is disabled in browser.
                return HttpResponseRedirect(reverse('login:login-error'))

    else:
        form = LoginForm()  # An unbound form.

    context = {
        'form': form,
        'formname': 'Login',
    }

    return render_to_response('login/login-index.html',
                              context,
                              context_instance=RequestContext(request))
Ejemplo n.º 29
0
def index(request):
	if request.method == 'POST':
		form = LoginForm(request.POST)

		if form.is_valid():
			user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password'])
			# if users:
			# 	print(user.users)
			try:
				login(request,user)
				return redirect('/')

			except:
				return render(request,'login/index.html',{"error":"Username or password incorrect"})
		return render(request,'login/index.html',{"error":"Form not Valid"})
	return render(request,'login/index.html')
Ejemplo n.º 30
0
    def get(self, request):
        if request.user.is_authenticated:
            return redirect('/jurnal/')

        form = LoginForm(request.POST or None)
        data = {'form': form}
        return render(request, self.template_name, data)
Ejemplo n.º 31
0
def mix_of_login_register(request, slug):
    """
        Template contains 2 forms, the login and the registration
        """
    if slug == 'doer':
        is_doer = True
        is_poster = False
    elif slug == 'poster':
        is_poster = True
        is_doer = False
    if request.user.is_authenticated():
        return HttpResponseRedirect('/dashboard/')
    if 'login' in request.POST:
        return LoginRequest(request)
    elif 'register' in request.POST:
        return PersonRegistration(request, slug)
    else:
        form = LoginForm()
        form2 = RegistrationForm()
        context = {
            'form': form,
            'form2': form2,
            'is_doer': is_doer,
            'is_poster': is_poster,
        }
        return render_to_response('mixlogin.html',
                                  context,
                                  context_instance=RequestContext(request))
Ejemplo n.º 32
0
def login():
    loginForm = LoginForm()
    if loginForm.validate_on_submit():
        user = User.query.filter_by(username=loginForm.username.data).first()

        if user is None or not user.check_password(loginForm.password.data):
            flash("Invalid username or password")
            return redirect(url_for("login"))

        login_user(user, remember=loginForm.remember_me.data)

        response = redirect(urlsConfig.URLS['newsfeed_url'])
        response.set_cookie("currentSessionCookie", str(user.id))
        return response

    return render_template("login.html", title="Sign In", loginForm=loginForm)
Ejemplo n.º 33
0
 def get(self, request):
     email = request.GET.get("email")
     form = LoginForm()
     return HttpResponse(
         render(request, "register/success.html", {
             "email": email,
             "login_form": form,
         }))
Ejemplo n.º 34
0
def auth_view(request):
	if request.method == 'POST' :
		form = LoginForm(request.POST)
		if form.is_valid() :
			username = form.cleaned_data['username']
			password = form.cleaned_data['password']
			print username
			print password
			user = auth.authenticate(username=username,password=password)
			if user is not None:
				auth.login(request,user)
 
				return HttpResponseRedirect('/vozeal/player/')
			else:
				return HttpResponseRedirect('/vozeal/invalid/')
		else:
			return HttpResponseRedirect('/vozeal/invalid/')
Ejemplo n.º 35
0
def login_user(request):
    logged = False
    userExist = True
    notMatch = False
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            login = form.cleaned_data["Login"]
            pwd = form.cleaned_data["Password"]
            if not user_exist(login):
                userExist = False
            elif not match(request, login, pwd):
                notMatch = True
            else:
                logged = True
    else:
        form = LoginForm()
    return render(request, "login/login.html", locals())
Ejemplo n.º 36
0
def login(request):
    state = "Please log in below..."
    if ("loggedUserId" in request.session):
        return(HttpResponseRedirect("/home"))
    if request.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:
                state = 'logged in'
                username = form.cleaned_data["username"]
                loggedUser = User.objects.get(username=username)
                request.session["loggedUserId"] = loggedUser.id
                return(render_to_response("home.html",{"loggedUser": loggedUser}))
    else:
        form = LoginForm()
    context = RequestContext(request,{'message':state, 'form':form})
    return render_to_response('login.html',context)
Ejemplo n.º 37
0
def login_page(request):
	message = None
	if request.method == 'POST':
		form = LoginForm(request.POST)
		if form.is_valid():
			username = request.POST['username']
			password = request.POST['password']
			user = authenticate(username=username, password=password)
			if user is not None:
				if user.is_active:
					login(request, user)
					message = "Te has identificado correctamente"
				else:
					message = "Tu usuario esta inactivo"
			else:
				message = "Nombre de usuario y/o password incorrecto"
	else:
		form = LoginForm()
	return render_to_response('login.html', {'message':message, 'form': form},
		context_instance=RequestContext(request))
Ejemplo n.º 38
0
def login():
    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        ld = Ld(form.sso.data)
        valid = ld.ldapFetch(form.password.data)
        if valid:
            check = ld.checkUser()
            if not check:
                ld.addUser(valid)
            user = ld.getLogin()
            login_user(user)
            return redirect(request.args.get('next') or url_for('index'))
        else:
            flash("Invalid SSO or Password")
    return render_template(
            "sb-admin/login.html",
            form=form
            )
Ejemplo n.º 39
0
def sitelogin(request, orig_url):
        if request.user.is_authenticated():
                return HttpResponseRedirect('/' +orig_url)

        if not request.method == 'POST':
	        lform = LoginForm()
        	return render_to_response('login/login.html', { 'lform': lform })
	
        lform = LoginForm(request.POST)
        if not lform.is_valid():
                return render_to_response('login/error.html')

        username = lform.cleaned_data['username']
        password = lform.cleaned_data['password']
        user = authenticate(username=username, password=password)

        if user == None or not user.is_active:
                return render_to_response('login/error.html')
        login(request, user)
        return HttpResponseRedirect('/' +orig_url)
Ejemplo n.º 40
0
def login(request):
    errors = []
    if request.user.is_authenticated():
        return HttpResponseRedirect('/1')
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            username = cd['username']
            password = cd['password']
            if login_validate(request,username,password):
            	#return  HttpResponse('%s' % request.GET.get('next'))
                return HttpResponseRedirect('%s' % request.GET.get('next'))
            else:
                errors.append('wrong username or password')
        return render_to_response('loginform.html',{'form':form,'errors': errors},  RequestContext(request) )
    else:
        form = LoginForm( 
                initial={'username': '******'}
                )
    return render_to_response('login.html',{'form': form}, RequestContext(request) )
Ejemplo n.º 41
0
    def post(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            return  HttpResponseRedirect('/index')
        else:
            mensaje = ""
            form = LoginForm(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 HttpResponseRedirect('/modulos')
                        print "Te has identificado de modo correcto"
                    else:
                        mensaje = "Tu usuario esta inactivo"
                else:
                    mensaje = "Nombre y/o password incorrectos"

            ctx = {'form':form,'mensaje':mensaje}
            return render(request,self.template_name,ctx)
Ejemplo n.º 42
0
def login_page(request):
    message = None
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST["username"]
            password = request.POST["password"]
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    message = "Te has identificado correctamente"
                    return redirect("homepage")
                else:
                    message = "Tu usuario esta inactivo"
            else:
                message = "Nombre de usuario y/o password incorrecto"
    else:
        form = LoginForm()
    return render_to_response(
        "login.html", {"message": message, "form": form}, context_instance=RequestContext(request)
    )
Ejemplo n.º 43
0
def Login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render_to_response('login/login.html', RequestContext(request, {'form': form,}))
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            user = authenticate(username=username, password=password)
            if user is not None and user.is_active:
                login(request, user)
                username = request.user.first_name
                Next = re.search(r"=/(.+)/", request.get_full_path())   #request.get_full_path() : like nginx's $request_uri . url like /login/?next=/index/
                if Next:
                    Next = Next.group(1)
                else:
                    Next = "index/"
                return HttpResponseRedirect("/%s" % Next)
            else:
                return render_to_response('login/login.html', RequestContext(request, {'form': form,'password_is_wrong':True}))
        else:
            return render_to_response('login/login.html', RequestContext(request, {'form': form,}))