Пример #1
0
def signin(request):    
    message = ''
    if request.method == 'POST': 
        form = LoginForm(request.POST) 
        if form.is_valid():
            login_username = form.cleaned_data['login_username']
            login_password = form.cleaned_data['login_password']
            user = authenticate(username=login_username, password=login_password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    if user.is_superuser:
                        return HttpResponseRedirect('/server1/')
                    else:
                        return HttpResponseRedirect('/server2/')
                else:
                    message='User is disabled'
            else:
                message="Invalid User"
        else:
            message = 'Please enter your username and password.'
    else:
        form = LoginForm()

    return render(request, 'signin.html', {
        'message': message,
        'login_username': '',
        'form': form,
    })
Пример #2
0
def signin(request):
    try:
        next = request.POST['next']
    except KeyError:
        try:
            next = request.GET['next']
        except KeyError:
            next = SNAP_PREFIX

    if request.POST:
        form_data = request.POST.copy()
        form = LoginForm(form_data)

        if form.is_valid():
            user = form.user
            login(request, user)
            form = LoginForm()
            return redirect_to(request, next)
    else:
        form = LoginForm()

    return render_to_response('snapboard/signin.html',
        {
        'login_form': form,
        'login_next': next,
        },
        context_instance=RequestContext(request))
Пример #3
0
def login():
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate_on_submit():
        user = form.get_user()
        login_user(user, remember=True)
        return redirect(url_for('main'))
    return render_template('login.jade', form=form)
Пример #4
0
def login(request):
    """
    Logs a user in using Django's contrib.auth, and sets the cookie that
    the cardstories client expects.

    """
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            # At this point, the user has already been authenticated by form
            # validation (which simplifies user feedback on login errors).
            auth_login(request, form.auth_user)

            GravatarAvatar(form.auth_user).update()

            # Redirect maintaining game_id, if set.
            url = '%s%s' % (reverse(welcome), get_gameid_query(request))
            return redirect(url);
    else:
        form = LoginForm()

    context = {'registration_form': RegistrationForm(),
               'login_form': form}
    return render_to_response('cardstories/welcome.html', context,
                              context_instance=RequestContext(request,
                              processors=[common_variables]))
Пример #5
0
 def post(self):
     form = LoginForm()
     if form.validate_on_submit():
         user = form._get_user()
         login_user(user)
         return redirect(url_for('admin.list'))
     return render_template('login.html', form=form)
Пример #6
0
def login():
    error = None
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            u = User.query.filter_by(
                name=request.form['name'],
                password=request.form['password']
            ).first()
            if u is None:
                error = 'Invalid username or password.'
                return render_template(
                    "login.html",
                    form=form,
                    error=error
                )
            else:
                session['logged_in'] = True
                session['user_id'] = u.id
                session['role'] = u.role
                flash('You are logged in. Go Crazy.')
                return redirect(url_for('tasks.tasks'))
        else:
            return render_template(
                "login.html",
                form=form,
                error=error
            )
    if request.method == 'GET':
        return render_template('login.html', form=form)
Пример #7
0
def login():
    form = LoginForm()
    if request.method == 'GET':
        return render_template('login.html', title = 'Log in', form = form, providers = app.config['OPENID_PROVIDERS'])
    if form.validate_on_submit():
        return redirect('/')
    return render_template('login.html', title = 'Log in', form = form)
Пример #8
0
def login(request):
	'''登录动作'''
	# 已经是登录状态的用户
	if request.session.get('isLogin',False) == True:
		return HttpResponseRedirect('/')

	# 非登录状态的用户
	loginform = LoginForm(auto_id=True)
	if request.method == 'POST':
		loginform = LoginForm(request.POST)
		if loginform.is_valid():
			account = loginform.cleaned_data['account']
			password = loginform.cleaned_data['password']

			# 查询数据库内信息,是否登录成功
			customer = CustomerModel.objects.filter(account=account, password=password)
			if customer :
				request.session['isLogin'] = True
				request.session['uid'] = customer[0].id
				request.session['nickname'] = customer[0].name
				return HttpResponseRedirect('/')
	# 表格字段格式错误,或者登录失败
	return render_to_response(
		'customer/login.html',
		{
		 'form' : loginform,
		 'session' : request.session,
		},
		context_instance=RequestContext(request)
	)
Пример #9
0
def account_login(request):
    form = LoginForm(request.POST or None)
    redirect_to = request.REQUEST.get('next', '')

    if request.method == "GET":
        if redirect_to and request.user.is_authenticated():
            return HttpResponseRedirect(redirect_to)

    if request.method == 'POST':
        if form.is_valid():
            if not redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL

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

            if user:
                login(request, user)
                if data['remember_me']:
                    remember_user(request, user)
                return HttpResponseRedirect(redirect_to)
            else:
                form.add_non_field_error(
                        _("Sorry, you have entered wrong E-mail or Password"))

    return render_to_response('account_login.html',
            RequestContext(request, {
                    'form': form,
                    'next': redirect_to,
                    }))
Пример #10
0
def login(request, template_name='cas/login.html', \
                success_redirect=settings.LOGIN_REDIRECT_URL,
                warn_template_name='cas/warn.html'):
    service = request.GET.get('service', None)
    if request.user.is_authenticated():
        if service is not None:
            if request.GET.get('warn', False):
                return render_to_response(warn_template_name, {
                    'service': service,
                    'warn': False
                }, context_instance=RequestContext(request))
            ticket = ServiceTicket.objects.create(service=service, user=request.user)
            return HttpResponseRedirect(ticket.get_redirect_url())
        else:
            return HttpResponseRedirect(success_redirect)
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            user = form.get_user()
            auth_login(request, user)
            service = form.cleaned_data.get('service')
            if service is not None:
                ticket = ServiceTicket.objects.create(service=service, user=user)
                success_redirect = ticket.get_redirect_url()
            return HttpResponseRedirect(success_redirect)
    else:
        form = LoginForm(initial={
            'service': service,
            'lt': LoginTicket.objects.create()
        })
    return render_to_response(template_name, {
        'form': form,
    }, context_instance=RequestContext(request))
Пример #11
0
def login():
    
    if current_user is not None and current_user.is_authenticated:
        return redirect(url_for('home'))
        
        
    form = LoginForm()
    if request.method == "POST" and form.validate_on_submit():
        
        
        # change this to actually validate the entire form submission
        # and not just one field
        username = form.username.data
        password = form.password.data
        user = UserProfile.query.filter_by(username=username,password=password).first()
            # Get the username and password values from the form.

            # using your model, query database for a user based on the username
            # and password submitted
            # store the result of that query to a `user` variable so it can be
            # passed to the login_user() method.

            # get user id, load into session
        if user is not None: 
            login_user(user)

            # remember to flash a message to the user
            flash ('Logged in successfully.', 'success')
            return redirect(url_for("securepage")) # they should be redirected to a secure-page route instead
        else:
            flash ('Username or Password incorrect','danger')
    flash_errors(form)
    return render_template("login.html", form=form)
Пример #12
0
def login():

    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))
    form_l = LoginForm()
    form_s = SignUpForm()

    if form_l.validate_on_submit() and (len(form_l.openid.data) < 100) and (len(form_l.password.data) < 100):
        session['remember_me'] = form_l.remember_me.data
        user = db.session.query(User).filter(User.email == form_l.openid.data).filter(User.password == md5(form_l.password.data).hexdigest()).first()
        if user is not None:
            login_user(user, remember = form_l.remember_me.data)
            return redirect(url_for('index')) 
        else: 
            print("NOT FOUND")
        
    if form_s.validate_on_submit() and (len(form_s.email.data) < 100) and (len(form_s.login.data) < 50) and (len(form_s.password.data) < 100):
        k = False
        user = db.session.query(User).filter(User.email == form_s.email.data  or  User.nickname == form_s.login.data).first()
        if user is None:
            u = User(nickname=form_s.login.data, email=form_s.email.data, password=md5(form_s.password.data).hexdigest())
            db.session.add(u)
            db.session.commit()
            db.session.add(u.follow(u))
            db.session.commit()
            login_user(u)
            return redirect(url_for('index')) 
        else:
            print("EXISTS")
             
    return render_template('login1.html',
        form_l = form_l,
        form_s = form_s)
