Exemplo n.º 1
0
def login():
    pass
    # from datetime import timedelta
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        #  检查  user ,和密码

        user = User.query.filter_by(email=form.email.data).first()

        if user and user.check_passwd(form.password.data):
            # check password
            # 一次性cookie
            login_user(user, remember=True)
            # login_user(user,remember=True,duration=timedelta(seconds=10))
            logger.info('login  success.')

            next = request.args.get('next')
            logger.info(f"next: {next}")

            if not next or next.startswith('wwww'):
                return redirect(url_for('web.index'))

            return redirect(next)
        else:
            flash('用户名或密码错误!')
            pass
    return render_template('auth/login.html', form=form)
Exemplo n.º 2
0
def log_in(request):
    if request.method == 'POST':
        login_form = LoginForm(data=request.POST)
        if login_form.is_valid():
            response = {}
            data = {}
            user = authenticate(username=request.POST['login_username'], password=request.POST['login_password'])
            if user:
                if user.is_active:
                    login(request, user)
                    data['url'] = "http://%s%s" % (request.get_host(), '/')
                    response['success'] = 'success'
                    response['data'] = data
                    return HttpResponse(json.dumps(response), content_type='application/json')
                else:
                    # User is not active
                    data['errors'] = ["Your Account is disabled"]
                    response['data'] = data
                    response['failed'] = 'failed'
                    return HttpResponse(json.dumps(response), content_type='application/json')

            else:
                data['errors'] = ["Invalid login information"]
                response['data'] = data
                response['failed'] = 'failed'
                return HttpResponse(json.dumps(response), content_type='application/json')
    else:
        user_form = UserForm()
        login_form = LoginForm()
        return render(request, 'public/home.html', {'user_form': user_form, 'login_form': login_form})
Exemplo n.º 3
0
def index() -> Union[Response, str]:
    """Handle the login process.

    Opened with GET:
        Check if the user is logged in. If it is, redirect to the app.
        Otherwise, render template to log in.

    Opened with POST:
        Get 'username' parameter from the POST form. Log in user of a given 'username'
        and redirect her/him to app if she/he entered valid credentials. Otherwise, show
        message that login was unsuccessful.

    Returns:
        By default, the rendered login page.
        If received valid POST form, the rendered app page.

    """
    if current_user.is_authenticated:
        return redirect(url_for('main.setup_app'))

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if is_valid_user(user, form):
            login_user(user=user, remember=form.remember)
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(
                url_for('main.setup_app'))
        else:
            flash('Login Unsuccessful. Incorrect email or password.', 'danger')

    return render_template('login.html', form=form)
Exemplo n.º 4
0
def login_route():
    if current_user.is_authenticated:
        return redirect(url_for('home.index'))

    form = LoginForm()
    if form.validate_on_submit():
        email = form.username.data
        password = form.password.data
        try:
            u = auth.sign_in_with_email_and_password(email, password)
            userID = u['localId']
            refreshToken = u['refreshToken']
            idToken = u['idToken']

            user = User(userID, idToken, refreshToken)
            login_user(user, remember=form.remember_me.data)

            flash('Login requested for user {}, remember_me={}'.format(
                form.username.data, form.remember_me.data))

            return redirect(url_for('home.index'))
        except Exception:
            flash('Invalid username or password')
            return redirect(url_for('login.login_route'))

    return render_template('login.html', title='Sign In', form=form)
Exemplo n.º 5
0
def login():
    login_form = LoginForm()
    if login_form.validate_on_submit():
        flash('Login requested for user {}, remember_me={}'.format(
            login_form.username.data, login_form.submit.data))
        return redirect('/')
    return render_template('login.html', title='Sign in', form=login_form)
Exemplo n.º 6
0
def user_login(request):
    """Log in page view in order for the user to access his account"""

    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = LoginForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data and authenticate user with processed data
            user = authenticate(username=form.cleaned_data['username'],
                                password=form.cleaned_data['password'])
            if user is not None:
                # a backend authenticated the credentials
                if user.is_active:
                    login(request, user)
                    # redirects to user's account
                    return HttpResponseRedirect('/account/')

            else:
                messages.error(request,
                               'Le pseudo ou le mot de passe est incorrect.')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = LoginForm()

    return render(request, 'app/login.html', {'form': form})
Exemplo n.º 7
0
def login():
    form = LoginForm()
    # Our form is an instance of LoginForm
    if form.validate_on_submit(
    ):  # A built in validator built in to flask-wtf.FlaskForm
        return redirect('/')
    return render_template('login.html', form=form)
Exemplo n.º 8
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        login_user(form.user)
        if 'admin' in current_user.permissions:
            return redirect(url_for('admin.index'))
        return redirect(url_for('index'))

    return render_template('public/login.html', form=form)
