コード例 #1
0
ファイル: application.py プロジェクト: nugtrio/pilot_fish
def log_in():
	if g.user is not None:
		if g.user.is_authenticated():
			flash('Already logged in')
			return redirect(url_for('person_info', id = g.user.get_id()))
	
	form = LogInForm()
	if request.method == 'POST':
		if form.validate_on_submit():
			registered_user = get_person_by_id(form.PersonID.data, form.Password.data)
			if registered_user is None:
				flash('Username or Password is invalid' , 'error')
				return redirect(url_for('log_in'))
				
			if not registered_user.is_authenticated:
				flash('Please wait for an ADMIN to accept your sign up' , 'error')
				return redirect(url_for('log_in'))
				
			login_user(registered_user)
			flash('Logged in successfully')
			return redirect(url_for('home'))
		
	return render_template('log_in.html', 
		title = 'Log In',
		form = form)
コード例 #2
0
ファイル: app.py プロジェクト: OlhaBerenchuk/coursework2211
def login():
    form = LogInForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            email = form.email.data
            password = sha256(str(
                form.password.data).encode('utf-8')).hexdigest()
            user = User.query.filter_by(user_email=email).first()
            if user:
                current_password = user.user_password
                if current_password != password:
                    return render_template('error.html',
                                           message='Password is wrong!',
                                           user=None)
                login_user(user)
                return redirect('/')
            else:
                return render_template('error.html',
                                       message='User does not exist!',
                                       user=None,
                                       form=form)
        return render_template('error.html',
                               message='Something is wrong',
                               user=None)
    return render_template('login.html', message=' ', user=None, form=form)
コード例 #3
0
ファイル: views.py プロジェクト: nitish1995/InstaClone
def login_view(request):
    getform = LogInForm()
    if request.method == "POST":
        form = LogInForm(request.POST)
        if form.is_valid():
            #fetching the form details..................................................................................
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = UserModel.objects.filter(username = username).first()
            if user:
                #authenticating user and creating session...............................................................
                if check_password(password,user.password):
                    token = SessionToken(user=user)
                    token.create_token()
                    token.save()

                    response = redirect('feed/')
                    response.set_cookie(key='session_token', value=token.session_token)
                    return response
                else:
                    message = "Wrong Password."
                    return render(request, 'login.html', {'form':getform,"login_error":message})
            else:
                message = "User does not exist."
                return render(request, 'login.html', {'form':getform,"login_error":message})
        #handling form error............................................................................................
        else:
            errors = form.errors
            return render(request, 'login.html', {'form':getform,"errors":errors})


    return render(request, 'login.html', {'form': getform})
コード例 #4
0
ファイル: app.py プロジェクト: jj12321/websiter
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'))
    return render_template("login.html", title = "Log In", form = form)
コード例 #5
0
ファイル: flaskblog.py プロジェクト: Joes-BitGit/atom_test
def login():
    form = LogInForm()
    if form.validate_on_submit():
        if form.email.data == '*****@*****.**' and form.password.data == 'password':
            flash(f'You have been logged in as admin!', 'success')
            return redirect(url_for('home'))
        else:
            flash(f"Login Unsuccessful. Please check username and password", 'danger')
    return render_template('login.html', title='Login', form=form)
コード例 #6
0
ファイル: app.py プロジェクト: NoamElbaum/Flask-Login
def login():
    form = LogInForm()
    result = {}
    if form.is_submitted():
        result = request.form
        if str(result["username"]) == 'noam' and str(
                result["password"]) == '1234':
            return render_template('User.html', result=result)
        else:
            return 'invalid username or password'
    return render_template('LogIn.html', form=form)