Пример #13
0
def v1_login_json(request):
    request.session.clear()
    success = False
    message = ""
    form = LoginForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data["username"]
        password = form.cleaned_data["password"]
        authToken = getAuthToken(request, username, password)

        if authToken != None:
            # Prewarm the cache with location fixtures
            cache.set('contacts-contact1:location', '{"name": "Unknown", "latitude": 35.668879, "longitude": 139.651436}', 3600)
            cache.set('contacts-contact2:location', '{"name": "Unknown", "latitude": 35.667979, "longitude": 139.64999}', 3600)
            cache.set('contacts-contact3:location', '{"name": "Unknown", "latitude": 35.668885, "longitude": 139.650634}', 3600)
            cache.set('contacts-contact4:location', '{"name": "Unknown", "latitude": 35.668737, "longitude": 139.623203}', 3600)

            request.session["authToken"] = authToken
            request.session["username"] = username
            request.session["password"] = password
            success = True
            message = "You're logged in."
        else:
            message = "Wrong username or password."
    return {"success": success, "message": message}
Пример #14
0
def refresh():
    form = LoginForm()
    if form.validate_on_submit():
        confirm_login()
        flash("Authentication refreshed", "success")
        return redirect(request.args.get("next") or url_for("index"))
    return render_template("login.html", login_form=form)
