Example #1
0
def login():
    def check_login(form):
        session = create_session()
        if not session.query(Users).filter(
                Users.email == form.email.data).first():
            return 'Нет такого email'
        else:
            return 'Неправильный пароль'

    if current_user.is_authenticated:
        return redirect('/')

    form = LoginForm()
    form.hidden_tag()

    if form.validate_on_submit():
        session = create_session()

        user = session.query(Users).filter(
            Users.email == form.email.data).first()
        if user and check_password(user.password, form.password.data):
            login_user(user, remember=form.remember_me.data)
            return redirect('/')

        return render_template('login_form.html',
                               form=form,
                               message=check_login(form))

    return render_template('login_form.html', form=form)
Example #2
0
def login():
    # login form
    form = LoginForm()

    # submit button
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        # поиск пользователя в базе данных
        sotrudnik_inf = db_sess.query(User).filter(User.email == form.email.data,
                                                   User.status == 'Сотрудник').first()
        potreb_inf = db_sess.query(User).filter(User.email == form.email.data,
                                                User.status == 'Потребитель').first()
        # если пользователь сотрудник и пороль совпадает, отправляет в лк сотрудника
        if sotrudnik_inf and sotrudnik_inf.check_password(form.password.data):
            login_user(sotrudnik_inf)
            # go home
            return redirect("/sotrudnik")
        # если пользователь потребитель и пороль совпадает, отправляет в лк потребителя
        if potreb_inf and potreb_inf.check_password(form.password.data):
            login_user(potreb_inf)
            # go home
            return redirect("/potreb")
        # user error
        return render_template('login.html',
                               message="Неправильный логин или пароль",
                               form=form)

    # return template
    return render_template('login.html', form=form)
Example #3
0
def signin():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' and form.password.data == 'adminpwd':
            return redirect(url_for('watermark'))

    return render_template('signin.html', form=form)
Example #4
0
def login():
    form = LoginForm(request.form)
    if not form.validate_on_submit():
        form = LoginForm()
        return render_template("login.html", form=form, msg="Form not valid")
    
    user = dict()
    # data and make sure to strip any accidental blank spaces.
    # Courteous and simple
    user['username'] = request.form['username'].lstrip().rstrip()
    user['password'] = request.form['password'].lstrip().rstrip()

    # if user is valid, log him in
    # of course anyone could access that page but sessions are not in the scope of this
    # assignment

    if user['username'] not in _TRIES:
        _TRIES[user['username']] = {'timestamp': datetime.datetime.now(), 'tries': 0}

    if _TRIES[user['username']]['timestamp'] < (datetime.datetime.now()-datetime.timedelta(minutes=5)):
        _TRIES[user['username']]['tries'] = 0
        _TRIES[user['username']]['timestamp'] = datetime.datetime.now()

    if _TRIES[user['username']]['tries'] >= 30:
        return render_template("login.html", msg="Too many attempts in past 5 minutes, "
                                                 "try again later", form=form)

    if check_user(user):
        _TRIES[user['username']]['tries'] = 0
        session['username'] = request.form['username'].lstrip().rstrip()
        return redirect(url_for(".logged_in_page"))
    else:
        _TRIES[user['username']]['tries'] += 1
        return render_template("login.html", msg="Invalid user name or password", form=form)
Example #5
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('web_interface.projects_view'))
    form = LoginForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            db_sess = db_session.create_session()
            email = request.form.get('email')
            password = request.form.get('password')
            user = db_sess.query(User).filter_by(email=email).first()
            if user is None or not check_password_hash(user.hashed_password,
                                                       password):
                return render_template(
                    "form.html",
                    form=form,
                    action=url_for('auth.login', next=request.endpoint),
                    title=lazy_gettext("Login"),
                    error=lazy_gettext("Wrong credentials data"))
            login_user(user, remember=True)
            return redirect_dest("/projects")
    k = {}
    if request.endpoint != "auth.login":
        k["next"] = request.endpoint
    return render_template("form.html",
                           form=form,
                           action=url_for('auth.login', **k),
                           title=lazy_gettext("Login"))
Example #6
0
def login_page():
    """"Login using email and password
    Check correctness login and password
    After that, redirect to home(/) """
    # login form
    form = LoginForm()

    # random background image 1 of 5
    bg_index = randint(0, 4)

    # submit button
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        # user search
        user = db_sess.query(UserLogin).filter(UserLogin.email == form.email.data).first()
        # check password
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            # go home
            return redirect("/profile")

        # user error
        return render_template('login.html',
                               message="Неправильный логин или пароль",
                               form=form,
                               bg_index=bg_index)

    # return template
    return render_template('login.html', title='Авторизация', form=form, bg_index=bg_index)
