Ejemplo n.º 1
0
def login():
    form = UserLoginForm()
    if request.method == 'GET':
        return render_template('login.html', form=form)

    if request.method == 'POST':
        if form.validate_on_submit():
            username = form.username.data
            password = form.password.data
            user = User.query.filter(User.username == username).first()
            # 验证用户是否存在
            if user:
                # 验证密码
                if check_password_hash(user.password, password):
                    # 密码正确
                    # 实现登录, django中auth.login(request, user)
                    login_user(user)
                    return redirect(url_for('app.index'))
                else:
                    error = '密码错误'
                    return render_template('login.html',
                                           error=error,
                                           form=form)
            else:
                # 账号不存在
                error = '账号不存在!'
                return render_template('login.html', error=error, form=form)
        else:
            return render_template('login.html', form=form)
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = UserLoginForm()
    search_form = SearchForm()
    if form.validate_on_submit():
        user = mongo.db.users.find_one({'username': form.username.data})
        if user and User.check_password(user['password'], form.password.data):
            user_obj = User(user['username'], user['email'], user['_id'],
                            user['is_admin'])
            login_user(user_obj)
            # accesses the 'next page' query string to determine which url user wanted to visit
            # before being redirected to the login page. If no next page was given then redirects user
            # to the index page. 'url_parse.netloc' prevents malicious redirect attacks. This prevents
            #redirects by ensuring that the url is relative to the page.
            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)
        else:
            flash('Wrong username or password', 'warning')
    return render_template('loginform.html',
                           form=form,
                           search_form=search_form,
                           title='Login')
