Exemple #1
0
def login(request):
    if request.method == 'POST': 
        form = forms1.loginForm(request.POST) 
     
        if form.is_valid(): 
            uname = form.cleaned_data['username']
            pword = form.cleaned_data['password']
        else:
            uname = ''
        userFound = findUser(uname)

        if userFound:
            # The password verified for the user
            if userFound.password == pword:
                request.session['name'] = userFound.username
                if (userFound.admin_non_admin == 1):
                    return HttpResponseRedirect('../auser/aprofile/' + uname)
                else:
                    return HttpResponseRedirect('../user/uprofile/' + uname)
            else:
                form = forms1.loginForm
                return render(request, 'home/login.html', {'form' : form, 'message' : 'wrongpassword'})
        else:
            form = forms1.loginForm
            return render(request, 'home/login.html', {'form' : form, 'message' : 'nosuchuser'})
    else:
        form = forms1.loginForm() # An unbound form
        return render(request, 'home/login.html', {'form' : form})
Exemple #2
0
def administrarEmpleados():
    login_form = forms.loginForm(request.form)
    usuario = session['usuario']
    nombre = login_form.nombre.data
    apellido = login_form.apellido.data
    puesto = login_form.puesto.data
    if nombre != "" and request.method == 'POST':
        agregarEmpleado(nombre, apellido, puesto)
    idEditar = login_form.idEditar.data
    print(idEditar)
    nombreEditar = login_form.nombreEditar.data
    #print (nombreEditar)
    apellidoEditar = login_form.apellidoEditar.data
    puestoEditar = login_form.puestoEditar.data
    lista = listaMod()
    print(idEditar)
    #print("fasfasfgagagaghhas")
    if idEditar != "":
        print("entro al if de idEditar")
        editarEmpleado(idEditar, nombreEditar, apellidoEditar, puestoEditar)
    #print (lista)
    listaEmpleados = listaEmp()
    #print (listaEmpleados)
    for x in lista:
        if usuario == x[0]:
            login_form = forms.loginForm(request.form)
            print(listaEmpleados)
            return render_template('AdministrarEmpleados.html',
                                   form=login_form,
                                   listaEmpleados=listaEmpleados)

    return redirect(url_for('index'))
Exemple #3
0
def login(request):
    if request.method == "POST":
        form = loginForm(request.POST)
        if form.is_valid():
            user_email = form.cleaned_data['email']
            logged_user = user.objects.get(email=user_email)
            request.session['logged_user_id'] = logged_user.id
        return HttpResponseRedirect('/main')
    else:
        form = loginForm()
        return render_to_response('login.html', {'form': form})
def loginView():
    if not 'token' in session:
        kwargs = {'formWidth': 300, 'contentTitle': 'Login'}

        form = loginForm()
        if form.validate_on_submit():
            regNo = form.regNo.data
            email = form.email.data
            password = form.password.data

            dataDict = {'regNo': regNo, 'email': email, 'password': password}

            req = authAPI('login', method='post', dataDict=dataDict)
            if 'success' in req:
                session['token'] = req['token']
                session['email'] = req['email']
                session['roles'] = req['roles']
                successMessage('You are now logged in')
                return redirect(url_for('indexView'))
            else:
                errorMessage('User / password combination error')

        return render_template('auth/loginForm.html', form=form, **kwargs)
    else:
        errorMessage('You are already logged into the system')
        return redirect(url_for('indexView'))
Exemple #5
0
def login():
    form = loginForm(request.form)
    if request.method == 'POST' and form.validate_on_submit:
        try:
            mydb = mysql.connector.connect(
                host="iot.c8yxuwoh5r6m.us-east-1.rds.amazonaws.com",
                user="******",
                password="******",
                database="securitysys_db")

            mycursor = mydb.cursor()
            sql = "SELECT * FROM Users WHERE Email = %s AND Password = %s"

            input = (form.email.data, form.password.data)
            mycursor.execute(sql, input)
            myresult = mycursor.fetchone()

            session['uid'] = myresult[0]
            session['firstName'] = myresult[1]

            mycursor.close()
            mydb.close()
            return redirect(url_for('home'))
        except:
            abort(401)

    else:
        return render_template("login.html", form=form)
