def login(): if request.method == "GET": if session.get("user_id"): return render_template("main.html", table=session['expenses'], budget=session['budget']) return render_template("login.html") if not request.form.get("username") or not request.form.get("password"): return render_template("error.html", warning="Please fill out all fields.") db = sqlite3.connect(DB_FILE) cursor = db.cursor() cursor.execute("select * from users where username = ?", (request.form.get("username"), )) user = cursor.fetchone() db.close() if not user or not bcrypt.check_password_hash( user[3], request.form.get("password")): return render_template("error.html", warning="Incorrect username or password.") session["user_id"] = user[1] session["username"] = user[2] user_id = session["user_id"] c.execute( 'select expense_name, desc, amount, timestamp from expenses where user_id=?', (user_id, )) expenses = c.fetchall() c.execute('select budget from users where user_id=?', (user_id, )) budget = float(c.fetchone()[0]) session['budget'] = budget session['expenses'] = expenses return redirect(url_for('root'))
def post(self): users = mongo.db.usuarios correo = request.get_json()['correo'] password = request.get_json()['password'] result = "" response = users.find_one({'correo': correo}) if response: if bcrypt.check_password_hash(response['password'], password): encoded_jwt = jwt.encode( { 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=1000), 'correo': response['correo'], 'rol': response['rol'] }, KEY_TOKEN_AUTH, algorithm='HS256') return jsonify({ "Status": "Login exitoso", "token": str(encoded_jwt), 'correo': response['correo'], 'rol': response['rol'] }), 200 else: return jsonify({"error": "Invalid username and password"}), 400 else: return jsonify({"error": "Invalid username and password"}), 400 return result
def verify_password(email_token, password): if email_token == '': return False ''' In this new version, the first authentication argument can be the email address or an authentication token. If this field is blank, an anonymous user is assumed, as before. If the password is blank, then the email_or_token field is assumed to be a token and validated as such. If both fields are nonempty then regular email and password authentication is assumed To give view functions the ability to distinguish between the two authentication methods a g.token_used variable is added ''' if password == '': g.current_user = User.verify_reset_token(email_token) g.token_used = True return g.current_user is not None user = User.query.filter_by(email=email_token).first() if user is None: return False g.current_user = user g.token_used = False ''' The authentication callback saves the authenticated user in Flask’s g context variable so that the view function can access it later. In this logic we block unauthorized user (they carry empty 'strings') ''' return bcrypt.check_password_hash(password, user.password)
def login(): if 'user' in session: return redirect(url_for('dashboard')) message = None if request.method == "POST": usern = request.form.get("username") passw = request.form.get("password").encode('utf-8') result = db.execute( "SELECT * FROM accounts WHERE username = '******'".format( str(usern))).fetchone() message = "Username or password is incorrect." if result is not None: if bcrypt.check_password_hash(list(result)[2], passw) is True: session['user'] = usern return redirect(url_for('dashboard')) else: #print(message) pass message = "Username or password is incorrect." return render_template("login.html", message=message)
def login(): if request.method == "GET": if session.get("user_id"): return redirect(url_for("index")) return render_template("login.html") if not request.form.get("username") or not request.form.get("password"): return render_template("login.html", warning="Please fill out all fields.") db = sqlite3.connect(DB_FILE) cursor = db.cursor() cursor.execute("select * from users where username = ?", (request.form.get("username"), )) user = cursor.fetchone() db.close() if not user or not bcrypt.check_password_hash( user[3], request.form.get("password")): return render_template("login.html", warning="Incorrect username or password.") session["user_id"] = user[1] session["username"] = user[2] return redirect(url_for("index"))
def check_password(password: str, salt: str, password_hash: str) -> bool: """Check a password with a salt and password hash""" salted_password = password + salt password_hash = password_hash.encode() if bcrypt.check_password_hash(password_hash, salted_password): return True else: return False
def login(): usernames = request.form['username'] passwords = request.form['pass'] if usernames is None or usernames == '': return render_template('mainindex.html', error='Username is empty') if passwords is None or passwords == '': return render_template('mainindex.html', error='Password is empty') else: users = mongo.db.users login_user = users.find_one({'name': request.form['username']}) all_questions = [] all_answers = [] all_yes_reviews = [] all_no_reviews = [] if login_user: if bcrypt.check_password_hash(login_user['password'], request.form['pass']): session['username'] = request.form['username'] chatTable = mongo.db.Chat chatData = chatTable.find({'name': request.form['username']}) print(chatData) if chatData: for x in chatData: questions = x['details']['question'] answers = x['details']['answer'] reviews = x['details']['review'] all_questions.append(questions) all_answers.append(answers) if reviews == 'Yes': all_yes_reviews.append(reviews) elif reviews == 'No': all_no_reviews.append(reviews) all_questions.reverse() all_answers.reverse() yes_count = len(all_yes_reviews) no_count = len(all_no_reviews) efficiency = (int(yes_count) / (int(yes_count) + int(no_count))) * 100 efficiency = round(efficiency, 2) return render_template('index.html', message=session['username'], all_history=zip( all_questions, all_answers), yes_count=yes_count, no_count=no_count, efficiency=efficiency) else: return render_template('index.html', message=session['username'], all_history=zip( all_questions, all_answers)) return render_template('mainindex.html', error='Invalid username/password combination')
def firstreset(): form = ResetpassForm() form2 = ProfileForm() if form.validate_on_submit(): if request.method == 'POST': global a results = request.form values = list(results.values()) cursor = connection1.cursor() select = "SELECT password FROM signin where empid='" + a + "'" cursor.execute(select) results2 = cursor.fetchone() if bcrypt.check_password_hash(results2[0], values[1]): if values[2] == values[3]: if bcrypt.check_password_hash(results2[0], values[2]): flash('Old and New passwords must be different', 'danger') else: cursor = connection1.cursor() update = ( "UPDATE signin SET password =? where empid ='" + a + "'") hashed_password = bcrypt.generate_password_hash( values[2]).decode('utf-8') values = [hashed_password] cursor.execute(update, values) connection1.commit() return redirect(url_for('afterreset')) else: flash('Please enter same password in both fields', 'danger') else: flash('Incorrect Password', 'danger') return render_template('profile.html', form=form, form2=form2, mng=mng, open=True)
def login(): form = LoginForm() st = User.query.filter_by(email=form.email.data).first() if form.validate_on_submit(): if bcrypt.check_password_hash(st.password, form.password.data): flash('You have been logged in!', 'success') else: flash('Login unsussesful. Check username and password', 'danger') return redirect(url_for('home')) return render_template('login.html', title='Login', form=form)
def login(): # if 'POST', the client tries to login into his account if request.method == 'POST': db = mongo.db users = db.users # if the room name is users or roomName which is used to stored information of the user and room if request.form['roomname'].lower() == 'users' or request.form['roomname'].lower() == 'roomname': return render_template("./index.html", data="The room name is reserved!") # find the account with the username keyed by the client from the database login_user = users.find_one({'_id' : request.form['loginusername'].lower()}) # if an account is found if login_user: # compare the keyed hashed password with the account hashed password hashloginpass = bcrypt.generate_password_hash(request.form['loginpassword'].encode('utf-8')) decodepass = bcrypt.generate_password_hash(login_user['password']).decode('utf-8') # if the password matched if ((bcrypt.check_password_hash(login_user['password'], request.form['loginpassword'])) and (login_user['_id']==request.form['loginusername'].lower())): roomName = request.form['roomname'].lower() # update the room list of the client account oldRoomList = login_user['room list'] # if the client is a new user if oldRoomList is None: newRoomList = [] newRoomList.append(roomName) # client is not a new user else: oldRoomList.append(roomName) newRoomList = list(set(oldRoomList)) users.update_one({'_id' : request.form['loginusername'].lower()}, {'$set' : {'last room' : roomName, 'room list' : newRoomList}}) # update the member list of the room room = db.roomName.find_one({'room name' : roomName}) if room is None: db.roomName.insert_one({'room name' : roomName}) oldMembers = [] else: oldMembers = room['members'] oldMembers.append(request.form['loginusername'].lower()) # ensures that the member list is unique members = list(set(oldMembers)) db.roomName.update_one({'room name' : roomName}, {'$set' : {'members' : members}}) # if room name not given, default room name is 'secret' if request.form['roomname'] == '': return redirect(url_for('chat', name=request.form['loginusername'].upper(), room='Secret')) # redirect to chat room upon successful login with 2 parameters namely client name and room name return redirect(url_for('chat', name=request.form['loginusername'].upper(), room=request.form['roomname'].upper())) # if the account can't be found or the username and password not match return render_template("./index.html", data="Invalid username/password combination!") # if 'GET', display the login form return render_template('./index.html')
def login(): global players_list users = client.CardDeck.users data = request.get_json(force=True) user = users.find_one({'email': data['email']}) if players_list.count(user['name']) > 0: return response('ALREADY_AUTHENTICATED', 400) if not user: return response('EMAIL_NOT_FOUND', 400) if not bcrypt.check_password_hash(user['password'], data['password']): return response('INVALID_PASSWORD', 400) auth_token = util.encode_auth_token(str(user['_id'])) return jsonify({'token': auth_token.decode(), 'name': user['name']})
def login(): form = request.form if EMAIL_REGEX.match(form['email']): users = mysql.query_db('SELECT * FROM users WHERE email = :email', {'email': form['email']}) if len(users) > 0: user = users[0] if bcrypt.check_password_hash(user['password'], form['password']): session['current_user'] = user['id'] flash("Welcome", "success") return redirect('/success') flash('Invalid credentials. Please try again', 'errors') return redirect('/')
def login(): form = Login() if form.validate_on_submit(): username = request.form['username'] login_user = Admin.Users.find_one({'username': username}) if login_user: # hashedpwd = bcrypt.generate_password_hash(form.password.data).decode('utf-8') if bcrypt.check_password_hash(login_user['password'], form.password.data): #if bcrypt.(request.form['pass'].encode('utf-8'), login_user['password']) == login_user['password']: session['username'] = request.form['username'] flash('Logined Succesful ', "success") return redirect(url_for('index')) return render_template('login.html', form=form)
def login(): 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') if next_page: return redirect(next_page) else: return redirect('riddles') return render_template('login.html', title='Login', form=form)
def changePassword(): try: db = mongo.db.Login_Details newpassword = bcrypt.generate_password_hash(request.get_json()['newPass']).decode('utf') oldpassword = request.get_json()['oldPass'] user = request.get_json()['user'] response = db.find_one({'email' : user}, {"password": 1}) if bcrypt.check_password_hash(response['password'], oldpassword): status = db.update_one({"email" : user},{"$set": { "password" : newpassword }}) return jsonify({"result" : "Password Updated Successfully"}) else: return jsonify({"result" : "Same Password"}) except Exception: return 'error'
def authenticate(cls, username, password): """Find user with `username` and `password`. It searches for a user whose password hash matches this password and, if it finds such a user, returns that user object. If can't find matching user (or if password is wrong), returns False. """ user = cls.query.filter_by(username=username).first() if user: is_auth = bcrypt.check_password_hash(user.password, password) if is_auth: return user return False
def login(): login_data = request.get_json() email_address, password = login_data['email_address'], login_data['password'] data = dict() logging.debug("API login, received data: {} {}".format(email_address, password)) # Searches for the particular user in the users mongo database login_user = users_collection.find_one({'email_address': email_address}) if login_user is not None: logging.debug('password: {}'.format(password.encode('utf-8'))) logging.debug('hash: {}'.format(login_user.password_hash)) # bcrypt validation for the enterred password compared to the stored hash if bcrypt.check_password_hash(password.encode('utf-8'), login_user.password_hash.encode('utf-8')): data['result'] = {'success': True, 'email_address': email_address} data['error'] = None else: data['result'] = {'success': False} data['error'] = "Example Error Message" return jsonify(data)
def login(): users = mongo.db.Login_Details email = request.get_json()['email'] password = request.get_json()['password'] cat = request.get_json()['cat'] result = "" response = users.find_one({'email' : email}) if response: if bcrypt.check_password_hash(response['password'], password) and (response['cat'] == cat): access_token = create_access_token(identity = { 'email': response['email'], 'cat' : response['cat'] }) result = jsonify({"token": access_token}) else: result = jsonify({"error": "Invalid username and password"}) else: result = jsonify({"result" : "No results found"}) return result
def user_login(): form_pwd = request.form.get('user_password') form_username = request.form.get('user_username') unhashed_pwd = form_pwd.strip() this_user = form_username.strip() user_log = mongo.db.Users.find_one({"Username": this_user}) if user_log: if bcrypt.check_password_hash(user_log["Password"], unhashed_pwd): loginuser = User(user_log) login_user(loginuser, remember=True) session['user'] = this_user return redirect(url_for('user_profile')) else: flash('The login credentials do not match our records') flash('(Note: username and password are case sensitive)') else: flash('The login credentials do not match our records') flash('(Note: username and password are case sensitive)') return render_template('index.html')
def login(): users = mongo.db.users user = request.get_json()['User Name'] password = request.get_json()['time'] result = "" response = users.find_one({'User Name': user}) if response: if bcrypt.check_password_hash(response['time'], password): access_token = create_access_token( identity={ 'name': response['name'], 'your_name': response['your_name'], 'email': response['email'] }) result = jsonify({'token': access_token}) else: result = jsonify({"error": "Invalid username and password"}) else: result = jsonify({"result": "No results found"}) return result
def login(): form = LoginForm() if form.validate_on_submit(): email = form.email.data unhashedPassword = form.password.data hashedPassword = db.getPassword(email) print("PASSWORDS", file=sys.stderr) print(unhashedPassword, file=sys.stderr) print(hashedPassword, file=sys.stderr) if bcrypt.check_password_hash(hashedPassword[0].decode(), unhashedPassword): signedIn = User(email) login_user(signedIn) return redirect(url_for('browse')) else: flash( 'Incorrect login information. Try again or register for an account', 'error') return redirect(url_for('login')) return render_template('login.html', title='Login', form=form)
def login(): email = request.form['email_l'] pw = request.form['password_l'] bool = True if len(email) == 0 or len(pw) ==0: flash('Fil shit Out ') bool = False if bool: user = mysql.fetch("SELECT * FROM users WHERE email = '{}' limit 1".format(pw)) if(len(user) > 0): if user[0]: #there was no email, so user is a list [] if bcrypt.check_password_hash(user[0]['password'], pw): session['user_id'] = user[0]['id'] session['first_name'] = user[0]['first_name'] print session else: flash("Nope") # print EMAIL_REGEX.match(user) # print password_regex.match(pw) # # print "ok" # # else: # # print "nahh" return redirect('/wall')
def login(): global a, results1, mng form = LoginForm() if form.validate_on_submit(): if request.method == 'POST': cursor = connection1.cursor() select = "SELECT * FROM signin WHERE empid=?" name1 = form.name.data global a, mng a = name1 # pass1 = form.password.data cursor.execute(select, [name1]) results = cursor.fetchone() if results != None: mng = results[2] password = results[1] if name1 in results and bcrypt.check_password_hash( password, form.password.data): session['user'] = True select1 = "select * from profile where empid ='" + name1 + "'" cursor.execute(select1) results1 = cursor.fetchone() if results1 != None: if mng != None: return redirect(url_for('dashboard')) else: return redirect(url_for('dashboard1')) else: return redirect(url_for('profile')) else: flash('Invalid username or password', 'danger') return redirect(url_for('login')) else: flash("Employee doesn't exists", 'danger') return redirect(url_for('login')) return render_template('login.html', form=form)
def login_validate(): email = request.form.get('email') password_entered = request.form.get('password') cursor = connection.cursor() data = cursor.execute( """SELECT * FROM `Users` WHERE `Email_ID` LIKE '{}'""".format(email)) if data > 0: user = cursor.fetchone() password = user['Password'] if bcrypt.check_password_hash(password, password_entered): print('password') session["login"] = True session['email'] = user['Email_ID'] session['userid'] = user['User_ID'] return redirect(url_for('index')) cursor.close() else: return render_template('login.html') else: return render_template('login.html')
def validate_formPassword(self, password): if bcrypt.check_password_hash(self.__FindUser().password, password.data) == False: raise ValidationError(password.data)
def check_password(self, value): """Check password.""" return bcrypt.check_password_hash(self.password, value)
def check_password(self, value): return bcrypt.check_password_hash(self.password, value)
def check_password(self, password): return bcrypt.check_password_hash(self.password, password)
def check_password(self, password): """ 验证密码 """ return bcrypt.check_password_hash(self.password, password)
def test_check_password(self): # Test given password is correct after unhashing user = User.queary.filter_by(email='*****@*****.**').first() self.assertTrue(bcrypt.check_password_hash( user.password, 'admin_user')) self.assertFail(bcrypt.check_password_hash(user.password, 'foobar'))
def login(): # error = None #isauthenticated = False if request.method == 'POST': checkuserspecial = request.form['username'] if not (regex.search(checkuserspecial) == None): flash('Username has special Characters bro, try again.') return redirect(url_for('login')) enc_pass = bcrypt.generate_password_hash(request.form['password']) inputuser = request.form['username'] myuser = db.session.query(Userinfo).filter( Userinfo.myusername == inputuser).first() if myuser is None: enc_pass_a = None else: enc_pass_a = bcrypt.check_password_hash(myuser.mypassword, request.form['password']) print(request.form['password'], enc_pass, enc_pass_a) if enc_pass_a is None: flash('Username or Password is invalid', 'error') print(request.form['password'], enc_pass, enc_pass_a) return redirect(url_for('login')) if enc_pass_a is False: flash('Username or Password is invalid', 'error') print(request.form['password'], enc_pass, enc_pass_a) return redirect(url_for('login')) #print(myuser) #print(request.form['password'],enc_pass,enc_pass_a) registered_user = Userinfo.query.filter_by( myusername=request.form['username'], twofactorbro=request.form['twoFactor']).first() if registered_user is None: flash('Username or Password is invalid', 'error') return redirect(url_for('login')) login_user(registered_user) currettime = datetime.now() #currettime=str(currettime) full = "%Y-%m-%d %H:%M:%S.%f" myfmt = "%Y-%m-%d %H:%M:%S" #currettime=datetime.strptime(currettime, full) update_logs = logstime(loggeduser=request.form['username'], lastlogintime=datetime.now()) db.session.add(update_logs) db.session.commit() print(update_logs) flash('Logged in successfully') '''with open('Login.txt', 'r') as file: for line in file: userN, passW, twoF = line.strip().split(',') # print("", userN,passW,twoF) # print("", request.form['username'],request.form['password'],request.form['twoFactor']) if userN == request.form['username']: if passW == request.form['password']: if twoF == '': flash('Logged in successfully') return render_template('login.html') if twoF == request.form['twoFactor']: flash('Logged in successfully') #isauthenticated = True session['auth'] = True return render_template('login.html') #return redirect(url_for('spell_check')) elif twoF != request.form['twoFactor']: flash('Two-factor failure') session['auth'] = False return render_template('login.html') if not ((userN == request.form['username']) and (passW == request.form['password'])): flash('Incorrect') session['auth'] = False''' return render_template('login.html')