def login():
    """ Get data for the recent activity sidebar (in base.html) """
    recent = utils.get_recent_activity()
    """ If user is logged in, these routes are unnecessary and so redirect to home page """
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    """ Instantiate form """
    form = LoginForm()
    if form.validate_on_submit():
        user = db.users.find_one({'email': form.email.data})
        if user and user['password'] == form.password.data:
            user_obj = User(username=user['username'],
                            email=user['email'],
                            bio=user['bio'],
                            location=user['location'],
                            level=user['level'],
                            password=user['password'])
            login_user(user_obj, remember=form.remember.data)
            """ The following assures the user will be redirected to the page she wanted before being prompted to sign in (if prompted) """
            next_page = request.args.get('next')
            if next_page:
                return redirect(next_page)
            else:
                return redirect(url_for('home'))
        else:
            flash('Login Unsuccessful. Please check email and password',
                  'danger')
    return render_template('login.html',
                           title='Login',
                           form=form,
                           recent=recent)
Ejemplo n.º 2
0
def login():
    userIp = session.get('userIp')
    login = LoginForm()
    context = {'userIp': userIp, 'login': login}
    if (login.is_submitted()):
        username = (login.username.data).lower()
        #session['username'] =  login.username.data#request.form.get('username')
        password = login.password.data
        userDoc = getUser(username)
        if userDoc is not None:
            passwordFromDb = userDoc.to_dict()['password']
            if check_password_hash(pwhash=passwordFromDb, password=password):
                userData = UserData(username=username,
                                    password=password,
                                    id=userDoc.id,
                                    correo=userDoc.to_dict()['correo'],
                                    nombre=userDoc.to_dict()['nombre'],
                                    role=userDoc.to_dict()['role'],
                                    imagen=userDoc.to_dict()['imagen'],
                                    telefono=userDoc.to_dict()['telefono'],
                                    access=userDoc.to_dict()['access'],
                                    fechadeactualizacion=userDoc.to_dict()
                                    ['fechadeactualizacion'])
                user = UserModel(userData)
                login_user(user)
                flash('Usario: {}, Ah iniciado sesion con exito'.format(
                    user.username.title()))
                session['username'] = username
                return redirect(url_for('home'))
            else:
                flash("Contraseña incorrecta, vuelva a intentarlo.", 'error')
        else:
            flash("El usuario {}, No has sido encontrado.".format(username),
                  'error')
    return render_template('login.html', **context)
Ejemplo n.º 3
0
def login():
    notice = Notice_Post.query.all()
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()

    if form.validate_on_submit():
        user = Worker.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password,
                                               form.password.data):
            if form.email.data == '*****@*****.**' and form.password.data == 'admin':
                next_page = request.args.get('next')
                return redirect(next_page) if next_page else redirect(
                    url_for('admin'))
            else:
                login_user(user)
                next_page = request.args.get('next')
                return redirect(next_page) if next_page else redirect(
                    url_for('home'))
        else:
            flash('Login Unsuccessful. Pleach check again', 'danger')
    return render_template('login.html',
                           title='Login',
                           form=form,
                           notice=notice)
Ejemplo n.º 4
0
def auth_login(request):
    form = LoginForm()
    msg = ''
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

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

        form = LoginForm(request.POST)
        if form.is_valid():
            if user:
                login(request, user)
                response = redirect('App:index')
                # future = datetime.now() + timedelta(days=3)
                # response.set_cookie('username', json.dumps(user.username), expires=future)
                return response
            else:
                msg = '用户名或密码错误'
                return render(request, 'page-login.html', locals())
        else:
            msg = '图形验证码出错'
            return render(request, 'page-login.html', locals())

    return render(request, 'page-login.html', locals())
Ejemplo n.º 5
0
def index(request):
  form=LoginForm(request.POST)
  if form.is_valid():
    username=form.cleaned_data.get("Name")
    password=form.cleaned_data.get("Password")
    user=authenticate(username=username,password=password)
    login(request,user)
  return render(request,'facebook.html',{'form':form})
Ejemplo n.º 6
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' and form.password.data == 'password':
            flash('You have been logged in!', 'success')
            return redirect(url_for('home'))
        else:
            flash('Login Unsuccessful. Please check username and password',
                  'danger')
    return render_template('login.html', title='Login', form=form)