Ejemplo n.º 3
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = UserLoginForm()
    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. Please try again.""")
            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)
Ejemplo n.º 4
0
def login():
    form = UserLoginForm()
    if request.method == 'POST' and form.validate_on_submit():
        error = None
        user = User.query.filter_by(username=form.username.data).first()
        if not user:
            error = "존재하지 않는 사용자입니다."
        elif not check_password_hash(user.password, form.password.data):
            error = "비밀번호가 올바르지 않습니다."
        if error is None:
            session.clear()
            session['user_id'] = user.id
            return redirect(url_for('main.index'))
        flash(error)
    return render_template('auth/login.html', form=form)
Ejemplo n.º 5
0
def login():
    form = UserLoginForm()
    if request.method == 'POST' and form.validate_on_submit():
        error = None
        user = User.query.filter_by(email=form.email.data).first()
        if not user:
            error = "There are no matching emails."
        elif not check_password_hash(user.password, form.password.data):
            error = "incorrect password."

        if error is None:
            session.clear()
            session['user_id'] = user.email
            if user.authority_type == 1:
                session['admin_mode'] = True
            return redirect('/')
        flash(error, 'danger')
    return render_template('main/auth/login.html', form=form)
Ejemplo n.º 6
0
def user_login():
    # If user is already logged in, redirect to home page
    if current_user.is_authenticated:
        return redirect(url_for("home"))
    # UserLoginForm object from forms.py
    user_login_form = UserLoginForm()
    if user_login_form.validate_on_submit():
        user = User.query.filter_by(
            username=user_login_form.username.data).first()
        # Checks validity of username and if provided password matches username
        if (user is None) or (not user.check_password(
                user_login_form.password.data)):
            flash("Invalid username or password")
            return redirect(url_for("user_login"))
        else:
            # Login function from flask_login
            UserLoginForm().login_user(user, user_login_form.remember_me.data)
            return redirect(url_for("user_profile", username=user.username))
    return render_template("user_login_form.html",
                           title="Login",
                           form=user_login_form)
Ejemplo n.º 7
0
def login_usuario():
    if current_user.is_authenticated:
        return redirect(url_for('home'))

    form = UserLoginForm()
    if form.validate_on_submit():
        usuario = Usuario.query.filter_by(nombre=form.nombre.data).first()
        if usuario is None or not usuario.check_password(form.password.data):
            flash('Nombre de usuario o contraseña es incorrecto', 'danger')
            return redirect(url_for('login_usuario'))

        login_user(usuario, remember=form.remember_me.data)

        app.logger.info(f'{datetime.now()}: {usuario} logged in')

        flash(f'Bienvenido {usuario.nombre}!', 'success')

        next_page = request.args.get('next')

        if next_page:
            try:
                next_page = my_utils.get_last_dir_url(next_page)
                return redirect(url_for(next_page))
            except BuildError:
                app.logger.info(
                    f'{datetime.now()}: Wierd redirect: {next_page} from {current_user} - {request.remote_addr}'
                )
                return redirect(url_for('home'))
        else:
            return redirect(url_for('home'))

    return render_template('login.html',
                           barra_busqueda=True,
                           titulo='Login',
                           form=form,
                           debug=app.config['DEBUG'])
Ejemplo n.º 8
0
def user_login():
    form = UserLoginForm()

    # POST: Process the PowerToken login form.
    if form.validate_on_submit():
        username = form.username.data
        user = User.query.filter_by(username=username).first()

        # If the user has not been added to the database, add the user to the
        # database and redirect to the WEconnect login.
        if user is None:
            user = User(username=username)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for("user_wc_login", username=username))

        # If the user exists in the database, but the WEconnect (or Fitbit)
        # info isn't filled out, redirect to the WEconnect login.
        if any([not user.wc_id, not user.wc_token, not user.fb_token]):
            return redirect(url_for("user_wc_login", username=username))

        #TODO Add token expiry check here
        # If user exists in the db, but token returns an error, then login again to refresh
        if not check_wc_token_status(user.wc_id, user.wc_token):
            return redirect(url_for("user_wc_login", username=username))

        # If the user exists in the database, and the WEconnect and Fitbit info
        # is already filled out, bypass the login process.
        return redirect(url_for("user_home", username=username))

    # GET: Render the PowerToken login page.
    error = request.args.get("error")
    if error:
        return render_template("user_login.html", form=form, error=error)
    else:
        return render_template("user_login.html", form=form)
Ejemplo n.º 9
0
def tdinfo():
    dbSession = db.Session()
    userLoginForm = UserLoginForm()
    takedownTradeForm = TakedownTradeForm()
    stats = dbSession.getTDStats()

    def tdPage(userEmail):
        if userEmail is None:
            user = [None]
        else:
            uid = dbSession.getUid(userEmail)
            pname = dbSession.getPname(uid)
            tdScore = dbSession.getTakedownScore(uid)
            penaltyScore = dbSession.getPenaltyBalance(uid)
            userPenalties = dbSession.getPenalties(uid)
            userAssignments = dbSession.getUserAssignments(uid)
            assignments = []
            if userAssignments:
                for dateId in userAssignments:
                    tid = dbSession.getTid(dateId[0])
                    date = dbSession.getIsoDate(dateId[0])
                    meal = ["Lunch", "Dinner"][tid % 2]
                    day = [
                        "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
                    ][int((tid - tid % 2) / 2)]
                    assignments.append([day + " " + meal, date, dateId[0]])

            user = [pname, tdScore, penaltyScore, userPenalties, assignments]

        resp = make_response(
            render_template("tdinfo.html",
                            user=user,
                            userLoginForm=userLoginForm,
                            takedownTradeForm=takedownTradeForm,
                            stats=stats))

        if userEmail:
            resp.set_cookie("userEmail", userEmail)

        dbSession.close()
        return resp

    if userLoginForm.submit.data and userLoginForm.validate_on_submit():
        userEmail = userLoginForm.email.data
        dbSession.close()
        return tdPage(userEmail)

    if takedownTradeForm.submitData.data and takedownTradeForm.validate_on_submit(
    ):
        userEmail = takedownTradeForm.email.data
        uid = dbSession.getUid(userEmail)
        dateId = takedownTradeForm.dateId.data
        tid = dbSession.getTid(dateId)
        traders = dbSession.getAvailibility(tid)
        mail.TakedownTradeMessage(uid, dateId, traders)
        dbSession.close()
        return tdPage(userEmail)

    try:
        userEmail = request.cookies.get("userEmail")
        # dbSession.close()
        return tdPage(userEmail)
    except Exception:
        # dbSession.close()
        return tdPage(None)
Ejemplo n.º 10
0
def user_login_attempt():
    form = UserLoginForm()
    email = request.form.get('email')
    login_ip = User.userIP()

    if form.validate_on_submit():
        if not User.check_email(email):
            message = 'Incorrect login details'
            return render_template('auth/login.html', message=message, form=form, title="Login")

        if not User.check_hashed_password(request.form.get('password'), User.get_hashed_password(email)):
            User().verificationFail(email)
            message = 'Incorrect login details'
            return render_template('auth/login.html', message=message, form=form, title="Login")            
        
        if not User.check_account_status(email): 
            generate_new_verfication_code = EmailVerification(email).verifyAccountLink()

            Emails(request.form.get('email')).newUserVerification(generate_new_verfication_code)
            
            User().updateCodeinDB(request.form.get('email'), generate_new_verfication_code, 'activation_link')

            message = 'Your account has not been verified. Another email has been sent'
            return render_template('auth/login.html', form=form, message=message, title="Login")

        if User.(email):
            if User.check_ifcheck_account_lock_lock_is_expired(email):
                pass
            else:
                account_locked = Emails(email).accountLocked()
                message = 'Account Locked'
                return render_template('/auth/login.html', form=form, message=message, title="Login")
        
        if User.check_login_ip(email, login_ip):
            user_to_login = User.query.filter_by(email=email).first()
            login_user(user_to_login, remember=True)
            session['logged-in'] = True

            if current_user.get_role() == 'BUYER':
                return redirect(url_for('buyer_bp.dashboard'))
            elif current_user.get_role() == 'SELLER':
                return redirect(url_for('seller_bp.dashboard'))
            else:
                logout_user()
                return redirect('auth_bp.user_login')
        else:
            session['email'] = email
            session['ip'] = login_ip
            generate_verification_code = EmailVerification(email).emailVerificationCode()
            Emails(request.form.get('email')).sendVerificationEmail(User().userIP(), generate_verification_code)

            User.updateCodeinDB(session['email'], generate_verification_code, 'email_verification')

            return redirect(url_for('auth_bp.verify_new_ip'))

    else:
        if not User().check_form_email_validation(request.form.get('email')):
            message = 'Invalid Login Details'
            return render_template('auth/login.html', message=message, form=form, title="Login")
        
        message = 'Unknown Error Occured'
        return render_template('auth/login.html', message=message, form=form, title="Login")