コード例 #7
0
ファイル: main.py プロジェクト: PALWolfOS/Gym-Routine
def login():
    form = LogInForm()
    if form.validate_on_submit():
        data = request.form
        user = User.query.filter_by(username=data['username']).first()
        if user and user.check_password(data['password']):
            flash('Logged in successfully.')
            login_user(user)
            return redirect(url_for('index'))
        else:
            flash('Invalid username or password')
            return redirect(url_for('login'))
    return render_template("registration/login.html", form=form)
コード例 #8
0
ファイル: app.py プロジェクト: jacobyan0/SERMOS
def login():
    form = LogInForm()
    if form.is_submitted():
        password = form.password.data
        # connect database and check password
        db = get_db()
        cur = db.cursor()
        cur.execute('SELECT * FROM password')
        for p in cur:
            psw = p[0]
        if bcrypt.check_password_hash(bcrypt.generate_password_hash(psw),
                                      password):
            return redirect(url_for('equity1'))
    return render_template("login.html", form=form)
コード例 #9
0
def login():
    form = LogInForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user:
            if check_password_hash(user.password, form.password.data):
                login_user(user, remember=form.remember.data)
                return redirect(
                    request.args.get("next") or url_for('blogposts'))

        return '<h1>Invalid Username or Password</h1>'

    return render_template('login.html', form=form)
コード例 #10
0
ファイル: main.py プロジェクト: aidanjames/aidan-blog
def login():
    form = LogInForm()
    if form.validate_on_submit():
        user = db.session.query(User).filter_by(email=form.email.data).first()
        if not user:
            flash("Email not registered, please try again.")
            return redirect(url_for("login"))
        elif not check_password_hash(user.password, form.password.data):
            flash("Invalid password, please try again.")
            return redirect(url_for("login"))
        else:
            login_user(user)
            return redirect(url_for("get_all_posts"))

    return render_template("login.html", form=form, current_user=current_user)
コード例 #11
0
ファイル: app.py プロジェクト: mo-op/TransactionAnalyser
def adminPage():
    '''
	1. Number of logins/ users. 
	2. Number of requests.
	3. Data spread across clusters.
	'''
    form = LogInForm()
    global login_count_u
    global login_count_a
    global login_count_b
    global request_count
    if request.method == 'POST':
        login_count_a += 1
        request_count += 1
        #a very secure set of credentials
        num_users = 3
        #for each user
        num_log_in = [login_count_a, login_count_b, login_count_u]
        num_request = request_count
        return render_template('admin.html',
                               num_users=num_users,
                               num_log_in=num_log_in,
                               num_request=num_request)

    else:
        return render_template('admin.html', form=form)

    return render_template('admin.html', form=form)
コード例 #12
0
def login():

    form = LogInForm()

    if form.validate_on_submit():
        user = User.login(form.username.data,
                                 form.password.data)

        if user:
            do_login(user)
            flash(f"Hello, {user.username}!", "success")
            return redirect("/")

        flash("Invalid credentials.", 'danger')

    return render_template('login.html', form=form)
コード例 #13
0
def login_user():
    form = LogInForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data

        user = User.authenticate(username, password)
        if user:
            flash(f'Welcome Back, {user.username}!', 'primary')
            session['username'] = user.username
            return redirect(
                url_for('display_user', username=session['username']))
        else:
            form.username.errors = ['Invalid username/password']

    return render_template('login.html', form=form)
コード例 #14
0
ファイル: app.py プロジェクト: khl1956/coursework1601
def signup():
    form = SignUpForm()
    form_login = LogInForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            email = form.email.data
            username = form.username.data
            password = sha256_decode(form.password.data)
            confirm_password = sha256_decode(form.confirm_password.data)
            if is_password_correct(password, confirm_password):
                try:
                    user = User(user_email=email, user_username=username, user_password=password)
                    db.session.commit()
                except Exception as e:
                    print(e)
                    return render_template('login.html',
                                           message=f'Try to log in, because user with email {email} does exist.',
                                           user=None, form=form_login)
                else:
                    try:
                        msg = Message(f"Hello, {username}!", sender="*****@*****.**", recipients=[email])
                        mail.send(msg)
                    except Exception as e:
                        print(e)
                    return redirect(url_for('login'))
    return render_template('signup.html', user=None, form=form)