Пример #15
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        login_user(form.user, remember=True)
        flash("Logged In (%s)" % form.user.name, "success")
        return redirect(request.args.get("next") or url_for("index"))
    return render_template("login.html", login_form=form)
Пример #16
0
def login():
	"""
		Log user in or display login form.
	"""
	form = LoginForm(request.form)

	if request.method == 'POST' and form.validate():
		#TODO:  Hash password
		hashed_pw = form.password.data
		#hashed_pw = hash_password(form.password.data)
		user = g.db_session.query(User).filter_by(email=form.email.data, password=hashed_pw).first()
		if user is not None:
			auth_user = AuthUser(user.id, user.username, user.role, user.confirmed)

			if login_user(auth_user):
				flash(u"Logged in!")
				return redirect(request.args.get('next') or url_for('index'))
			else:
				flash(u"Sorry, but you could not be logged in.")
		else:
			flash(u"Invalid login credentials.")

	try:
		return render_template('login.html', form=form)
	except TemplateNotFound:
		abort(404)
Пример #17
0
def login():
    form = LoginForm(request.form)
    if (request.method == 'POST') and form.validate():
        methods.check_if_admin(form.username.data, form.password.data)
        if session["permission"] == "authenticated":
            session['data'] = [0]
            #session['present'] = 'present'
            session["logout"] = False
            return redirect(url_for('show_work'))
        elif session["permission"] == "authorized":
            session['data'] = [0]
            #session['present'] = 'present'
            session["logout"] = False
            return redirect(url_for('show_work'))
        elif session["permission"] == "incorrect":
            flash('Wrong password. Try again.')
            register = True
            return render_template('login.html', form = form, register = register)
        elif session["permission"] == "denied":
            register = False
            flash('No such user. You need to register first')
            return render_template('login.html', form = form, register = register)
    elif request.method == 'POST' and form.username.data =='' or \
            form.password.data == '':
        flash('Fill in all fields, please.')
        return render_template('login.html', form = form)
    else:
        return render_template('login.html', form = form)
Пример #18
0
def login():
    if current_user.is_authenticated():
        return redirect(url_for('index'))
    form_login = LoginForm()
    form_registration = RegistrationForm()

    if form_login.validate_on_submit():
        user = User.query.filter_by(name=form_login.login.data).first()
        if user is None:
            flash('Invalid login')
        elif user.verify_password(form_login.password.data):
            login_user(user, form_login.remember_me.data)
            return redirect(request.args.get('next') or url_for('index'))
        else:
            flash('Invalid password')

    if form_registration.validate_on_submit():
        user = User(
            email=form_registration.email.data,
            name=form_registration.login.data,
            password=form_registration.password.data)
        db.session.add(user)
        db.session.commit()
        flash('You can now login.')
        return render_template('login.html', title='Hello!', form_login=form_login, form_registration=form_registration)

    return render_template('login.html', title='Hello!', form_login=form_login, form_registration=form_registration)
Пример #19
0
def login():
    if 'username' in session:
        flash('You are already logged in.')
        return redirect(url_for('home'))

    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        user = db.retrieve_user_by_username(form.username.data)

        if not user:
            form.username.errors.append('Username not found')
            return render_template('login.html', form=form, title='Login')

        if not db.is_activated(form.username.data):
            flash('This account is not activated, please verify your email by opening activation link that we sent you')
            return render_template('login.html', form=form, title='Login')

        if not user.is_password_correct(form.password.data):
            form.password.errors.append('Wrong password, please try again...')
            return render_template('login.html', form=form, title='Login')

        #  username and password are correct, create a session
        session['username'] = user.username
        session['acc_type'] = user.acc_type

        #  record ip address and timestamp
        db.insert_log(Log(user.username, request.remote_addr))

        return redirect(url_for('profile'))

    return render_template('login.html', form=form, title='Login')