Exemple #6
0
def log_in():
    """If the request is POST and form data is valid, check credential to authenticate.
    If authentication is true, add current user to the session and redirect to /users/<username> route.
    Otherwise, render the form template."""

    if "user_username" in session:
        return redirect(f'/users/{session["user_username"]}')

    form = loginForm()

    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data

        user = User.authenticate(username, password)

        print("\n\n\n THE USER IS", user)

        if user:
            session["user_username"] = user.username
            return redirect(f'/users/{user.username}')
        else:
            form.username.errors = ["Invalid username/password"]

    return render_template('login-form.html', form=form)
Exemple #7
0
 def wrapped_function(*args, **kwargs):
     if 'level' in session:
         #if no argument specified, being logged in is enough
         if level == None:
             return fn(*args, **kwargs)
         #lower numbers give more power
         elif session['level'] <= level:
             return fn(*args, **kwargs)
         else:
             if session['level'] == 2:
                 header = "Unauthorized"
                 body = """<p>Sorry, your access level does not allow you to view this page.</p>"""
                 return render_template('completepage.html',
                                        header=header,
                                        body=body,
                                        user=session['user'])
             elif session['level'] == 3:
                 header = "Account not enabled"
                 body = """<p>The account is not available to be used for advances operations until a staff member from Rudraya activates it</p>"""
                 return render_template('completepage.html',
                                        header=header,
                                        body=body,
                                        user=session['user'])
             elif session['level'] == 4:
                 header = "Email address not yet verified"
                 body = """<p>In order to view this page, please verify your email address by clicking the link in the email which was sent
                 to the email address you registered with. Please click <a href="%s">here</a> if you would like us to send 
                 the verification email again.</p>"""
                 return render_template(
                     'completepage.html',
                     header=header,
                     body=body % (url_for('resendactivationemail')),
                     user=session['user'])
             elif session['level'] == 5:
                 header = "Banned"
                 body = """<p>The account you have attempted to log in with has been banned by an administrator</p>"""
                 return render_template(
                     'completepage.html',
                     header=header,
                     body=body % (url_for('resendactivationemail')),
                     user=session['user'])
             else:
                 header = "A strange error has occurred"
                 body = """<p>The design of this page blocks content from superadmin users, please contact webmaster.</p>"""
                 return render_template('completepage.html',
                                        header=header,
                                        body=body,
                                        user=session['user'])
     else:
         #if not logged in at all, then must log in
         header = "Please log in"
         body = "<p>You must be logged in to view this page, please use the log in panel at the top of the page.</p>"
         loginForm = forms.loginForm()
         #add the current url to the login form for redirection later
         loginForm.wantsurl.data = request.url
         return render_template('completepage.html',
                                header=header,
                                body=body,
                                loginForm=loginForm,
                                wantsurl='privacy')
Exemple #8
0
def loginView(lang='dk'):
    if not 'token' in session:
        g.lang = lang
        kwargs = {'formWidth':300,
                  'contentTitle':messageText('newPassword'),
                  'breadcrumbs': breadCrumbs('authBP.loginView')}

        form = loginForm()
        if form.validate_on_submit():
            regNo = form.regNo.data
            email = form.email.data
            password = form.password.data

            dataDict = {'regNo':regNo,
                        'email':email,
                        'password':password}

            req = authAPI('login', method='post', dataDict=dataDict)
            if 'success' in req:
                session['token'] = req['token']
                session['email'] = req['email']
                session['roles'] = req['roles']
                flashMessage('loginSuccess')
                return redirect(url_for('indexView', lang=lang))
            else:
                print req
                flashMessage('loginError')

        return render_template(lang+'/auth/loginForm.html', form=form, **kwargs)
    else:
        flashMessage('alreadyLoggedIn')
        return redirect(url_for('indexView', lang=lang))
Exemple #9
0
def sign():
	form = loginForm()
	if form.validate_on_submit():
		return redirect ('login')
		u = models.user(firstname = request.user['firstname'])
		db.session.add(u)
	return render_template('signin.html', form = form, title = 'SignIn')