Ejemplo n.º 7
0
def handle_captcha(request):
    if request.method == "POST":
        form = LoginForm(request.POST, request)
        print(form)
        if form.is_valid():
            print("验证通过")
            return HttpResponse("验证通过")
        else:
            return render(request, 'app/verifycode.html', locals())
    else:
        form = LoginForm()
        return render(request, 'app/verifycode.html', locals())
Ejemplo n.º 8
0
def login():
    if current_user.is_authenticated:
        return redirect(location=url_for(endpoint='home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user and bcrypt.check_password_hash(pw_hash=user.password, password=form.password.data):
            login_user(user=user, remember=form.remember.data)
            next_page = request.args.get('next')
            flash(message="ورود شما با موفقیت انجام شد!", category='success')
            return redirect(location=next_page if next_page else url_for(endpoint='home'))
        else:
            flash(message="نام کاربری یا رمز عبور وارد شده صحیح نمیباشد!",
                  category='danger')
    return render_template(template_name_or_list='login.html', form=form)
Ejemplo n.º 9
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash(_('Invalid username or password'))
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    return render_template('login.html', title=_('Sign In'), form=form)
Ejemplo n.º 10
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password,
                                               form.password.data):
            next_page = request.args.get('next')
            login_user(user)
            flash(f'Welcome {current_user.first_name}!', 'success')
            return redirect(next_page) if next_page else redirect(
                url_for('home'))
        else:
            flash(f"Your login credentials don't match", 'danger')

    return render_template('login.html', form=form)
Ejemplo n.º 11
0
def login(request):
    # 如果是POST
    correct = 1
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            userinfo = request.POST.dict()
            user = User.objects.filter(username=userinfo.get('username'),
                                       password=userinfo.get('password'))
            if user:
                response = redirect('/')
                time = datetime.now() + timedelta(days=1)
                response.set_cookie('username', user[0].username, expires=time)
                return response
            else:
                correct = 0
        else:
            correct = 2
            form = LoginForm()
    # 如果是GET
    else:
        form = LoginForm()
    return render(request,
                  'loginb.html',
                  context={
                      'correct': correct,
                      'form': form
                  })
Ejemplo n.º 12
0
def login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        try:
            if request.POST.get('login') == '登录':

                if form.is_valid():
                    username = request.POST.get('username')
                    # print(username)
                    password = request.POST.get('password')
                    user = User.objects.get(username=username,
                                            password=password)
                    print(user)
                    # username1 = request.POST.get('username')
                    # password1 = hashlib.sha1(request.POST.get('password').encode('utf-8')).hexdigest()
                    # user1 = User.objects.get(username=username1, password=password1)
                    # print(user1)
                    # print(11111)
                    # user.password=hashlib.sha1(user.password.decode('utf-8')).hexdigest()
                    # if user or (User.objects.get(username=username,password=(hashlib.sha1(request.POST.get('password').encode('utf-8')).hexdigest()))) :
                    if user:
                        response = redirect('/blog/')
                        #设置session
                        request.session['username'] = username
                        request.session['password'] = password
                        return response

                    # elif user1:
                    #     response = redirect('/blog/')
                    #     # 设置session
                    #     request.session['username'] = username
                    #     request.session['password'] = password
                    #     return response

                else:
                    messages.error(request, '抱歉,验证码错误,请再试一次')
                    return render(request,
                                  'loginb.html',
                                  context={'form': form})
                # elif (not user) or (not form.is_valid()):
        except:
            messages.error(request, '抱歉,用户名或密码错误,请再试一次')
            return redirect('/blog/login/', locals())
    form = LoginForm()
    return render(request, 'loginb.html', locals())
Ejemplo n.º 13
0
def login(oid):
    if g.user is not None and g.user.is_authenticated:  # Flask 中的 g 全局变量是一个在请求生命周期中用来存储和共享数据。我敢肯定你猜到了,我们将登录的用户存储在这里(g)。
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        # flash('Login requested for OpenID="' + form.openid.data + '", remember_me=' + str(form.remember_me.data))
        # return redirect('/index')
        session[
            'remember_me'] = form.remember_me.data  # 当我们从登录表单获取的数据后的处理代码也是新的。这里我们做了两件事。首先,我们把 remember_me 布尔值存储到 flask 的会话中,这里别与 Flask-SQLAlchemy 中的 db.session 弄混淆。之前我们已经知道 flask.g 对象在请求整个生命周期中存储和共享数据。flask.session 提供了一个更加复杂的服务对于存储和共享数据。一旦数据存储在会话对象中,在来自同一客户端的现在和任何以后的请求都是可用的。数据保持在会话中直到会话被明确地删除。为了实现这个,Flask 为我们应用程序中每一个客户端设置不同的会话文件。
        return oid.try_login(
            form.openid.data, ask_for=['nickname', 'email']
        )  # id.try_login 被调用是为了触发用户使用 Flask-OpenID 认证。该函数有两个参数,用户在 web 表单提供的 openid 以及我们从 OpenID 提供商得到的数据项列表。因为我们已经在用户模型类中定义了 nickname 和 email,这也是我们将要从 OpenID 提供商索取的。
    return render_template(
        'login.html',
        title='Sign In',
        form=form,
        providers=Config.OPENID_PROVIDERS
    )  # OpenID 认证异步发生。如果认证成功的话,Flask-OpenID 将会调用一个注册了 oid.after_login 装饰器的函数。如果失败的话,用户将会回到登陆页面。
Ejemplo n.º 14
0
def login():
    if current_user.is_authenticated:  #already logged in ..so dont login again
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():  #checks if all reqd fields are entered?
        flash('Login requested for user {}'.format(form.username.data))
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            #checks with pass entered by input user
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=True)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            #next arg has no val in url then go to index
            next_page = url_for('index')
        return redirect(next_page)
    return render_template('login.html', title='Sign In', form=form)