Example #7
0
def login():
    if current_user.is_authenticated:
        return redirect(request.args.get('next', '/'))
    form = LoginForm()
    if 'last_logins' not in flask_session:
        flask_session['last_logins'] = TEMPLATE_REMEMBER_USERS
    if form.validate_on_submit():
        login = form.login.data.strip()
        password = form.password.data.strip()
        user = session.query(User).filter(User.login == login).first()
        if user and user.check_password(password):
            if login in flask_session['last_logins']:
                flask_session['last_logins'].remove(login)
            flask_session['last_logins'].append(login)
            flask_session['last_logins'] = flask_session['last_logins'][
                -COUNT_SAVED_LOGINS:]
            flask_session.modified = True
            login_user(user, remember=REMEMBER_USER)
            return redirect(request.args.get('next', '/'))
        return render_template('login.html',
                               message="Неправильный логин или пароль",
                               form=form)
    login = request.args.get('login', '')
    form.login.data = login
    last_logins = flask_session['last_logins'][::-1]
    return render_template('login.html',
                           form=form,
                           login=login,
                           last_logins=last_logins)
Example #8
0
def login():
    login_form = LoginForm()
    if login_form.validate_on_submit():
        users = User.query.filter_by(name=login_form.name.data).all()
        if len(users) > 0 and compare_password(login_form.password.data, users[0].password_hash, users[0].salt):
            login_user(users[0])
            return redirect(url_for('dashboard'))
    else:
        print('Not Validated')
    return render_template('login.html', form=login_form)
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = get_user_by_email(form.email.data)
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            return redirect('/')
        return render_template('login.html',
                               message="Wrong login or password",
                               form=form)
    return render_template('login.html', title='Authorization', form=form)
Example #10
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if not db_ops.checklogin(form.username.data, form.password.data,
                                 form.remember.data, login_user, session,
                                 sess):
            return render_template('login.html',
                                   form=form,
                                   error='Invalid username or password')
        return redirect(url_for('upload'))
    return render_template('login.html', form=form)
Example #11
0
def login():
    form = LoginForm()

    if form.validate_on_submit():  # POST
        user = server.get_user_by_name(form.name.data)
        if user and user.check_password(form.password.data):
            login_user(user)
            next_uri = request.args.get("next") or url_for("welcome")
            return redirect(next_uri)

    # GET
    return render_template("login.html", form=form)
Example #12
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter(
            and_(User.username == form.username.data,
                 User.password == hashlib.sha1(
                     form.password.data).hexdigest())).first()
        if user:
            login_user(user=user, remember=form.remember_me.data)
            return redirect('/panel')

    return render_template('login.html', form=form)