Exemple #10
0
def inject_user():

    pageVars = {}
    pageVars['banner'] = 'MISPrint'
    pageVars['navEnabled'] = True

    if 'level' in session:
        pageVars['user'] = session['user']
        pageVars['fname'] = session['fname']
        pageVars['lname'] = session['lname']
        pageVars['level'] = session['level']
        pageVars['loginForm'] = None
        #db = get_db()
        # userGlasses = db.users.find_one({"_id":user}, {'_id':0,"glasses":1})['glasses']
        # if len(userGlasses) == 0:
        #     glasses = None
        # else:
        #     glasses = db.glasses_available.find({'nickname':{'$in':userGlasses}})

    else:
        pageVars['user'] = False
        pageVars['loginForm'] = forms.loginForm()
        pageVars['loginForm'].wantsurl.data = request.url

    return pageVars
Exemple #11
0
def loginJugador():
	global userNow
	login = loginForm()
	if request.method == 'POST':
		if not getUser():
			if request.form['signIn'] == 'Sign In':
				#return redirect(url_for('juego'))
				#if request.form['correo'] == '*****@*****.**':
				#if request.form['passwd'] == '123':
				if login.validate():
					return redirect(url_for('loginJugador'))
				else:
					correo = request.form['correo']
					password = request.form['passwd']
					if verificarUsuario(correo, password):
						userNow = correo
						signInUsuario(correo)
						grade = getGrade(correo)
						if grade < 7:
							return redirect(url_for('juego'))
						else:
							return redirect(url_for('juego2'))
					return redirect(url_for('loginJugador'))
		else:
			if verificarCorreoUsuario(getUser()):
				grade = getGrade(getUser())
				if grade < 7:
					return redirect(url_for('juego'))
				else:
					return redirect(url_for('juego2'))
			else:
				return redirect(url_for('admin'))
	return render_template('loginUsuario.html', title = "Mereces Tu Diploma? Login", form = login)
Exemple #12
0
def login():
    form = loginForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' and form.password.data == 'password':
            return redirect(url_for('home'))
        else:
            flash('Login unsuccessful, please check email and password',
                  'danger')
    return render_template('login.html', title='Login', form=form)
 def register(self):
     reg_form = registerForm(request.form)
     login_form = loginForm(request.form)
     if request.method == "POST":
         if reg_form.submit1.data and reg_form.validate():
             user = {
                 "_id": uuid.uuid4().hex,
                 "name": reg_form.name.data,
                 "email": reg_form.email.data,
                 "username": reg_form.username.data,
                 "password": reg_form.password.data
             }
             user['password'] = sha256_crypt.encrypt(user['password'])
             if config.db.users.find_one({"email": user['email']}):
                 error = "Email already exists!"
                 return render_template(config.template,
                                        error=error,
                                        reg_form=reg_form,
                                        login_form=login_form)
             if config.db.users.insert_one(user):
                 self.start_session(user)
                 flash('You are now registered and can log in!', 'success')
                 return render_template(config.template,
                                        reg_form=reg_form,
                                        login_form=login_form)
         elif login_form.submit2.data and login_form.validate():
             user = config.db.users.find_one(
                 {"username": login_form.username.data})
             if user:
                 if sha256_crypt.verify(login_form.password.data,
                                        user['password']):
                     self.start_session(user)
                     return render_template('dashboard.html')
                 else:
                     error = 'Incorrect login details!'
                     return render_template(config.template,
                                            error=error,
                                            reg_form=reg_form,
                                            login_form=login_form)
             else:
                 error = 'Username not found!'
                 return render_template(config.template,
                                        error=error,
                                        reg_form=reg_form,
                                        login_form=login_form)
         error = 'Check the registered details!'
         return render_template(config.template,
                                error=error,
                                reg_form=reg_form,
                                login_form=login_form)
     else:
         try:
             return render_template(config.template,
                                    reg_form=reg_form,
                                    login_form=login_form)
         except Exception:
             return "Given template does not exists."