Пример #20
0
def login(request):
	'''登录动作'''
	# 已经是登录状态的用户
	if request.session.get('isLogin',False) == True:
		return HttpResponseRedirect('/')
	s = dir(request.session)
	# 非登录状态的用户
	loginform = LoginForm(auto_id=True)
	if request.method == 'POST':
		loginform = LoginForm(request.POST)
		if loginform.is_valid():
			account = loginform.cleaned_data['account']
			password = loginform.cleaned_data['password']

			print('account:%s,password:%s'%(account,password))
			# TODO:查询数据库内信息,是否登录成功
			if account == 'aaaaaa' and password == 'aaaaaa':
				request.session['isLogin'] = True
				return HttpResponseRedirect('/')

	# 表格字段格式错误,或者登录失败
	return render_to_response(
		'customer/login.html',
		{
		 'form' : loginform,
		 # TODO: debug用
		 'session' : request.session.items(),
		},
		context_instance=RequestContext(request)
	)
Пример #21
0
	def post(self, request):
		form = LoginForm(None, request.POST or None)
		if form.is_valid():
			login_user(request, form.get_user())
			return redirect('index', permanent=True)
		else:
			return render(request, self.template_name, {'login_form': form})
Пример #22
0
def home():
    """
    首页视图函数

        1. 最近录入
        2. 最近借阅

        new_book_list: 最近录入新书列表(默认为6本, 依据时间[id]排序)
    """
    form = LoginForm()
    new_book_list = Book.query.order_by('-id').all()[:9]
    get_book_list = Book.query.filter_by(status=True).order_by('start desc').all()[:2]

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is not None and user.verify_password(form.password.data):
           login_user(user)
           return redirect(url_for('user', id=current_user.id))
        flash('用户名或密码错误!')

    range_book_count = range(len(new_book_list)/6 + 1)

    return render_template('home.html', new_book_list=new_book_list,
                           get_book_list=get_book_list, form=form,
                           range_book_count=range_book_count)
Пример #23
0
def login():
    '''
        form is imported from froms.py
        session["logged_in"] is a boolean wether or not someone is logged in
        if you are already logged in you dont need to login, so you are redirected
        to index

        session['alias'] is the alias of the user that is currently logged in
        session['allowTracking'] is wether or not the user is to be tracked
        session['isMod'] is wether or not user is a moderator/advanced permission
        flash returns a string to be delayed

        
    '''
    form = LoginForm()
    if session.get('logged_in'):
        return redirect(url_for('index'))
    if form.validate_on_submit():
        try:
            user = User.objects(email=form.email.data)[0]
            if check_password_hash(user.password, form.password.data):
                session['logged_in'] = True
                session['alias'] = user.alias
                session['allowTracking'] = user.allowTracking
                session['isMod'] = user.isMod
                return redirect(url_for('index'))
            else:
                flash('Wrong password')
        except:
            flash('Wrong email, silly!')
    return render_template('login.html', form = form)
Пример #24
0
def index():
    if g.user is None:
        login_form = LoginForm(prefix="login")
        registration_form = RegistrationForm(prefix="register")
        button = request.form.get('button')
        if button == 'login' and login_form.validate_on_submit():
            user = login_form.user
            user.touch()
            session['username'] = user.username
            return redirect(request.args.get('next', url_for('index')))
        elif button == 'register' and registration_form.validate_on_submit():
            count = User.query.count()
            user = User(
                registration_form.username.data,
                generate_password_hash(registration_form.password.data),
                registration_form.email.data,
                False,
                True,
                bool(count == 0),
            )
            db.session.add(user)
            db.session.flush()
            email.send_account_created_email(user)
            db.session.commit()
            session['username'] = user.username
            flash('Registration successful! Please check your e-mail so we can verify your address.')
            return redirect(url_for('index'))
        else:
            return render_template('index.html',
                login_form=login_form,
                registration_form=registration_form)
    else:
        identity_tokens = list(g.user.identity_tokens.filter_by(enabled=True))
        return render_template('index.html', identity_tokens=identity_tokens)
Пример #25
0
def login():
    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('panel'))
    form = LoginForm()
    if form.validate_on_submit():
        #logging_in_user = User.objects(username=form.username.data)
        #logging_in_user = User.all().filter('username ='******'next') or url_for('panel'))
            else:
                flash('Invalid login. Please try again.', 'error')
                redirect(url_for('login'))
        else:
            flash('Invalid login. Please try again.', 'error')
            redirect(url_for('login'))
    return render_template('users/login.html',
        title='Sign In',
        form=form)