Exemplo n.º 9
0
    def post(self):
        form = LoginForm(request.form)
        if not form.validate_on_submit():
            save_form_to_session(request.form)
            return redirect(url_for("LoginView:show"))

        if do_login(username=form.username.data, password=form.password.data):
            return redirect(url_for("IndexView:index"))
        else:
            return redirect(url_for("LoginView:show"))
Exemplo n.º 10
0
def login_page():
    if current_user.is_authenticated:
        return redirect("/")
    form = LoginForm()
    if form.validate_on_submit():
        try:
            log_in(form.login.data, form.password.data, form.remember_me.data)
            return redirect("/")
        except InvalidLoginOrPassword as e:
            form.password.errors.append(str(e))
    return render_template("user/login.html", form=form)
Exemplo n.º 11
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)
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)
Exemplo n.º 12
0
def login():
    """登录视图"""

    # 判断用户是否为已登录状态
    # 如果用户已登录则跳转回首页
    if current_user.is_authenticated:
        return redirect(url_for('web.index'))

    # 实例化 LoginForm 表单类,并且向它传递一个参数
    # request 对象可以用来获取客户端传递的各种数据
    # request.form 就是得到前端表单中填写的数据
    # 向表单类传递 request.form 不是必须的,但是如果登录失败,用户填写的数据会保留在表单的输入框中,增加用户体验
    # 保留用户填写的数据除了要在这里传入 request.form,前端表单也需要接收,后面会提到
    form = LoginForm(request.form)

    # flask-wtf 独有的方法,它等同于下面这种写法:
    # if request.method == 'POST' and form.validate():
    if form.validate_on_submit():
        # 表单校验成功,去 admin 表中查询是否有 username 与表单 username 匹配的记录
        admin = Admin.query.filter_by(username=form.username.data).first()
        # 判断记录是否存在并判断密码是否匹配
        # check_password 是我们最开始就写好的校验密码的方法
        if admin and admin.check_password(form.password.data):

            # 配置 session 的 permanent 的值为 True
            # 使 PERMANENT_SESSION_LIFETIME 配置项生效
            session.permanent = True

            # 如果有这条记录,且密码匹配,处理代码写在这里
            # 数据校验通过,执行 login_user 方法
            # 这个方法有一个必须参数,就是登录用户的查询实例
            # remember 参数控制是否记住用户,也就是浏览器关闭之后,再次打开,是否保留登录状态
            login_user(admin, remember=form.remember.data)

            # 通过 request.args.get 获取 next 参数值
            # 自动生成的 next 参数值是一个相对链接
            # 也就是类似 `/admin` 这种形式的
            next_url = request.args.get('next')
            # 如果 next_url 没有值或者 next_url 不是以 `/` 开头的话
            # next_url 的值就等于 url_for('web.index')
            # 否则 next_url 的值就是 next 参数的值
            # url_for 方法接受视图的 endpoint 作为参数,返回的是视图的相对链接
            if not next_url or not next_url.startswith('/'):
                next_url = url_for('web.index')
            # 通过 redirect 执行重定向
            return redirect(next_url)


        else:
            # 如果数据库中没有相应的记录或者密码不匹配,处理代码写在这里
            flash('登录失败!请检查用户名或密码', 'error')
    # 渲染登录页面模板,并传递表单实例
    return render_template('login/login.html', form=form)
Exemplo n.º 13
0
def login():
    """
    Login page.
    :return: Login template.
    """
    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))

    form = LoginForm()
    if form.validate_on_submit():
        session['remember_me'] = form.remember_me.data
        return tryLogin(User.query.get(form.username.data), form.password.data)

    return render_template('login.html', title='Sign In', form=form)
Exemplo n.º 14
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('dashboard.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('auth.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('dashboard.index')
        return redirect(next_page)
    return render_template('auth/login.html', title=('Sign In'), form=form)
Exemplo n.º 15
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index_user'))
    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_hash.data):
            flash('Username atau password salah')
            return redirect(url_for('login'))
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index_user')
        return redirect(next_page)
        return redirect(url_for('index_user'))
    return render_template('user/login.html', title='Log In', form=form)
Exemplo n.º 16
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(f'No se encuentra el usuario')
            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('views/login.html', title='Login', form=form)
Exemplo n.º 17
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # se o usuario existe
        user = User.query.filter_by(email=form.email.data).first()
        if user and user.password == form.password.data:
            login_user(user)
            flash('Seja bem vindo(a) ' + current_user.name)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('getVagas'))
        else:
            flash('Informações inválidas.')
    else:
        print(form.errors)
    return render_template('usuario/login.html', form=form)
Exemplo n.º 18
0
def login():
    """login screen"""
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = SiteUser.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('home')
        return redirect(next_page)
    return render_template('login.html', title='sign in', form=form)