Exemple #14
0
def login():
  form = loginForm()                          #sets the form as the login form class as defined
  if request.method == 'POST':                #this is the same as the contact form, checking for POST and Validation
    if form.validate() == False:
      return render_template('login.html',form=form)
    else:
      session['email'] = form.email.data      #if all is passed, it logs the user in by creating a cookie of thier email address. this is done by using the session command in flask as thier data is then secure
      return redirect(url_for('index'))       #sends user to the home page after logging in    
  elif request.method == 'GET':
    return render_template('login.html', form=form)
Exemple #15
0
def login():
    form = loginForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' and form.password.data == 'password':
            flash("Logged Successfully")
            return redirect(url_for('home'))
        else:
            flash('Login Unsucessfuly please check username and password','danger')

    return render_template('login.html',title='Login',form=form)
Exemple #16
0
    def decorated_function(*args, **kwargs):

        if 'level' in session:
            user = session['user']
            loginForm = None
        else:
            user = False
            loginForm = forms.loginForm()
            loginForm.wantsurl.data = request.url
        return f(user=user, loginForm=loginForm, *args, **kwargs)
Exemple #17
0
def login():
    form = forms.loginForm(request.form)
    if request.method == 'POST' and form.validate():
        if form.username.data in app.config['ADMINS'] and ldap.search_and_auth(
                form.username.data, form.password.data):
            session['username'] = form.username.data
            return redirect(url_for('show_assets'))
        else:
            flash('incorrect username or password')
    return render_template('login.html', form=form)
def login():
    form = loginForm()
    if form.validate_on_submit():

        if form.password.data == app.config['password']:
            session['password'] = app.config['password']
            session.permanent = True
            return redirect(url_for('home'))

    return render_template('login.html', form=form)
Exemple #19
0
def administrarObjetos():
    login_form = forms.loginForm(request.form)
    #usuario = session['usuario']
    #lista = listaMod()
    #print (lista)
    #listaEmpleados = listaEmp()
    #print (listaEmpleados)
    #for x in lista:
    #	if usuario == x[0]:
    #		login_form = forms.loginForm(request.form)
    return render_template('AdministrarObjetos.html', form=login_form)
Exemple #20
0
def login():
    if current_user.is_authenticated:
        return redirect(request.args.get('next', '/'))

    LF = f.loginForm()

    if LF.validate_on_submit():
        login_user(User('username', LF.username.data), remember=True)

        return redirect(request.args.get('next', '/'))

    return render_template('login.html', form=LF)
Exemple #21
0
def login():
    form = loginForm()
    if form.validate_on_submit():
        password = form.password.data
        username = form.username.data
        user = Users.query.filter_by(username=username).first()
        if ph.validate_password(password, user.salt, user.hashed):
            login_user(user)
            return redirect(vs_url_for('index'))
        else:
            flash('login unsuccessful!')
    return render_template('login.html', form=form)
Exemple #22
0
def login():
    form = loginForm()  #sets the form as the login form class as defined
    if request.method == 'POST':  #this is the same as the contact form, checking for POST and Validation
        if form.validate() == False:
            return render_template('login.html', form=form)
        else:
            session[
                'email'] = form.email.data  #if all is passed, it logs the user in by creating a cookie of thier email address. this is done by using the session command in flask as thier data is then secure
            return redirect(url_for(
                'index'))  #sends user to the home page after logging in
    elif request.method == 'GET':
        return render_template('login.html', form=form)
Exemple #23
0
def login():
    form = loginForm()

    if request.method == 'POST':
        if (form.validate() == False):
            flash('All fields are required.')
            return render_template('landing.html', **locals())
        else:
            name = request.form.get("name", "")
            return render_template('return.html', **locals())
    elif (request.method == 'GET'):
        return render_template('landing.html', **locals())