Example #13
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        user = db_sess.query(User).filter(User.email == form.email.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            return redirect("/")
        return render_template('login.html',
                               message="Неправильный логин или пароль",
                               form=form)
    return render_template('login.html', title='Авторизация', form=form)
Example #14
0
 def post(self):
     form = LoginForm()
     if form.validate_on_submit():
         user = User.query.filter_by(username=form.username.data).first()
         if user is None:
             return redirect(url_for('login'))
         elif check_password_hash(user.password, form.password.data):
             session['username'] = user.username
             print("Logged in")
             return redirect(url_for('index'))
         else:
             return redirect(url_for('login'))
Example #15
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        if not user_service.exists_by_name(form.username.data):
            flash('Nama pengguna tidak ditemukan')
        if not user_service.check_password(form.username.data, form.password.data):
            flash('Kata sandi yang dimasukkan salah')
        user = user_service.get_user_by_username(form.username.data)
        login_user(user)
        return redirect(url_for('index'))
    return render_template('login.html', login_form=form)
Example #16
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        user = db_sess.query(User).filter(
            User.email == form.email.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            return redirect("/")
        return render_template('login2.html',
                               message="Wrong login or password",
                               form=form)
    return render_template('login2.html', title='Authorization', form=form)
Example #17
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        user = db_sess.query(Users).filter(
            Users.login == form.login.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.is_remember_me.data)
            return redirect("/")
        return render_template('login.html',
                               message='Неверный логин или пароль!',
                               form=form,
                               title='Вход')
    return render_template('login.html', title='Вход', form=form)
Example #18
0
def login():
    ava = stay_ava()
    form = LoginForm()
    params = return_files(ava=ava, form=form)
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        user = db_sess.query(User).filter(User.email == form.email.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            return redirect("/")
        return render_template('login.html',
                               message="Неправильный логин или пароль",
                               **params)
    return render_template('login.html', **params)
Example #19
0
def signin():
    form = LoginForm()
    if form.validate_on_submit():
        flag = 0
        for user in db.session.query(Users).all():
            password_hash = user.password
            if form.email.data == user.email and check_password_hash(
                    password_hash, form.password.data):
                flag = 1
                login_user(user)
                return redirect(url_for('index'))
        if flag == 0:
            flash("邮箱或密码错误,请重新登录!")
            return redirect(url_for('signin'))
    return render_template('signin.html', form=form)
Example #20
0
def login():
    """Router for login page."""
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = Users.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)
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(
                url_for('home'))
        else:
            flash('Ошибка! Проверьте электронную почту или пароль.', 'danger')
    return render_template('login.html', title='Вход', form=form)
def login():
    form = LoginForm()
    if form.validate_on_submit():
        procced_user_fio = validation_user_fio(form.username.data)
        procced_user_snils = validation_user_snils(form.password.data)
        if procced_user_fio and procced_user_snils:
            if verification(procced_user_fio, procced_user_snils):
                return redirect('/home')
            return render_template("login.html",
                                   message="Неверный логин или пароль",
                                   form=form)
        return render_template("login.html",
                               message="Неверный логин или пароль",
                               form=form)
    return render_template(
        "login.html",
        title='Электронная регистратура Воронежской области',
        form=form)
Example #22
0
def render_login_page():
    login_form = LoginForm()
    if request.method == 'POST' and login_form.validate_on_submit():
        login = login_form.email.data
        password = login_form.password.data
        remember = login_form.remember.data

        user_service = UserService(current_app)
        registered_user = user_service.get_by_login(login)
        if registered_user is not None:
            if user_service.check_password_hash(registered_user.password,
                                                password):
                login_user(registered_user, remember=remember)
                return redirect('/')

    # return render_template("user/login.html", form=login_form)
    return (WebSiteHtmlView("main_blocks/main_template.html").set_title(
        'Вход на сайт').set_content('user/login.html').render(form=login_form))
Example #23
0
def login():
    """Страница входа в аккаунт пользователя."""
    if current_user.is_authenticated:
        return redirect('/logout')
    form = LoginForm()
    if form.validate_on_submit():
        session = db_session.create_session()
        user = session.query(User).filter(
            User.login == form.login.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)

            next_url = request.args.get('next')
            return redirect(next_url or '/news')
        return render_template('login.html',
                               title='Авторизация',
                               message='Неправильный логин или пароль',
                               form=form)
    return render_template('login.html', title='Авторизация', form=form)
Example #24
0
def login():
    """Функция обработки адреса /login - авторизация пользователя с помощью модели формы LoginForm"""

    form = LoginForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        user = db_sess.query(User).filter(
            User.email == form.email.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            return redirect("/")
        return render_template('login.html',
                               message="Wrong password or name",
                               form=form,
                               img=get_background())
    return render_template('login.html',
                           title='Authorisation',
                           form=form,
                           img=get_background())
Example #25
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit() and form.validate():
        session = Session(bind=engine)
        client = session.query(User, Client, Profile).select_from(User).join(Client).join(Profile).filter(
            Profile.mail == form.mail.data). \
            filter(User.check_password(Profile.password, form.password.data)).first()
        friend = session.query(User, Friend, Profile).select_from(User).join(Friend).join(Profile). \
            filter(Profile.mail == form.mail.data). \
            filter(User.check_password(Profile.password, form.password.data)).first()

        if friend is None and client is None:
            flash('Invalid username or password')
            return redirect(url_for('login'))
        user = friend if friend is not None else client
        login_user(user.User, remember=True)
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)
def login():
    '''
    ROTA DE ACESSO PARA A PÁGINA DE LOGIN DA APLICAÇÃO

    - FORMULÁRIO DE LOGIN IMPLEMENTADO PELO Flask WTF

    @autor: Luciano Gomes Vieira dos Anjos -
    @data: 27/08/2020 -
    @URL: http://localhost:5000/login - 
    @versao: 1.0.0
    '''
    form = LoginForm()
    if form.validate_on_submit():
        usuario = usuario_dao.get_login_usuario(form.login.data)
        if usuario != None and usuario.senha == form.senha.data:
            login_user(usuario)
            return redirect(url_for('form_gerenciamento_estoque'))
        flash("Usuário ou senha inválidos")
        return redirect(url_for('login'))
    return render_template('login.html', form=form)
Example #27
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('books'))

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(name=form.name.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('books')

        return redirect(next_page)

    return render_template('user/login.html', title='Sign In', form=form)
Example #28
0
def login():
    """login page"""
    if current_user.is_authenticated:
        return redirect(f'/id{current_user.id}')
    form = LoginForm()
    if form.validate_on_submit():  # sign in form
        # if password and user are correct, login the user
        user = db_sess.query(User).filter(
            User.username == form.username.data).first()
        if user and user.check_password(form.password.data):
            login_user(user, remember=form.remember_me.data)
            return redirect("/")
        return render_template(
            'login.html',
            message="Неправильное имя пользователя или пароль",
            form=form)
    return render_template('login.html',
                           title='Авторизация',
                           form=form,
                           message="")
Example #29
0
def login():
    # Используется шаблон входа их папки шаблонов
    # При входе используется форма входа, импортированная из отдельного файла
    if not current_user.is_authenticated:
        form = LoginForm()
        if form.validate_on_submit():
            db_sess = db_session.create_session()
            # Проверка на существование пользователя и правильность пароля
            user = db_sess.query(User).filter(User.email == form.email.data).first()
            if user and user.check_password(form.password.data):
                login_user(user, remember=form.remember_me.data)
                # При успешном входе пользователя перебрасывает на главную, а при неверном логине
                # или пароле сайт об этом сообщает
                return redirect("/")
            return render_template('login.html',
                                   message="Incorrect login or password",
                                   form=form)
        return render_template('login.html', deletion=False, title='Authorisation', form=form)
    else:
        abort(404)
Example #30
0
def login():
    LOGGER.info("Entering Login")

    form = LoginForm()

    if form.validate_on_submit():
        user_name = form.user_name.data
        user_password = form.user_password.data

        if User().already_exists(user_name, user_password):
            user = User().find_one_user(user_name, user_password)
            session['userId'] = user['id']
            print "******* Session user id : " + str(session['userId'])
            return render_template('user.html', title=MAIN_TITLE)

        else:
            error = unicode("Unknow user, please retry")
            return render_template('index.html', title=MAIN_TITLE, form=SignInForm(), error=error)

    else:
        return render_template('login.html', title=MAIN_TITLE, form=LoginForm())
Example #31
0
def login():
    if current_user.is_authenticated:
        return redirect('/')

    form = LoginForm()
    context = {'form': form, 'title': 'Авторизация'}
    if form.validate_on_submit():
        db_sess = create_session()
        user = db_sess.query(User).filter(
            User.email == form.email.data).first()
        if user and user.check_password(
                form.password.data) and not user.is_banned:
            login_user(user, remember=form.remember_me.data)
            return redirect('/')
        elif user and user.is_banned:
            return render_template('login.html',
                                   message='Вы заблокированны',
                                   **context)
        elif user and not user.check_password(form.password.data):
            return render_template('login.html',
                                   message='Неправильный логин или пароль',
                                   **context)
    return render_template('login.html', **context)
Example #32
0
def delete_user(id):
    # Функция удаления пользователя, его постов и комментариев
    db_sess = db_session.create_session()
    user = db_sess.query(User).filter(User.id == id).first()
    # Если такой пользователь существует, и этот пользователь и вызвал эту функцию...
    if user and user == current_user:
        form = LoginForm()
        if form.validate_on_submit():
            # Проверяем данные пользователя для подтверждения удаления
            if user and user.check_password(form.password.data) and (
                    user.email == form.email.data):
                # Удаляем все посты и связанные изображения, а также комментарии
                for post in user.posts:
                    if os.path.isfile('static/img/Posts/' + post.image) and post.image != 'Empty.png':
                        os.remove('static/img/Posts/' + post.image)
                    for comment in post.comments:
                        db_sess.delete(comment)
                    db_sess.delete(post)
                # Удаляем все комментарии, которые оставил пользователь
                for comment in user.comments:
                    db_sess.delete(comment)
                # Удаляем аватар, если он не системный
                if avatar_function(user.avatar) and os.path.isfile('static/img/Avatars/' + user.avatar):
                    os.remove('static/img/Avatars/' + user.avatar)
                # Наконец, удаляем самого пользователя
                db_sess.delete(user)
                db_sess.commit()
                return redirect("/")
            return render_template('login.html',
                                   title='Log in to delete your account',
                                   deletion=True,
                                   message="Incorrect login or password",
                                   form=form)
        return render_template('login.html', title='Log in to delete your account', deletion=True, form=form)
    else:
        # Если пользователь, которого пытаются удалить - не текущий, ошибка 404
        abort(404)