Exemplo n.º 19
0
def login():
    """
    Login page.
    :return: Login template.
    """
    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))

    form = LoginForm()
    if form.validate_on_submit():
        session['remember_me'] = form.remember_me.data
        return tryLogin(User.query.get(form.username.data), form.password.data)

    return render_template('login.html',
                           title='Sign In',
                           form=form)
Exemplo n.º 20
0
def login():
    """Route to the login page"""
    if current_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()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid user name or password')
            return redirect(url_for('auth.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('profile.user', nickname=user.nickname)
        return redirect(next_page)

    return render_template('login.html', title='Sign In', form=form)
Exemplo n.º 21
0
    def test_is_valid_user(self, user_1, user_2) -> None:
        with app.test_request_context():
            form = LoginForm()
            form.email.data = '*****@*****.**'
            form.password.data = 'testPassword'

        assert u.is_valid_user(user_1, form)
        assert not u.is_valid_user(user_2, form)
        assert not u.is_valid_user(None, form)
Exemplo n.º 22
0
def users_login():
    """ Login page """
    if current_user.is_authenticated():
        return redirect(url_for('index_home'))

    form = LoginForm()
    if form.validate_on_submit():
        user = User.find_by_name(form.username.data)
        if user is None or not user.is_valid_password(form.password.data):
            flash('Invalid username or password', 'danger')
        elif login_user(user, remember=form.remember.data):
            # Enable session expiration only if user hasn't chosen to be remembered.
            session.permanent = not form.remember.data
            return redirect(request.args.get('next') or url_for('index_home'))
    elif form.errors:
        flash('Invalid username or password', 'danger')

    return render_template('users/login.html', form=form)
Exemplo n.º 23
0
def login():
    form = LoginForm().validate_for_api().data_
    username = form['username']
    password = form['password']
    user = User.get_by_id(username)
    if user is None or user.password != password:
        raise AuthFailed('登录失败,用户名或密码错误')
    login_user(user, remember=False)
    raise Success('登录成功')
Exemplo n.º 24
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = Profesor.query.filter_by(email=form.email.data).first()
        if user is None:
            flash(f'No se encuentra el correo del profesor')
            return redirect(url_for('login'))
        if not user.check_password(form.password.data):
            flash(f'La clave ingresada es erronea')
            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('views/login.html', title='Login', form=form)
Exemplo n.º 25
0
def login():
    form = LoginForm()
    if request.method == 'GET':
        return render_template('login.html', form=form, page_title=lazy_gettext(u'Log in'),
        get_text=lazy_gettext)
    elif request.method == 'POST':
        if form.validate_on_submit():
            user = User.objects(username=form.username.data).first()
            if user:
                if user.password == form.password.data:
                    login_user(user)
                    return redirect('/admin')
                else:
                    form.password.errors.append("Wrong Password")
            else:
                form.username.errors.append("user doesn't exist")
        return render_template('login.html', form=form, page_title=lazy_gettext(u'Log in'),
                               get_text=lazy_gettext)
Exemplo n.º 26
0
def home(request):
    if request.method == 'POST':
        response = {}
        data = {}
        user_form = UserForm(data=request.POST)

        if user_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            user = authenticate(username=request.POST['username'],
                                password=request.POST['password'])
            login(request, user)

            data['url'] = "http://%s" % request.get_host()
            response['data'] = data
            response['success'] = 'success'

        else:
            errors = user_form.errors.as_json()
            data['errors'] = errors
            response['data'] = data
            response['failed'] = 'failed'

        return HttpResponse(json.dumps(response),
                            content_type='application/json')

    elif request.user.is_authenticated and request.user.username != '':
        if user_is_member(request.user):
            group = request.user.member.group  # get the group from the request
            group_members = Member.objects.filter(group_id=group)
            expense_form = ExpenseForm()
            expense_form.fields['pay_to'].queryset = group_members
            group_expenses = Expense.objects.filter(shared_by_id=group)
            total_expenses = 0
            for expense in group_expenses:
                total_expenses += expense.total_cost

            return render(
                request, 'dashboard.html', {
                    'expense_form': expense_form,
                    'group_expenses': group_expenses,
                    'group_members': group_members,
                    'total_expenses': total_expenses
                })

        else:
            return HttpResponseRedirect('/register')

    user_form = UserForm()
    login_form = LoginForm()
    return render(request, 'public/home.html', {
        'user_form': user_form,
        'login_form': login_form
    })
Exemplo n.º 27
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        data = form.data
        query = User.query
        user = query.filter_by(name=data['name'])
        count = user.count()
        result = query.first()
        if count == 0:
            flash("用户不存在", "error")
        if not result.verify_password(data['password']):
            flash("密码不正确", "error")
            return redirect(url_for("admin.login"))
        if request.method == "POST":
            session['name'] = data['name']
            session['id'] = result.id
            return redirect(
                request.args.get("next") or url_for("admin.article"))
    return render_template("admin/login.html", form=form)
Exemplo n.º 28
0
def login():
    if session.get('logged_in'): return redirect(url_for('index_dashboard'))
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate():
            user = User.query.filter(
                User.username == form.username.data).first()
            if user:
                if user.password == form.password.data:
                    session['logged_in'] = True
                    session['user_id'] = user.id
                    session['username'] = user.username
                    flash(f'Bem vindo, {user.username}', 'success')
                    return redirect(url_for('index_dashboard'))
                else:
                    flash('Senha incorreta', 'danger')
            else:
                flash('Usuario nao encontrado', 'danger')
    return render_template('login/index.html', form=form)
Exemplo n.º 29
0
def login():
    form = LoginForm()

    if form.validate_on_submit():
        try:
            user = User.query.filter_by(username=form.username.data).first()

            if user is None:
                raise UserNotFoundException()

            user.verify_password(form.password.data)
        except Exception:
            form.username.errors.append("Invalid credentials")
            form.password.errors.append("Invalid credentials")
        else:
            login_user(user)
            return redirect(url_for("main.list_chatrooms"))

    return render_template("auth/login.html", form=form)
Exemplo n.º 30
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    login_form = LoginForm(request.form)
    if login_form.validate_on_submit():
        user = User.query.filter_by(email=request.form["email"]).first()
        if user is None or not user.check_password(request.form["password"]):
            flash("Invalid username or password")
            return redirect(url_for("auth.login"))
        remember_me = False
        if "remember_me" in request.form:
            remember_me = True
        login_user(user, remember=remember_me)
        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)
    flash_form_errors(login_form)
    return render_template("login.html", page_title="Log in", form=login_form)
Exemplo n.º 31
0
def login():
    if current_user.is_authenticated():
        return redirect('/')

    form = LoginForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is not None and user.check_password(form.password.data):
            if login_user(user, remember=form.remember.data):
                # Enable session expiration only if user hasn't chosen to be
                # remembered.
                session.permanent = not form.remember.data
                flash(_('Logged in successfully!'), 'success')
                return redirect('/')
            else:
                flash(_('This username is disabled!'), 'error')
        else:
            flash(_('Wrong username or password!'), 'error')
    return render_template('users/login.html', version='0.1', form=form)
Exemplo n.º 32
0
def login():
    if current_user.is_authenticated():
        return redirect('/')

    form = LoginForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is not None and user.check_password(form.password.data):
            if login_user(user, remember=form.remember.data):
                # Enable session expiration only if user hasn't chosen to be
                # remembered.
                session.permanent = not form.remember.data
                flash(_('Logged in successfully!'), 'success')
                return redirect('/') 
            else:
                flash(_('This username is disabled!'), 'error')
        else:
            flash(_('Wrong username or password!'), 'error')
    return render_template('users/login.html', version=app.config['SAGEO_VERSION'], form=form) 
Exemplo n.º 33
0
def login():
    """登录视图"""
    # 如果用户已登录则跳转回首页
    if current_user.is_authenticated:
        return redirect(url_for('web.index'))

    form = LoginForm(request.form)

    if form.validate_on_submit():
        admin = Admin.query.filter_by(username=form.username.data).first()
        if admin and admin.check_password(form.password.data):
            # 使 PERMANENT_SESSION_LIFETIME 配置项生效
            session.permanent = True
            login_user(admin, remember=form.remember.data)
            # 登录后重定向,预防重定向攻击
            next_url = request.args.get('next')
            if not next_url or not next_url.startswith('/'):
                next_url = url_for('web.index')
            return redirect(next_url)
        else:
            flash('登录失败!请检查用户名或密码', 'error')
    return render_template('login/login.html', form=form)
Exemplo n.º 34
0
def log_in(request):
    if request.method == 'POST':
        login_form = LoginForm(data=request.POST)
        if login_form.is_valid():
            response = {}
            data = {}
            user = authenticate(username=request.POST['login_username'],
                                password=request.POST['login_password'])
            if user:
                if user.is_active:
                    login(request, user)
                    data['url'] = "http://%s%s" % (request.get_host(), '/')
                    response['success'] = 'success'
                    response['data'] = data
                    return HttpResponse(json.dumps(response),
                                        content_type='application/json')
                else:
                    # User is not active
                    data['errors'] = ["Your Account is disabled"]
                    response['data'] = data
                    response['failed'] = 'failed'
                    return HttpResponse(json.dumps(response),
                                        content_type='application/json')

            else:
                data['errors'] = ["Invalid login information"]
                response['data'] = data
                response['failed'] = 'failed'
                return HttpResponse(json.dumps(response),
                                    content_type='application/json')
    else:
        user_form = UserForm()
        login_form = LoginForm()
        return render(request, 'public/home.html', {
            'user_form': user_form,
            'login_form': login_form
        })