Exemple #24
0
def signin():
    form = SearchForm()
    form_register = loginForm()
    if form_register.validate_on_submit():
        if User.query.filter_by(username = form_register.username.data).first():
            user = User.query.filter_by(username = '******').first()
            if check_password_hash(user.password, form_register.password.data):
                session['username'] = form_register.username.data
                flash(f'{form_register.username.data} has logged in!', 'success')
                return redirect(url_for('home'))
        flash(f'{form_register.username.data} has not logged in!', 'danger')
    return render_template('signin.html', title= 'Log in', form= form, form_register = form_register)
Exemple #25
0
def login():
    '''
    Login Form
    '''

    form = forms.loginForm(request.form)
    if request.method == 'POST' and form.validate():
        if ldap.search_and_auth(form.username.data, form.password.data):
            session['username'] = form.username.data
            return redirect(url_for('index'))
        else:
            flash('incorrect username or password')
    return render_template('login.html', form=form)
def login():
    form = loginForm()
    if form.validate_on_submit():
        password = form.password.data
        username = form.username.data
        user_id = db.check_password(username, password)
        if user_id:
            user = User(user_id, username)
            login_user(user)
            return redirect(vs_url_for('twits_blueprint.index'))
        else:
            flash('login unsuccessful!')
    return render_template('login.html', form=form)
Exemple #27
0
def loginUser(request):
	if request.user.is_authenticated():
		return HttpResponseRedirect("/")

	next = request.GET.get('next')
	if len(request.POST) > 0:
		form = loginForm(request.POST)
		if form.is_valid():
			s_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
			if s_user is not None:
				login(request, s_user)
				if next is not None:
					return HttpResponseRedirect(next)
				else:
					return HttpResponseRedirect("/")
			else:
				return render_to_response("login.html", {'form': form, 'next':next})
		else:
			return render_to_response("login.html", {'form': form, 'next':next})
	else:
		form = loginForm()
		return render_to_response("login.html", {'form': form, 'next':next})
Exemple #28
0
def index():

    RegistrationForm = registrationForm()
    LoginForm = loginForm()

    if RegistrationForm.validate_on_submit():
        user = Users.query.filter_by(
            email=RegistrationForm.email2.data).first()

        if user is not None:
            flash("Email Id already registered!")

        else:

            passw = generate_password_hash(RegistrationForm.password2.data)

            user = Users(
                email=RegistrationForm.email2.data,
                name=RegistrationForm.username2.data,
                pasword_hash=passw,
            )

            db.session.add(user)
            db.session.commit()
            flash("Thanks for registeration! Login to continue")
            return redirect(url_for("index"))

    if LoginForm.validate_on_submit():
        user = Users.query.filter_by(email=LoginForm.email1.data).first()

        if user is not None and user.check_password(LoginForm.password1.data):

            login_user(user)
            # flash('Log in Success')

            next = request.args.get("next")

            if next == None or not next[0] == "/":
                next = url_for("dashboard")

            return redirect(next)

        elif user is None:
            flash("Email Id not registered!")

        else:
            flash("Wrong Password!")

    return render_template("index.html",
                           logForm=LoginForm,
                           signForm=RegistrationForm)
Exemple #29
0
def showLoginForm():
    loginForm = forms.loginForm(request.form)
    if request.method == 'POST' and loginForm.validate():
        username = request.form['userName']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        if user is not None and user.verifyPassword(password):
            #if 1==1:
            session['userName'] = username
            session['idP'] = user.idPerson
            print(user.position)
            return redirect(url_for('showDashBoard'))

    return render_template('General/login.html', form=loginForm)
Exemple #30
0
def login():
    '''
    Login Form
    '''

    form = forms.loginForm(request.form)
    if request.method == 'POST' and form.validate():
        if ldap.search_and_auth(
                form.username.data, form.password.data):
            session['username'] = form.username.data
            return redirect(url_for('index'))
        else:
            flash('incorrect username or password')
    return render_template('login.html', form=form)
Exemple #31
0
def login():
    form = loginForm()
    if form.validate_on_submit():
        password = form.password.data
        username = form.username.data
        # get user object using sqlalchemy
        user = Users.query.filter_by(username=username).first()
        # use password helper to validate password
        if ph.validate_password(password,user.salt,user.hashed):
            login_user(user)
            return redirect(vs_url_for('index'))
        else:
            flash('please try again')
    return render_template('login.html',form=form)
