Exemplo n.º 1
0
def login():
    error = ''
    if request.method == 'GET':
        form = LoginForm(None)
    else:
        # post请求验证表单
        form = LoginForm(request.form)
        if form.validate():
            # 表单验证通过验证用户信息
            username = form.data.get('username')
            password = form.data.get('password')
            # md5加密
            pwd_md5 = md5(password)
            data = fetch_one(
                'select id, nickname from userinfo where user = %s and pwd = %s',
                (username, pwd_md5))
            if not data:
                error = '用户名密码错误'
            else:
                session['user_info'] = {
                    'user_id': data['id'],
                    'nick_name': data['nickname']
                }
                return redirect('/index')
    return render_template('login.html', form=form, error=error)
Exemplo n.º 2
0
def login():
    if current_app.config.get('IS_LOCALHOST'):
        form = LoginForm()
        if form.validate_on_submit():
            # user = User.query.filter_by(username=form.username.data).first()
            user = db.session.query(User).filter(
                User.username == form.username.data).first()
            if user is not None and user.verify_password(form.password.data):
                if not user.status:
                    #禁止被禁用的用户登陆
                    flash(u'用户被禁用,请联系管理员')
                else:
                    login_user(user, form.remember_me.data)
                    record_log(
                        'login', u'用户登陆', 'current_user:{username}'.format(
                            username=current_user.username))
                    return redirect(
                        request.args.get('next') or url_for('admin.index'))
            else:
                flash(u'用户名或密码错误')
        if current_user.is_authenticated:
            return redirect(url_for('admin.index'))
        return render_template('admin/login.html', form=form)
    else:
        return redirect(current_app.config.get('OPERATOR_LOGIN'))
Exemplo n.º 3
0
    def signup(self):
        from werkzeug.security import generate_password_hash

        pprint("Auth.singup()")
        signupform = LoginForm()
        context = {"signupform": signupform}

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

            userdoc = FirestoreService().get_user(username)

            if userdoc.to_dict() is None:
                passwordhash = generate_password_hash(password)
                userdata = UserData(username, passwordhash)
                FirestoreService().user_put(userdata)
                user = UserModel(userdata)
                login_user(user)
                self.set_msg_succes("Bienvenido")
                return self.redirect("todo_list")
            else:
                self.set_msg_error("El usuario ya existe")

        return self.render("signup.html", **context)
Exemplo n.º 4
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash('Login requested for OpenID="%s", remember_me=%s' %(form.openid.data, str(form.remember_me.data)))
        return redirect("/index/")

    return render_template("login.html", title="Sign In", form=form, providers=app.config["OPENID_PROVIDERS"])
Exemplo n.º 5
0
def login():
    """Route for handling user login.

    Args:
        None
    Returns:
        A JSON response with the JWT if the user is succesfully logged in
        and a 200 response code.
        If the user data is invalid or not found, a 401 response is
        returned
    """
    # Initialize form form object and temporarily disable csrf
    form = LoginForm(meta={'csrf': False})

    # Send CSRF token on get requests
    # if request.method == 'GET':
    #   return make_response({'csrf_token': generate_csrf()}, 200)

    # Initialize username and password to none, to prevent undefined error
    username = None
    password = None
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data

    # Check if the fields were successfully recieved, if not return a 401
    if username is None or password is None:
        return make_response(
            {'error': 'Username or password fields are empty'}, 401)

    user = UserModel.query.filter_by(username=username).first()

    # Return a 401 if no user is found
    if user is None:
        return abort(
            make_response(
                {"error": 'Could not verify user, the user does not exist'},
                401))

    # Verify user password
    if user.check_password(password) is True:
        expiry_time = app.config.get('JWT_ACCESS_LIFESPAN').get('hours')

        # Generate the JWT Token
        token = jwt.encode(
            {
                'id': user.id,
                'exp': datetime.utcnow() + timedelta(hours=expiry_time),
            },
            app.config.get('SECRET_KEY'),
            algorithm="HS256")

        return make_response(
            jsonify({
                'message': 'Login Successful',
                'token': token
            }), 200)
    else:
        return make_response({'error': 'Incorrect password'}, 401)
Exemplo n.º 6
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(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)
        return redirect(url_for('home'))
    return render_template('login.html', title='Sign In', form=form)
Exemplo n.º 7
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('stocks.index'))
    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):
            login_user(user, remember=form.remember.data)
            flash('Logged in successfully', 'alert-success')
            return redirect(url_for('stocks.index'))
        else:
            flash('Log in failed, check your email or password', 'alert-danger')

    return render_template('stocks/login.html', form=form)
Exemplo n.º 8
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and user.check_password(form.password.data):
            flash('You have successfully logged in', 'success')
            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('Login Unsuccessful!! Please check email and password',
                  'danger')
    return render_template('login.html', title='login', form=form)
Exemplo n.º 9
0
def login():
    form = LoginForm(request.form)
    form = form.validate_for_api()
    4 / 0
    # 表单验证通过验证用户信息
    username = form.data.get('username')
    password = form.data.get('password')
    # md5加密
    pwd_md5 = md5(password)
    data = fetch_one(
        'select id, nickname from userinfo where user = %s and pwd = %s',
        (username, pwd_md5))
    if data:
        return Success()
    else:
        return AuthFailed()