Ejemplo n.º 15
0
Archivo: user.py Proyecto: Paddyy/flask
def login():
    form = LoginForm()
    # post才能进
    if form.validate_on_submit():  # 此段代码可优化,不够简洁
        #判断用户存不存在
        u = User.query.filter_by(username=form.username.data).first()
        if not u:
            flash('亲,账号或密码输错了呀~')
            return render_template('user/login.html', form=form)
        #存在在判断密码是否相等,用models里边的方法验证
        if not u.verify_password(form.password.data):
            flash('亲,账号或密码输错了呀~')
        #登录写入session
        # 此处需要用到第三方包pip install flask-login,并且在ext进行初始化,
        # 并且需要一个认证的回调函数,写在user model中
        login_user(u, remember=form.remenber.data)  #需要导入,然后看底层的东西, 记住我
        #登录成功返回首页,或者之前野蛮
        return redirect(request.args.get('next') or url_for('main.index'))
    return render_template('user/login.html', form=form)
Ejemplo n.º 16
0
Archivo: views.py Proyecto: Gcxy1/666
def login(request):
    if request.method == 'POST':
        print('*'*23)
        print(111111111)
        #使用form,对获取的数据进行过滤、判断。在进行登录操作
        forms = LoginForm(request.POST)
         # 判断forms,输入的值是否正确?
        # print(forms.phone)
        # print(forms.password)
        print(forms,type(forms))
        if forms.is_valid():
            print(333333)
             #获取前端传给forms的值
            phone = forms.cleaned_data.get('phone')
            res = redirect(reverse('index'))
            request.session['userid'] = User.objects.first().id
            request.session.set_expiry(60*60*24) #设置过期时间为一天
            print(phone)
            return res
        print(forms.errors)
        return render(request,'login.html')
    else:
        return render(request,'login.html')
Ejemplo n.º 17
0
def login_user(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)

        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            hashed_pass = generateHash(password)

            if User.objects.get(Q(email=email), Q(
                    password=hashed_pass)):  # we need to handle the exception
                user = User.objects.get(email=email)

                #if hashed_pass == user.get_pass():
                #login(request, user)
                messages.success(request, 'You are logged in')
                return redirect(reverse('products'))
            else:
                messages.error(request, 'Bad authentication')
                return redirect(reverse('login_user'))
    else:
        form = LoginForm()

    return render(request, 'Login.html', {'form': form})
Ejemplo n.º 18
0
def login(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        try:
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                auth.login(request, user)
                return render(request, 'welcome.html')
            else:
                messages.error(request,
                               "Username and Password did not matched !!")
        except auth.ObjectDoesNotExist:
            print("Invalid User")
    else:
        form = LoginForm()
    return render(request, 'login.html', {"form": form})