def login_page():
    if current_user.is_authenticated:
         return redirect(url_for('home'))
    form=loginForm()
    if request.method =='POST':
        if form.validate_on_submit:
            user = username_check(form.username.data)
            if user and bcrypt.check_password_hash(user.password,form.password.data):
                login_user(user, remember=form.remember.data)
                next_page=request.args.get('next')
                return redirect(next_page) if next_page else redirect(url_for('home'))
            else:
                flash(f'Login Unsuccessful. Check Username and Password!', 'warning')
    return render_template("login.html", form = form)
Exemple #33
0
def login(request):
    if request.method == 'GET':
        response = render(request, 'admin/login.html')
    else:
        form = loginForm(request.POST)
        if form.is_valid():
            key = form.user.key
            response = redirect('/admin/home/')
            response.set_cookie('adminCookie', key)
        else:
            response = render(request, 'admin/login.html', {
                'data': request.POST,
                'form': form
            })
    return response
def login():
    form = loginForm()
    if (form.validate_on_submit()):
        user_log = User.query.filter_by(email=form.email.data).filter_by(
            password=form.password.data).first()
        if (user_log):
            session["user"] = user_log.full_name
            return render_template("login.html",
                                   message="Succesfully Logged In")
        else:
            return render_template(
                "login.html", message="Wrong credentials. Please try again.")
    elif form.errors:
        return render_template("login.html", form=form)
    return render_template("login.html", form=form)
Exemple #35
0
def login():
    form = loginForm()
    if form.validate_on_submit():
        try:
            data = list(
                dbengine.execute(
                    "select userID, passwd from cred where userID='{}';".
                    format(form.userID.data)))
            if data[0][0] == form.userID.data:
                if data[0][1] == form.passwd.data:
                    return redirect('/')
        except:
            pass
        return redirect(url_for('login'))
    return render_template('login.html', form=form)
Exemple #36
0
    def POST(self):
        form = forms.loginForm()
	if not form.validates():
            return render.formtest(form)
        else:
	    i = web.input()
	    username = i.username
	    passwd = i.password
            pwdhash = hashlib.md5(passwd).hexdigest()
	    authdb = sqlite3.connect('db/db1')
	    check = authdb.execute('select * from users where username=?\
			    and password=?',(username,pwdhash))
            if check:
                session.loggedin = True
		session.username = username
		raise web.seeother('/')
            else:
                return render.base('Login failed, please try again!')
def login():
    form = loginForm()

    if request.method == "GET":
        return render_template("login.html", form=form) 

    elif request.method == "POST":
        if form.validate():
            username = form.username.data
            password = form.password.data
            if user_validate_credentials(username, password):
                user = User()
                user.id = username
                flask_login.login_user(user)
                
                # check to see if default credentials are being used. If so, redirect to change password page.
                if user_validate_credentials("admin", "gosecure"):
                    flash("Please change the default password.", "notice")
                    return redirect(url_for("user"))
                else:
                    internet_status_bool = internet_status()
                    vpn_status_bool = vpn_status()
                    vpn_configuration_status_bool = vpn_configuration_status()

                    # check to see if network is up. If not, redirect to network page
                    if internet_status_bool is False and vpn_configuration_status_bool is True:
                        flash("Internet is not reachable.", "notice")
                        return redirect(url_for("wifi"))
                    # check to see if network and vpn are up. If not, redirect to initial setup page
                    elif internet_status_bool is False and vpn_status_bool is False:
                        return redirect(url_for("initial_setup"))
                    # check to see if vpn is up. If not, redirect to vpn page
                    elif vpn_status_bool is False:
                        flash("VPN is not established.", "notice")
                        return redirect(url_for("vpn_psk"))
                    else:
                        return redirect(request.args.get("next") or url_for("status"))
            else:
                flash("Invalid username or password. Please try again.", "error")
                return render_template("login.html", form=form)
        else:
            flash_form_errors(form)
            return render_template("login.html", form=form)