Пример #26
0
def login():
  form = LoginForm()
  if form.validate_on_submit():
    return redirect('/auth')
  return render_template('login.html',
    title = 'Sign In',
    form = form)
Пример #27
0
def user_login(request):
    if not request.user.is_anonymous():
        return HttpResponseRedirect('/')
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            username = cd['username']
            password = cd['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                if "next" in request.REQUEST:
                    return HttpResponseRedirect(request.REQUEST["next"])
                else:
                    return HttpResponseRedirect("/")
            else:
                form.errors['password'] = u"帐号验证失败!"
                context = RequestContext(request, {
                    'form': form })
                return render_to_response("login.html", context)
        else:
            context = RequestContext(request, {
                'form': form })
            return render_to_response("login.html", context)
    else:
        form = LoginForm()
        context = RequestContext(request, {
            'form': form })
        return render_to_response("login.html", context)
Пример #28
0
def login_view(request):
	mensaje = ""
	#Si el usuario se ha autenticado
	if request.user.is_authenticated():
		return HttpResponseRedirect('/')
	else:
		#Si la solicitud fue enviada...
		if request.method == "POST":
			form = LoginForm(request.POST)
			#Verificar si el formulario cumple con las condiciones de validacion
			if form.is_valid():
				#Limpia los datos ingresados de nombre de usuario y contrasena
				username = form.cleaned_data['username']
				password = form.cleaned_data['password']
				#Procede a autenticar el usuario
				usuario = authenticate(username=username,password=password)
				#Verificar si el usuario existe y si esta activo
				if usuario is not None and usuario.is_active:
					#Enviar la peticion web con el usuario autenticado
					login(request, usuario)
					return HttpResponseRedirect('/')
				#Si no se autentica el usuario
				else:
					#Mostrar un mensaje indicando los fallos
					mensaje = "Usuario y/o password incorrecto"
		form = LoginForm()
		#Envio final del formulario con datos
		ctx = {'form':form, 'mensaje':mensaje}
		#Redirecciona a la pagina del login
		return render_to_response('login.html', ctx, context_instance=RequestContext(request))
Пример #29
0
def login():
    """ Creates new user if needed. Then logs the user in. 
    Note:
        Stores phonenumber in a cookie
    
    """
    form = LoginForm()
    if request.method == "GET":
        return render_template("login.html",form=form)
    
    if form.validate_on_submit():
        #convert phonenumber to an integer
        phoneNumber = re.sub(r'[^0-9]','',str(form.number.data))
        phoneNumer = int(phoneNumber)
        
        hashPhone = hashVal(phoneNumber)
        user = newUser(hashPhone)#none if user alreay exists
        note = "Successfully Loggedin."
        
        #user is trying to generate a password
        if user == None:
            user = getUser(hashPhone)
            flash(note)
            return redirect(url_for("getCode", phoneNumber = str(phoneNumber)))
        
        #user is creating an account
        note = "New Account created for " + str(phoneNumber) + ".\n" + note
        flash(note)
    return redirect(request.args.get("next") or url_for("login"))
Пример #30
0
def login():
    error = None
    form = LoginForm()
    next = get_redirect_target()
    next = retain_before_auth_page(next)
    print request.method
    if request.method == 'POST':
        if request.form['submit'] == 'cancel':
            return redirect_back('index')
        else:
            if form.validate_on_submit():
                session['remember_me'] = True
                user = User.query.filter_by(username=form.username.data).first()
                if user:
                    if bcrypt.check_password_hash(str(user.password), str(form.password.data)):
                        login_user(user)
                        flash('You were logged in. ', 'success')
                        return redirect_back('index')
                    else:
                        flash('Invalid email or password.', 'danger')
                        return render_template('login.html', form=form, error=error)
                else:
                    flash('Invalid email or password.', 'danger')
                    return render_template('login.html', form=form, error=error, next=next)
            else:
                flash('Invalid email or password.', 'danger')
                return render_template('login.html', form=form, error=error, next=next)
    else:
        return render_template('login.html', form=form, error=error, next=next)
Пример #31
0
def login():
    form = LoginForm()
    if request.method == "POST":
        # change this to actually validate the entire form submission
        # and not just one field
        if request.method == 'POST' and form.validate_on_submit():
            # Get the username and password values from the form.

            # using your model, query database for a user based on the username
            # and password submitted
            # store the result of that query to a `user` variable so it can be
            # passed to the login_user() method.

            # get user id, load into session
        username = form.username.data
        password = form.password.data

        user = UserProfile.query.filter_by(username=username, password=password)\
        .first()

        if user is not None:
            # If the user is not blank, meaning if a user was actually found,
            # then login the user and create the user session.
            # user should be an instance of your `User` class
            login_user(user)
            
            flash('Logged in successfully.', 'success')
            next = request.args.get('next')
            return redirect(url_for('secure_page'))
        else:
            flash('Username or Password is incorrect.', 'danger')

            # remember to flash a message to the user
            return redirect(url_for("home")) # they should be redirected to a secure-page route instead
    return render_template("login.html", form=form)

# user_loader callback. This callback is used to reload the user object from
# the user ID stored in the session
@login_manager.user_loader
def load_user(id):
    return UserProfile.query.get(int(id))

@app.route("/logout")
@login_required
def logout():
    # Logout the user and end the session
    logout_user()
    flash('You have been logged out.', 'danger')
    return redirect(url_for('home'))
    
###
# The functions below should be applicable to all Flask apps.
###

@app.route('/<file_name>.txt')
def send_text_file(file_name):
    """Send your static text file."""
    file_dot_text = file_name + '.txt'
    return app.send_static_file(file_dot_text)


@app.after_request
def add_header(response):
    """
    Add headers to both force latest IE rendering engine or Chrome Frame,
    and also to cache the rendered page for 10 minutes.
    """
    response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
    response.headers['Cache-Control'] = 'public, max-age=0'
    return response


@app.errorhandler(404)
def page_not_found(error):
    """Custom 404 page."""
    return render_template('404.html'), 404


if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0",port="8080")
Пример #32
0
def login():
	form = LoginForm()
	return render_template('login.html', form=form)
Пример #33
0
def signup():
    """
    Renders the login_signup.html template and displays it to the user.
    """

    # If the user is logged in.
    if current_user.is_authenticated():
        # Redirect to the dashboard.
        return redirect(url_for('dashboard.dashboard'))

    # Create an empty error variable.
    error = None

    # Create the sign up form.
    user_signup_form = SignUpForm()

    if request.method == 'POST':
        if user_signup_form.validate_on_submit():
            # Check the email isn't already in the database.
            member = Member.query.filter_by(
                email=user_signup_form.email.data).first()
            if member is None:
                # Not in the database, sign up the user.
                # Get the current time.
                now = datetime.utcnow()

                # Try and get the auto_aprove and auto_admin configuration.
                try:
                    if app.config['AUTO_ADMIN']:
                        is_admin = 1
                    else:
                        is_admin = 0
                except KeyError:
                    is_admin = 0

                try:
                    if app.config['AUTO_APPROVE']:
                        is_active = 1
                    else:
                        is_active = 0
                except KeyError:
                    is_active = 0

                member = Member(
                    user_signup_form.firstname.data,
                    user_signup_form.surname.data, user_signup_form.email.data,
                    user_signup_form.password.data,
                    user_signup_form.gender.data, user_signup_form.height.data,
                    user_signup_form.address_line_1.data,
                    user_signup_form.city.data, user_signup_form.postcode.data,
                    now, now, is_admin, is_active)

                db.session.add(member)
                db.session.commit()

                # The ID of the new member.
                new_id = Member.query.filter_by(
                    email=user_signup_form.email.data).first().id
                # Add the users weight to the weight table.
                db.session.add(
                    Weight(user_signup_form.weight.data, now, new_id))

                # Add a welcome message.
                db.session.add(
                    Message(
                        now,
                        "Welcome to the training log! Important messages are displayed here. Click them to delete.",
                        new_id))

                # Commit the changes.
                db.session.commit()

                # Redirect them to the dashboard. (Also log them in.)
                if login_user(member):
                    # All is okay log the user in.
                    flash('Logged In')
                    # Redirect them to the dashboard page.
                    return redirect(url_for('dashboard.dashboard'))
                else:
                    # For some reason the user could not be logged in.
                    if not member.is_active():
                        # The account is not activated as account_is_active returns False (AUTO_APPROVE set to False)
                        return redirect(
                            url_for(
                                'login.login',
                                error=
                                "Before you can login, the system requires an administrator approves your account."
                            ))
                    else:
                        # Redirect them to the login page. The error will be dealt with there.
                        return redirect(url_for('login.login'))
            else:
                error = "An account is already associated with this email address."
        else:
            render_template('login_signup.html',
                            user_signup_form=user_signup_form,
                            user_login_form=LoginForm(),
                            error=error)

    # Display the sign up page.
    return render_template('login_signup.html',
                           user_signup_form=user_signup_form,
                           user_login_form=LoginForm(),
                           error=error)
Пример #34
0
def login():
    """
    Renders the login_login.html template and displays it the user.
    """

    # If the user is logged in.
    if current_user.is_authenticated():
        # Redirect to the dashboard.
        return redirect(url_for('dashboard.dashboard'))

    # Create an empty error variable.
    error = None

    # If there is anything in the URL args.
    if request.args.get('error'): error = request.args.get('error')

    # Create the login form.
    user_login_form = LoginForm()

    if request.method == 'POST':
        # If the form was submitted. (i.e. data posted to the page.)
        if user_login_form.validate_on_submit():
            # Do the user Login.
            # Query the database for a user that matches the email.
            member = Member.query.filter_by(
                email=user_login_form.email.data).first()
            if member is not None and bcrypt.check_password_hash(
                    member.password, user_login_form.password.data):
                # The user is valid.
                # Log the In.
                if login_user(member,
                              remember=bool(user_login_form.remember.data)):
                    # All is okay log the user in.
                    flash('Logged In')
                    # Update the last login date.
                    member.set_last_login_date(datetime.utcnow())
                    # Commit changes to the database.
                    db.session.commit()
                    # Due to some errors with old users not having weight data, make sure the user has added weight data.
                    if not member.weight_data:
                        # If no data was found, redirect them to the add page.
                        return redirect(
                            url_for(
                                'weight.add_weight',
                                error=
                                "You must add a weight to the database before continuing. Otherwise some applications may not work correctly."
                            ))

                    # If the user was trying to access a page before he was redirected here
                    # redirect them back to that page.
                    if request.args.get('next') and not request.args.get(
                            'next') == "/logout":
                        return redirect(request.args.get('next'))
                    else:
                        # Redirect them to the dashboard page.
                        return redirect(url_for('dashboard.dashboard'))
                else:
                    # The user cannot be logged in.
                    if not member.is_active():
                        # The account is not activated as account_is_active returns False
                        error = "Account is not active, please contact your system administrator."
                    else:
                        # Unknown error.
                        error = "Unknown error occurred, please contact your system administrator."
            else:
                # Either the user does not exist or the password doesn't match.
                # Error message left vague for security.
                error = "Invalid Credentials, Please try again."

    # Display the login_login.html page to the user.
    return render_template('login_login.html',
                           user_login_form=user_login_form,
                           error=error)
Пример #35
0
def home():
    return render_template("home.html", loginform=LoginForm(), registrationform=RegistrationForm())
Пример #36
0
def index():
    form = LoginForm()

    return render_template('index.html',
                           form=form,
                           logged_in_user=current_user)
Пример #37
0
def login():
    form = LoginForm()
    return render_template('/login.html/', title='login', form=form)
Пример #38
0
 def get(self):
     if current_user.is_authenticated:
         return redirect(url_for('index'))
     form = LoginForm()
     return make_response(
         render_template('login.html', title='Sign In', form=form))
Пример #39
0
def register():
    form = LoginForm()
    return render_template('login.html', title='Login', form=form)
Пример #40
0
 async def get(self):
     return {
         'form': LoginForm(db=self.request.app.sync_db)
     }
Пример #41
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        return redirect('index')
    return render_template('login.html', form=form)
Пример #42
0
def logout():
    form = LoginForm()
    if userinfo == None:
        return render_template('login.html', title='Login', form=form)
    session.pop('user')
    return redirect(url_for('login'))
Пример #43
0
def student_login():
    """Render page with form for student only login"""
    form = LoginForm()
    return render_template("login.html", form=form)
Пример #44
0
def login():
	form = LoginForm()
	return render_template('login.html', title='Login', form=form) #form keyword renders RegistrationForm class instance from forms.py	
Пример #45
0
def login():
    form = LoginForm()
    return render_template("login.html", title="Login", form=form)
Пример #46
0
def login(req):
    if req.method == "GET":
        fs = LoginForm()
        return render(req, "admina/login.html", {"fs": fs})
Пример #47
0
def homepage():
    """home page"""
    login_form = LoginForm()
    new_user_form = NewUserForm()

    return render_template('home.html', login_form=login_form, new_user_form=new_user_form)
Пример #48
0
def teacher_login():
    """Render page with form for teacher only login"""

    form = LoginForm()
    return render_template("login.html", form=form)
Пример #49
0
def hello():
    if session.get('user_id') is not None:
        return redirect(url_for('user_profile', user_id=session['user_id']))
    else:
        form = LoginForm()
        return render_template('login.html', title='Sign In', form=form)
Пример #50
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash(form.username.data)
        return redirect(url_for("index"))
    return render_template("login.html", form=form)
Пример #51
0
def login():
    form = LoginForm()
    user = {'username': '******'}
    return render_template('forms.html', title='Home', user=user, form=form)
Пример #52
0
def login():
    form = LoginForm()
    return render_template('login.html', title='Sign In', form=form)
Пример #53
0
def login():
	form=LoginForm()
	if form.validate_on_submit():
		flash(f'You have logged in {form.username.data}',"success")
		return redirect(url_for('home'))
	return render_template('login.html',title='Login',form=form)
Пример #54
0
def loginview(request, target):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if not form.is_valid(): # All validation rules pass
            form = LoginForm()
            context = { 'form': form, 'error': 'Invalid form' }
            return scirius_render(request, 'accounts/login.html', context)
        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)
                if not form.cleaned_data['persistent']:
                    request.session.set_expiry(0)
                return redirect("/" + target)
            else:
                form = LoginForm()
                context = { 'form': form, 'error': 'Disabled account' }
                return scirius_render(request, 'accounts/login.html', context)
        else:
            form = LoginForm()
            context = { 'form': form, 'error': 'Invalid login' }
            return scirius_render(request, 'accounts/login.html', context)
    else:
        form = LoginForm()
        context = { 'form': form }
        return scirius_render(request, 'accounts/login.html', context)