コード例 #15
0
def login():
    form = LogInForm()

    if request.method == 'GET':
        return render_template('login.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            try:
                conn = mysql.connect()
                cursor = conn.cursor()
                cursor.callproc('ValidateLogin', (form.email.data, ))
                rv = cursor.fetchall()

            finally:
                conn.commit()
                conn.close()
                print len(rv)
                if len(rv) != 0:

                    if check_password_hash(str(rv[0][2]), form.password.data):
                        voter = Voter(rv[0][0], rv[0][1])
                        login_user(voter)
                        return redirect(url_for('showAGMs'))
                    else:
                        return "Wrong password"
                else:
                    return "user doesn't exist"

        else:
            return "form not validated"
    else:
        return "form not validated"
コード例 #16
0
ファイル: views.py プロジェクト: jonnyp9/flasktaskr
def login():
    error = None
    form = LogInForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            user = User.query.filter_by(name=request.form['name']).first()
            if user is not None and user.password == request.form['password']:
                session['logged_in'] = True
                session['user_id'] = user.id
                session['role'] = user.role
                flash('Welcome!')
                return redirect(url_for('tasks'))
            else:
                error = 'Invalid username or password'
        #else:
        #   error = 'Both fields are required.'
    return render_template('login.html', form=form, error=error)
コード例 #17
0
def user_login():
    ''' Render login page or login user'''
    form = LogInForm()

    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        
        user = User.authenticate(username, password)
        if user:
            session['username'] = user.username
            return redirect(f'/users/{user.username}')
        else:
            form.username.errors = ['Invalid username/password']

    
    return render_template('login.html', form = form)
コード例 #18
0
ファイル: main.py プロジェクト: rivelez65/my-blog_Flask
def login():
    form = LogInForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            if check_password_hash(user.password, form.password.data):
                login_user(user)
                return redirect(url_for('get_all_posts'))
            else:
                flash("Wrong Password, Try Again")
                return redirect(url_for('login'))
        else:
            flash(
                "This email is not registered yet.\nYou are invited to register!"
            )
            return redirect(url_for('login'))
    return render_template("login.html", form=form, current_user=current_user)
コード例 #19
0
ファイル: views.py プロジェクト: olegkovalov/library
 def post(self):
     if 'logout' in request.form:
         f_session.pop('nickname', None)
         flash('You have been logged out')
         return redirect(url_for('index'))
     form = LogInForm()
     if form.validate():
         u = session.query(User).filter_by(nickname=form.nickname.data).first()
         if u is not None and u.check_password(form.password.data):
             f_session['nickname'] = u.nickname
             msg = 'Wellcome <strong class=badge>{0}</strong>!'.format(u.nickname)
             flash(msg)
             return redirect(url_for('index'))
         else:
             flash('Wrong nickname or password')
             return redirect(url_for('index'))
     return render_template('login.haml', form=form)
コード例 #20
0
ファイル: main.py プロジェクト: aidanjames/ecommerce-site
def login():
    form = LogInForm()
    if form.validate_on_submit():
        customer = db.session.query(Customer).filter_by(
            email=form.email.data).first()
        if not customer:
            flash(
                "Email not registered, please try again or register for a new account.",
                "error")
            return redirect(url_for("login"))
        elif not check_password_hash(customer.password, form.password.data):
            flash("Invalid password, please try again.", "error")
            return redirect(url_for("login"))
        else:
            login_user(customer)
            return redirect(url_for("product_page"))

    return render_template("login.html", form=form, current_user=current_user)
コード例 #21
0
ファイル: server.py プロジェクト: Zandrenel/Soen-287
def processLogIn():
    form = LogInForm()
    if form.validate_on_submit():
        print('Started')
        _user = request.form['username']
        _pass = request.form['password']
        if (findUser(_user)
                and bcrypt.checkpw(_pass.encode('utf-8'),
                                   (returnUser(_user))[1].encode('utf-8'))):
            print('users match')
            session['Admin'] = returnUser(_user)[3]
            session['username'] = _user
            print('Log in Sucess')
            return redirect('/')
        else:
            print('logInFailed')
            return redirect("/LogIn")
            raise ("Could not Log In.")
コード例 #22
0
def validate_login():
    """ show the registration form for user """
    form = LogInForm()

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

        user = User.authenticate(username, password)

        if user:
            session["user_id"] = user.username

            return redirect(f"/users/{user.username}")

        else:
            form.username.errors = ["Bad name/password"]
            return redirect("/login")
コード例 #23
0
def login():
    # Login isnt working
    form = LogInForm()
    if form.validate_on_submit():
        email = form.email.data
        password = form.password.data
        user = User.query.filter_by(email=email).first()
        # Email doesn't exist or password is incorrect.
        if not user:
            flash("That email does not exist, please try again.")
            return redirect(url_for('login'))
        elif not check_password_hash(user.password, password):
            flash('Password incorrect, please try again.')
            return redirect(url_for('login'))
        else:
            login_user(user)
            return redirect(url_for('cafes'))
    return render_template("login.html", form=form, current_user=current_user)
コード例 #24
0
ファイル: app.py プロジェクト: kmalfatti/game-exchange
def login():
  form = LogInForm()
  error = None
  if request.method == 'POST':
    if form.validate_on_submit():
      user = User.query.filter_by(username=request.form['username']).first()
      if user:
        is_authenticated = bcrypt.check_password_hash(user.password, form.password.data)
        if is_authenticated:
          flash('Welcome back, '+user.username+'!')
          login_user(user)
          session['logged_in'] = True
          return redirect(url_for('show', id=user.id))
        else:
          error = "Invalid Username/Password"
      else:
        error = "Invalid Username/Password"
  return render_template('login.html', form=form, error=error)
コード例 #25
0
ファイル: app.py プロジェクト: khl1956/coursework1601
def login():
    form = LogInForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            email = form.email.data
            password = sha256(str(form.password.data).encode('utf-8')).hexdigest()
            print(password)
            user = User.query.filter_by(user_email=email).first()
            if user:
                try:
                    assert user.user_password == password
                except AssertionError:
                    return render_template('login.html', message='Password is wrong!', user=None, form=form)
                else:
                    session['username'] = email
                    return redirect('/')
            else:
                return render_template('login.html', message='User does not exist!', user=None, form=form)
        return render_template('error.html', message='Something is wrong', user=None)
    return render_template('login.html', message=' ', user=None, form=form)
コード例 #26
0
def login_user():
    """Handle form for logging in users. On successful submit,
    logs user in, and redirects them to cafe list
    with flashed message. Or renders form.
    """

    form = LogInForm()

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

        user = User.authenticate(username, password)

        if user:
            do_login(user)
            flash(f"Hello, {user.get_full_name()}!")
            return redirect("/cafes")
        else:
            form.username.errors = ["Invalid credentials"]

    return render_template("/auth/login-form.html", form=form)
コード例 #27
0
ファイル: views.py プロジェクト: pawelpbm/student
def home(request):
    """View for displaying main page with login form"""
    if request.method == 'POST':
        form = LogInForm(request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)

            if user is not None:
                if user.is_active:
                    login(request, user)
                    request.session['username'] = username
                    return HttpResponseRedirect('/')
                else:
                    return render_to_response('invitation.html',  {'form': form, 'error': u'Użytkownik nieaktywny.'}, context_instance=RequestContext(request))
            else:
                return render_to_response('invitation.html',  {'form': form, 'error': u'Nieprawidłowy login lub hasło.'}, context_instance=RequestContext(request))
    else:
        form = LogInForm()

    return render_to_response('invitation.html',  {'form': form,}, context_instance=RequestContext(request))
コード例 #28
0
ファイル: app.py プロジェクト: Sebthecreator95/makeameal
def login():
    """Produce login form or handle login."""

    if "user_id" in session:
        flash("You are already logged in!", "danger")
        return redirect("/")

    form = LogInForm()

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

        user = User.authenticate(username, password)  # <User> or False
        if user:
            session["user_id"] = user.id
            return redirect("/")
        else:
            form.username.errors = ["Invalid username/password."]
            return render_template("login.html", form=form)

    return render_template("login.html", form=form)
コード例 #29
0
def login():
    form = LogInForm()
    if form.validate_on_submit():
        email = form.email.data
        password = form.password.data

        # Find user by email entered.
        user = User.query.filter_by(email=email).first()

        if not user:
            flash("That email does not exist. Try again.")
            return redirect(url_for('login'))

        elif not check_password_hash(user.password, password):
            flash("Password incorrect, please try again.")
            return redirect(url_for('login'))

        else:
            login_user(user)
            return redirect(url_for('get_all_posts'))

    return render_template("login.html", form=form, current_user=current_user)
コード例 #30
0
def login():
    """
    Loads login page, allows user to insert username and password for database
    comparison.
    If a match is found they are directed to userpage, else returned to
    login with an error message.
    """

    page_title = "Login"

    # Code suggestion for identifying cookies found at stack overflow
    # https://stackoverflow.com/questions/28925602/how-can-i-detect-whether
    # -a-variable-exists-in-flask-session/39204060
    if session.get("user") is not None:
        return redirect(url_for("home"))

    logForm = LogInForm()

    if logForm.validate_on_submit():
        existing_user = mongo.db.users.find_one(
            {"username": request.form.get("login_username").lower()})

        if existing_user:
            if check_password_hash(existing_user["password"],
                                   request.form.get("login_password")):
                session["user"] = request.form.get("login_username").lower()
                return redirect(
                    url_for("user_profile", username=session["user"]))
            else:
                flash("Incorrect Username and/or Password.")
                return redirect(url_for("login", logForm=logForm))
        else:
            flash("Incorrect Username and/or Password.")
            return redirect(url_for("login", logForm=logForm))

    return render_template("login.html",
                           logForm=logForm,
                           page_title=page_title)
コード例 #31
0
def login():
    form = LogInForm()
    if form.validate_on_submit():
        try:
            conn = cx_Oracle.connect('PROJECTDB/oracle123@localhost/XE')
            cur = conn.cursor()
            cur.execute('select * from USER_TABLE')
            data = []
            for i in cur:
                data.append(i)
            cur.close()
            conn.close()
            mail = form.user_mail.data
            passw = form.user_pass.data

            c1 = 0
            for i in data:
                c1 += 1
                for j in i:
                    if j == passw and mail == data[c1 - 1][2]:
                        #print('ok')
                        # username = data[c1 - 1][1]


                        user = data[c1 - 1][0]
                        print(user)
                        session.pop('sess_var', None)
                        session['sess_var'] = user
                        return render_template('home.html', result=session['sess_var'])


                        #return render_template('question.html')

        except:
            #session['sess_var'] = 'error'
            return render_template('notOk.html')

    return render_template('login.html', title='Login', form=form)
コード例 #32
0
ファイル: app.py プロジェクト: jepainter/MilestoneProject3
def log_user_in():
    """
    Function to load WTForm for user log in and render to html
    WTForms code adapted from Corey Shafer's tutorial found at
    https://www.youtube.com/watch?v=UIJKdCIEXUQ&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=3
    Login functionality adapted from Pretty Printed's tutorial found at
    https://www.youtube.com/watch?v=eBwhBrNbrNI
    """
    
    form = LogInForm()
    session.pop("user", None)
    if form.validate_on_submit():
        user = mongo.db.users.find_one({"email": form.email.data.lower()})
        if user is not None:
            for k, v in user.items():
                if k == "password":
                    if user and bcrypt.check_password_hash(
                            v, form.password.data):
                        flash(
                            f"Log in successful!",
                            "success")
                        session["user"] = str(user["_id"])
                        return redirect(
                            url_for(
                                'home_screen',
                                _scheme="https",
                                _external=True))
                    else:
                        flash(
                            f"Log in unsuccessful!  Check your email and password.",
                            "warning")
        else:
            flash(
                f"Log in unsuccessful!  Check your email and password.",
                "warning")
    return render_template("loginuser.html", form=form)
コード例 #33
0
ファイル: app.py プロジェクト: mo-op/TransactionAnalyser
def analystPage():
    '''
	Check the gas station most frequented so far.
	Number of users per gasstation today/ another day.
	'''
    form1 = LogInForm()
    global login_count_b
    global request_count

    if request.method == 'POST':

        login_count_b += 1
        request_count += 2
        return render_template('analyst.html', view="True")

    return render_template('analyst.html', form=form1)
コード例 #34
0
ファイル: routes.py プロジェクト: utsavpatel51/learning-flask
def LogIn():
    if 'email' in session:
        return redirect(url_for('home'))
    form = LogInForm()
    if (request.method == 'POST'):
        if (form.validate == False):
            return render_template('login.html', form=form)
        else:
            email = form.email.data
            passwd = form.passwd.data
            user = User.query.filter_by(email=email).first()
            if user is not None and user.check_passwd(passwd):
                session['email'] = form.email.data
                return redirect(url_for('home'))
            else:
                return redirect(url_for('LogIn'))
    elif (request.method == 'GET'):
        return render_template('login.html', form=form)
コード例 #35
0
def login_page(request):
    """The login view. Served from index()
    """
    User = get_user_model()

    next_page = request.GET.get('next', '/')
    c = {}
    
    if request.method == 'POST':
        form = LogInForm(request.POST)
        if form.is_valid:
            email = request.POST['email']
            p = request.POST['password']

            # We can't actually authenticate with an email address. So, we have
            # to query the User models by email address to find a username,
            # and once we have that we can use the username to log in.
            try:
                user = User.objects.get(email__iexact=email)
            except User.DoesNotExist:
                form = LogInForm()
                form.cleaned_data = {}

                form.add_error('email', "Your login information does not match our records. Try again or click 'I forgot my password' below.")
                c = dict(next=quote(next_page), form=form)
                return render(request, 'accounts/login.html', c)

            user = authenticate(username=user.username, password=p)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(next_page)
                else:
                    form = LogInForm()
                    form.cleaned_data = {}

                    form.add_error('email', "Your email address is incorrect")
                    form.add_error('password', "Your password is incorrect")
                    c = dict(next=quote(next_page), form=form)
                    return render(request, 'accounts/login.html', c)
            else:
                form = LogInForm()
                form.cleaned_data = {}

                form.add_error('email', "Your login information does not match our records. Try again or click 'I forgot my password' below.")
                c = dict(next=quote(next_page), form=form)
                return render(request, 'accounts/login.html', c)
        else:
            form = LogInForm()
            form.cleaned_data = {}

            form.add_error('email', "Please try again")
            c = dict(next=quote(next_page), form=form)
            return render(request, 'accounts/login.html', c)
    else:
        form = LogInForm()

    # TODO: Fix the else staircase, refactor this as a FormView

    # c = dict(GPLUS_ID=settings.SOCIAL_AUTH_GOOGLE_PLUS_KEY,
    #          GPLUS_SCOPE=' '.join(settings.SOCIAL_AUTH_GOOGLE_PLUS_SCOPES),
    c = dict(next=quote(next_page), form=form)
    
    return render(request, 'accounts/login.html', c)