Exemplo n.º 10
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('admin.index'))
    form = LoginForm()
    if form.validate_on_submit():
        u = form.username.data
        p = form.password.data
        remember = form.remember_me.data
        app.logger.debug('login {}, {} remember = {}'.format(u, p, remember))
        user = User.query.filter_by(username=u).first()
        if user is not None:
            if verify_password(u, p):
                login_user(user, remember=remember)
                app.logger.debug("Hi {}".format(current_user.name))
                return redirect(url_for('admin.index'))
        else:
            flash('Invalid username or password.')
    return render_template('login.html', title='Sign In', form=form)
Exemplo n.º 11
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('signup'))
    form = LoginForm()
    if form.validate_on_submit():
        student = Student.query.filter_by(username=form.username.data).first()
        if student and bc.check_password_hash(student.password,
                                              form.password.data):
            login_user(student)
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(
                url_for('signup'))
        else:
            flash('Bad login. Check username and/or password.', 'danger')
    return render_template('login.html',
                           title='Login',
                           form=form,
                           debug=app.debug)
Exemplo n.º 12
0
def index():
    if current_user.is_authenticated:
        return redirect(url_for('dashboard'))
    else:
        form = LoginForm(request.form)
        if form.validate_on_submit():
            user = User.query.filter_by(email=form.email.data).first()
            if user and check_password_hash(user.password, form.password.data):
                user.authenticated = True
                try:
                    db.session.add(user)
                    db.session.commit()
                except:
                    return redirect(url_for('index'))
                login_user(user, remember=True)
                return redirect(url_for('dashboard'))
            flash('Email or password you entered is invalid', 'error')
        return render_template("login.html", form=form)
Exemplo n.º 13
0
def login():
    if g.user is not None and g.user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first_or_404()
        session['remember_me'] = form.remember_me.data

        if user.is_correct_password(form.password.data):
            login_user(user)
            return redirect(url_for('member_center', nickname=user.nickname))
        else:
            flash(sting_utf8('登录失败!'))
            return redirect(url_for('login'))

    return render_template('member/login.html',
                           title=sting_utf8('登录'),
                           form=form,
                           providers=app.config['OPENID_PROVIDERS'])
Exemplo n.º 14
0
 def get_context_data(self, **kwargs):
     common = CommonView(self)
     context = super(LoginView, self).get_context_data(**kwargs)
     context['common'] = common.infos
     if self.request.session.get('message'):
         context['message'] = self.request.session['message']
         del self.request.session['message']
     context['titre'] = _(u'Login')
     context['form'] = LoginForm()
     return context
Exemplo n.º 15
0
def login():
    # if already logged in redirect to homepage
    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()
        login_user(user, remember=form.remember_me.data)
        db_tools.add_login_record()
        session['payment_due'] = None

        # return regular users to homepage; staff users to admin page
        if user.is_regular():
            return redirect(url_for('index'))
        else:
            return redirect(url_for('admin.index'))

    # render login page
    return render_template('login.html', title='EBS: Sign In', form=form)
Exemplo n.º 16
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('main.capture'))
    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('main.login'))

        login_user(user)
        g.user = user

        next_ = request.args.get('next')
        if not is_safe_url(next_):
            return abort(400)

        return redirect(next_ or url_for('main.capture'), code=301)
    return render_template('login.html', title='Sign In', form=form)
Exemplo n.º 17
0
    def login(self):
        pprint("Auth.login()")
        frmLogin = LoginForm()

        if frmLogin.validate_on_submit():
            from werkzeug.security import check_password_hash, generate_password_hash
            username = frmLogin.username.data
            passreq = frmLogin.password.data
            passhash = generate_password_hash(passreq)
            pr("username:{},password:{}".format(username, passreq),
               "los passwords")
            pr(passhash, "pass-hash")

            userdoc = FirestoreService().get_user(username)
            userdict = userdoc.to_dict()

            if userdict is not None:
                passdb = userdict["password"]
                is_passwok = check_password_hash(passdb, passreq)
                pr(passreq, "pass db")
                pr(is_passwok, "is_passok")
                # bug aqui
                if is_passwok or passdb == passreq:
                    userdata = UserData(username, passreq)
                    user = UserModel(userdata)
                    login_user(user)
                    self.set_msg_succes("Bienvenido de nuevo")
                    self.redirect("todo_list")
                else:
                    bug("La informacion no coincide")
                    self.set_msg_error("La informacion no coincide")
            else:
                bug("El usuario no existe")
                self.set_msg_error("El usuario no existe")

            return self.redirect("todo_list")

        context = {"loginform": frmLogin}
        return self.render("login.html", **context)
Exemplo n.º 18
0
def login():
    """
    Handle requests to the /login route
    Log an user in through the login form
    """
    form = LoginForm()
    if form.validate_on_submit():

        # check whether user exists in the database and whether
        # the password entered matches the password in the database
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            # log user in
            login_user(user)

            if user.is_admin:
                return redirect(url_for('view.dashboard'))
            else:
                return redirect(url_for('view.dashboard'))
        # when login details are incorrect
        else:
            flash('Invalid email or password.')
    # load login template
    return render_template('index.html', form=form, title='Login')
Exemplo n.º 19
0
 def setUp(self):
     self.login = LoginForm()
     self.register = RegisterForm()
     self.business = BusinessForm()