Пример #55
0
def login():
    form = LoginForm()  # initialise forms
    return render_template('index.html', form=form)  # pass form to template
Пример #56
0
def users_login():
    """shows login form"""
    return render_template('users/login.html', form=LoginForm())
Пример #57
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        print(form.email.data)
        return redirect(url_for("dashboard"))
    return render_template("login.html", form=form)
Пример #58
0
def login():
    global user
    global userInfo

    loginok = False
    form = LoginForm()

    if form.validate_on_submit():
        print(str(form.remember.data))
        print(form.username.data, form.password.data)

        # store user preference first even if login not successful
        session.permanent = form.remember.data

        '''
        Check For Special Characters As Part Of Special Characters
        '''
        for letter in form.password.data:
            for character in specialChars:
                if letter == character:
                    flash('Login Unsuccessful. Please check username and password for any special characters!', 'danger')
                    return render_template('login.html', title='Login', form=form)
        try:
            for letter in form.username.data:
                for character in specialChars:
                    if letter == character:
                        flash('Login Unsuccessful. Please check username and password for any special characters!', 'danger')
                        return render_template('login.html', title='Login', form=form)
        except:
            print(form.username.data,specialChars)
        '''
        Check If Username & Password Are Matching Pairs
        '''
        try:
            userInfo = db.execute("SELECT * FROM cognnectuser WHERE (username = :un);",{"un": form.username.data}).fetchall()
            if len(userInfo) == 0:
                raise Exception('username not found')

        except:
            print('no user exists')
            flash('Login Unsuccessful. Please check your username!', 'danger')
            return redirect(url_for('login', title='Login', form=form))
        ''' userinfo Is A Row Of Data, userinfo[0][3] Is The Password Of User'''

        try:
            print("User Info:", userInfo)
            if form.password.data == userInfo[0][4]:
                session['is_logged'] = True
                session['current_user'] = form.username.data
                session['firstname'] = userInfo[0][1]
                session['fullname'] = userInfo[0][1] + " " + userInfo[0][2]
                session['dorp'] = userInfo[0][5]
                print("User Full Name: " + session['fullname'])

                user = User()

                user.username = userInfo[0][0]
                user.email = userInfo[0][3]
                user.password = userInfo[0][4]

                message = 'You have been logged in, ' + session['firstname'] + '!'
                flash(message, 'success')
                return redirect(url_for('myaccount'))
            else:
                print('not matching')
                flash('Login Unsuccessful. Please check username and password and make sure that they are correct!', 'danger')
        except:
            print(traceback.format_exc())
            flash('Login Unsuccessful. Please check username and password and make sure that they are correct!', 'danger')
    return render_template('login.html', title='Login', form=form)
Пример #59
0
def login():
    form = LoginForm()  # login instance form
    return render_template('login.html', title='login', form=form)
Пример #60
0
def login():
    form = LoginForm()