Exemple #38
0
def login():
    if 'username' in session:
        return redirect(url_for('dashboard'))
    form=loginForm()
    if request.method=='POST' and form.validate_on_submit():
        if form.validate()==False:
            flash("Username or password error!")
            return render_template('auth/login.html',form=form)
        else:
            user=Users.query.filter_by(username=form.username.data).first()
            print user

            u = load_user(user.id)
            login_user(u, form.remember_me.data)
            userIPAddress=getIPInfo()
            logUserLogin(user.username, userIPAddress)
            return redirect(url_for('dashboard'))
    else:
        return render_template('auth/login.html',form=form)
Exemple #39
0
def login():
    error = None
    form = loginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()

        if user is None:
            error = 'User does not exist'
        elif (bcrypt.check_password_hash(
                user._password, form.password.data) is not True):
            error = 'Wrong user/password combination'
        else:
            session['logged_in'] = True
            session['user_id'] = user.id
            session['name'] = user.username
            flash('You were logged in.')
            return redirect(url_for('index')), 200

    return render_template('login.html', error=error, form=form), 400
Exemple #40
0
    def GET(self):
        loginform = forms.loginForm()
	return render.formtest(loginform)
Exemple #41
0
 def test_empty(self):
     form_data = {'username': '', 'password' : ''}
     form = loginForm(data=form_data)
     self.assertEqual(form.is_valid(), False)
Exemple #42
0
def index(request):
    """
        Login view
    """
    if not request.user or not request.user.is_authenticated():
        # Not autenticate user, show login form
        form = loginForm ()
        if request.method == 'POST':
            form = loginForm (request.POST)
            if form.is_valid ():
                user = authenticate (username = form.data['username'], 
                                     password = form.data['password']
                                    )
                if user is not None:
                    login (request, user)
                    info (request, 'index', 
                          'User %(username)s logged in ' % {'username':user.username}
                         )
                    request.session['profile'] = getProfile (user)
                    menu = request.session['profile']                    
                    if request.GET.has_key ('next'):
                        return HttpResponseRedirect(request.GET['next'])
                    data = {}
                    try:
                        credits = {}
                        u = Customer.objects.get(id=request.user.id)
                        for account in u.account_set.all():
                            credits[account.name] = account
                        data['credit'] = credits
                    except Customer.DoesNotExist:
                        if checkAdmin(user):
                            for account in Account.objects.all():
                                credits[account.name] = account
                            data['credit'] = credits
                    data['profile'] = menu
                    return render_to_response(TEMPLATES['root'], data,
                                                RequestContext (request)
                                             )
                else:
                    warning (request, 'index', 
                             'Invalid username or password'
                            )
                    form.errors['username'] = [
                                            _('Invalid username and password')
                                              ]
            else:
                warning (request, 'index', _('Posted values not valid'))
        else:
            info (request, 'index', 'Showing login form')
        data = {}
        data['form'] = form
        data['profile'] = getProfile(request.user)
        return render_to_response(TEMPLATES['login'], data , RequestContext (request))
    else:
        # Autenticate user
        try:
            data = {}
            try:
                credits = {}
                user = Customer.objects.get(id=request.user.id)
                for account in user.account_set.all():
                    credits[account.name] = account
                data['credit'] = credits
            except Customer.DoesNotExist:
                if (checkAdmin(request.user)):
                    for account in Account.objects.all():
                        credits[account.name] = account
                    data['credit'] = credits
            data['profile'] = request.session['profile']                            
            data['showInfoToUser'] = getOutputMsg(request)

            return render_to_response(TEMPLATES['root'], 
                                      data, 
                                      RequestContext (request)
                                     )            
        except KeyError:
            # Profile not correctly loaded, so we log out
            # and ask for login            
            return logout_view(request)            
Exemple #43
0
 def test_forms(self):
     form_data = {'username': '******', 'password' : 'socute'}
     form = loginForm(data=form_data)
     self.assertEqual(form.is_valid(), True)
Exemple #44
0
 def test_limit(self):
     form_data = {'username': '******', 'password' : 'limit'}
     form = loginForm(data=form_data)
     self.assertEqual(form.is_valid(), False)