Beispiel #1
0
def login():
    form = LoginForm()
    if hasattr(current_user, 'login'):
        form.login.data = current_user.login
    wrong_login = False

    if form.validate_on_submit():
        user = User.query.filter_by(login=form.login.data).first()
        try:
            ldap_user = check_ldap_credentials(form.login.data, form.password.data)
        except:
            ldap_user = None
            print "Błąd połączenie z LDAP!"
        if user is not None and (pwd_context.verify(form.password.data, user.password) or ldap_user):
            if ldap_user:
                if user.display_name != ldap_user['display_name']:
                    user.display_name = ldap_user['display_name']
                    db.session.commit()
            login_user(user, remember=form.remember)
            flask.flash('Logged in successfully.')
            return form.redirect()
        else:
            wrong_login = True

    return render_template('login.html', form=form, wrong_login=wrong_login)
Beispiel #2
0
 def verify_password(self, password):
     """
     takes password and verifies if hash of it is same with hash stored in db
     :param password: input password
     :return: True if it same else False
     """
     return pwd_context.verify(password, self.password_hash)
Beispiel #3
0
 def validate_python(self, field_dict, state):
     try:
         encrypted_password = field_dict[self.field_names[0]]
     except TypeError: # Generally because field_dict isn't a dict
         raise validators.Invalid(self.message('notDict', state), field_dict, state)
     except KeyError:
         encrypted_password = None
     if encrypted_password:
         errors = {}
         for name in self.field_names[1:]:
             raw_password = field_dict.get(name)
             # Values are validated both before and after conversion, so we check to
             # see if the raw values match or if the raw password can be verified against
             # encrypted one.
             ok = False
             if raw_password == encrypted_password:
                 ok = True
             else:
                 try:
                     ok = pwd_context.verify(raw_password, encrypted_password)
                 except ValueError:
                     pass
             if not ok:
                 errors[name] = self.message('invalidNoMatch', state)
         if errors:
             error_list = errors.items()
             error_list.sort()
             lines = ['%s: %s' % (name, value) for name, value in error_list]
             raise validators.Invalid(
                 '<br>\n'.join(lines),
                 field_dict, 
                 state, 
                 error_dict=errors
             )
Beispiel #4
0
    def post(self):
        user = json.loads(self.request.body)
        user_name = user["user_name"]
        pwd = user["pass_word"]

        select_user_name = """SELECT `user_name` FROM `User` WHERE `user_name` = "%s" """\
        % (user_name)

        result = self.application.db.get(select_user_name)
        if result is None:
            self.write({"success": "unregistered-user"})
            self.finish()
            return

        select_pwd = """SELECT `password` FROM `User` WHERE `user_name` = "%s" """\
        % (user_name)
        result = self.application.db.get(select_pwd)

        if pwd_context.verify(pwd, result["password"]):
            self.write({"success": "success"})
            user["pass_word"] = "hidden"
            self.set_secure_cookie("bwitter", tornado.escape.json_encode(user))
            self.finish()
            return
        else:
            self.write({"success": "useremail-error"})
            self.finish()
            return
Beispiel #5
0
	def POST(self):
		i = web.input()
		accountinfo = json.loads(i.data)
		username = accountinfo['username']
		password = accountinfo['password']

		passwordhash = pwd_context.encrypt(password)

		with connection() as conn:
			if not "@" in username:
				queryString = r.db(RDB_CONFIG['db']).table(tables['users']).filter(r.row['username'] == username)
			else:
				queryString = r.db(RDB_CONFIG['db']).table(tables['users']).filter(r.row['email'] == username)
			findAccount = list(queryString.run(conn))
			returndata = {}
			if(len(findAccount) == 1):
				for index,item in enumerate(findAccount):
					ok = pwd_context.verify(password, item['password'])
					if(ok):
						returndata['userdata'] = {}
						returndata['userdata']['id'] = item['id']
						returndata['userdata']['username'] = item['username']
						returndata['userdata']['email'] = item['email']
						returndata['success'] = True
					else:
						returndata['error'] = {}
						returndata['error']['message'] = 'There was a problem logging in, password or username didn\'t match.'
						returndata['success'] = False
			else:
				returndata['success'] = False
				returndata['message'] = {}
				returndata['error'] = {}
				returndata['error']['message'] = 'I\'m sorry, we cannot find an account with that username';
		return json.dumps(returndata)
Beispiel #6
0
 def authenticate(cls, username, password):
     admin = Admin.query.filter_by(username=username).first()
     if admin is not None and pwd_context.verify(password, admin.password):
         login_user(admin)
         return True
     else:
         return False
Beispiel #7
0
 def authenticate(self):
     user = User.query.filter(User.account == self.account).first()
     if user is not None and pwd_context.verify(self.password, user.password):
         login_user(user)
         return True
     else:
         return False
Beispiel #8
0
def login(request):
    """Display form and handle login.

    Puts up a view with a simple login form then validates the password
    against stored sha-512 password hashes in the 'user' table.
    """
    from passlib.apps import custom_app_context as pwd_context

    session = request.dbsession
    login_url = request.route_url("login")
    referrer = request.url
    if referrer == login_url:
        referrer = "/"  # never use the login form itself as came_from
    came_from = request.params.get("came_from", referrer)
    message = ""
    login_name = ""
    password = ""
    if "form.submitted" in request.params:
        login_name = request.params["login"]
        password = request.params["password"]
        this_user = session.query(User).filter_by(loginname=login_name).first()
        if this_user and pwd_context.verify(password, this_user.password):
            headers = remember(request, login_name)
            return HTTPFound(location=came_from, headers=headers)
        message = "Failed login"
    return dict(
        message=message,
        url=request.application_url + "/login",
        came_from=came_from,
        login=login_name,
        password=password,
    )
Beispiel #9
0
def login():

    # if g.user is not None and g.user.is_authenticated:
    # 	return redirect(url_for('tickets'))

    form = LoginForm()
    if form.validate_on_submit():
        print "ok"

        # flash('Login requested for username="******", password="******"' % (form.username.data, form.password.data))

        username = form.username.data
    password = form.password.data
    if "username" in locals():
        result = models.User.query.filter_by(username=username).first()
        if result:
            password_in_db = result.password
            res = pwd_context.verify(password, password_in_db)
            if res:
                login_user(result)
                # flash('Login successful')
                print "successful login "
                return redirect(request.args.get("next") or url_for("index"))

            else:
                # flash('invalid password')
                print "failed : invalid password"
                return render_template("login.html", result="failed", form=form)

    return render_template("login.html", title="Sign in", form=form)
Beispiel #10
0
    def login(self, username, password, session_login=True):
        """
    @param username is the username of an account
    @param password is the password of an account
    @returns a single record from the database as a Storage object
    """
        log.loggit("AccountDB.login()")
        # Try to login
        account = self.review_account(username)
        if not account:
            return False
        if not pwd_context.verify(password, account["password"]):
            return False

        account = wputil.clean_account(account)
        if session_login:
            # Update the account information
            data = {}
            data["last_ip"] = web.ctx.ip
            data["last_login"] = str(int(time.time()))
            account = self._set_account_info(account, data)

            # Put account information in session key
            for key, value in account.items():
                value = str(value)
                web.ctx.session[key] = (value[:50] + "...") if len(value) > 50 else value

        return account
def authenticate_existing_user( users, form ):
    if ( 'username' in form.keys() and
            'password' in form.keys() ):
        username = form['username']
        password = form['password']
        if ( username != None and password != None ):
            user_cursor = users.find( { 'username' : username },
                    { '_id' : 0, 'password_hash' : 1 } )
            if user_cursor.count() != 0:
                return pwd.verify( password, user_cursor.next().pop( 'password_hash' ) )
                pass
            else:
                # Error : username doesn't exist
                abort( 405 )
                pass
            pass
        else:
            # Error : either username or password is None
            abort( 400 )
            pass
        pass
    else:
        # Error: Both username and password not supplied
        abort( 400 )
        pass
    pass
Beispiel #12
0
def login():
    '''This routine verifies that the user is an administrator and, if so,
    puts them in admin mode and redirects them to the admin resource they
    originally requested. It sends them back to the main page if their
    requested URL is unsafe. The username and password are stored in
    the database.
    '''
    if is_logged_in():
        return redirect(url_for('web.display_admin'))
    target_url = request.values.get('next') or url_for('web.display_admin')
    if not is_safe_url(target_url):
        return redirect(url_for('web.display_index'))
    form = Users()
    if form.is_submitted():
        # Check if the cancel button has been pressed; the form value will be
        # 'Cancel' but this doesn't need to be checked.
        if request.form.get('cancel'):
            return redirect(url_for('web.display_index'))
        if form.validate():
            user = Users.read_unit(form.nameField.data)
            if (user is not None) and \
                   (custom_app_context.verify(form.passwordField.data,
                                          user['password'])):
                session['logged_in'] = True
                return redirect(target_url)
        flash('invalid login...', 'error')
    return display_content(
        form=form,
        next=target_url,
        title='Login',
        breadcrumbs=get_breadcrumbs('login')
    )
Beispiel #13
0
 def change_password(self,old,new):
     if pwd_context.verify(old, self.Password):
         self.Password=pwd_context.encrypt(new)
         self.save()
         return True
     else:
         return False
Beispiel #14
0
 def verify_password(self, password):
     """
     arguments: password
     return True / False
     验证密码是否正确
     """
     return custom_app_context.verify(password, self.password)
 def sign_in(self, login, password):
     if self.signed_in():
         record = 'You are already signed in. Please sign out first'
         self.log_manager.log_record(record=record, category='Warning')
         return False
     user = self.session.query(User).filter(User.login == str(login)).all()
     email = self.session.query(User).filter(User.email == str(login)).all()
     if user:
         user = user[0]
     elif email:
         user = email[0]
     else:
         record = 'Login failed. Username: @%s' % str(login)
         self.log_manager.log_record(record=record, category='Warning')
         return False
     if pwd_context.verify(password, user.password_hash):
         self.user = user
         self.session_data = self._generate_session_data()
         self.session.add(self.session_data)
         self.session.commit()
         self.log_manager = LogManager(self)
         record = '@%s signed in (#%s)' % (self.user.login, self.session_data.token)
         self.log_manager.log_record(record=record, category='Information')
         self.project_manager.session_data = self.session_data
         self.project_manager.user = self.user
         return True
     else:
         record = 'Login failed. Username: @%s' % str(login)
         self.log_manager.log_record(record=record, category='Warning')
         return False
def login():
    data = request.get_json()
    user = User.query.filter_by(email=data['email']).one()
    if custom_app_context.verify(data['password'], user.pw_hash):
        session['email'] = user.email
        return jsonify({"email":user.email})
    return jsonify({"status":"error"})
Beispiel #17
0
def verify_token(username, token):
    """
    Verify validity of token
    """
    s = TimedJWSSerializer(app.config['SECRET_KEY'])

    try:
        ut.pretty_print("Trying to load the token")
        data = s.loads(token)
    except SignatureExpired:
        ut.pretty_print("ERROR: Expired Token")
        return False
    except BadSignature:
        ut.pretty_print("ERROR: Invalid Token")
        return False
    else:
        ut.pretty_print("Token successfully loaded")
        stored = db.sessions.find_one(
            filter={'username': data['username']}, sort=[('_id', -1)])

        if not stored:
            return False
        result = json_util.loads(json_util.dumps(stored))

        return pwd_context.verify(
            data['password'],
            result['password_hash']) and data['username'] == username
Beispiel #18
0
	def login(self):
		userpw = wx.GetPasswordFromUser('Enter root password', 'Root Password')
		loggedin = False
		if not isUserSet():
			conf = wx.GetPasswordFromUser('Please confirm root password', 'Root Password')
			while conf != userpw:
				print 'Passwords do not match'
				userpw = wx.GetPasswordFromUser('Enter root password', 'Root Password')				
				conf = wx.GetPasswordFromUser('Please confirm root password', 'Root Password')
			print 'Initializing user'
			password = pwd_context.encrypt(userpw)
			setUser(password)
			return True
		else:
			tries = 2
			while not loggedin:
				loggedin = pwd_context.verify(userpw, getUser())
				if not loggedin:
					print 'Wrong password'
					userpw = wx.GetPasswordFromUser('Enter root password', 'Root Password')
					tries -=1
					if tries == 0:
						self.ResetApplication()
						return False
			return True
Beispiel #19
0
def login():
    if request.method == 'GET':
        if 'username' in session:
            # logged in already
            return redirect('orders.html')
        else:
            html = '''
            <form action="%s" method="post">
                <p><input type=text name=username>
                <p><input type=password name=passwd>
                <p><input type=submit value=Login>
            </form>
            ''' % url_for('login')
            return render_template('login.html')
    elif request.method == 'POST':
        user = request.form['username']
        pwd = request.form['passwd']        
        # lookup user, hash in db
        init_resources()
        with g.db:
            application.logger.debug("logging in %s" % user)
            # get cursor and setup to close cursor on completion of suite
            with g.db.cursor() as cur:
                cur.execute("SELECT passwd from em_users WHERE username = %s", (user, ))
                row = cur.fetchone()
                hash = row[0]
                if pwd_context.verify(pwd, hash):
                    # match, set user
                    session['username'] = user
                    return redirect('orders.html')
                else:
                    # failed, redirect back to login with message
                    flash('Login failed')
                    return redirect(url_for('login'))
def login():
    """Log user in."""
    # forget any user_id
    session.clear()

    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username")

        # ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password")

        # query database for username
        rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))

        # ensure username exists and password is correct
        if len(rows) != 1 or not pwd_context.verify(request.form.get("password"), rows[0]["hash"]):
            return apology("invalid username and/or password")

        # remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # redirect user to home page
        return redirect(url_for("index"))

    # else if user reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")
Beispiel #21
0
  def login(self,
            session,
            messages,
            username,
            password):
    ''' Tries to authenticate the session.

        @param username: the name of the user to authenticate
        @param password: the password for the user
    '''

    user = self[username]

    if not user or not pwd.verify(password, user.password):
      messages.error('The username or password you entered was incorrect.')

      return False

    elif not user.active:
      messages.error('This account has not yet been activated.')

      return False

    else:
      session.username = username
      session.save()

    messages.success('Welcome, %s' % username)

    return True
Beispiel #22
0
def login():
    """Log user in."""

    # forget any user_id
    session.clear()

    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username")

        # ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password")

        # query database for username
        user = User.query.filter(User.username == request.form.get("username")).first()

        # ensure username exists and password is correct
        if user == None or not pwd_context.verify(request.form.get("password"), user.hash):
            return apology("invalid username and/or password")

        # remember which user has logged in
        session["user_id"] = user.id

        # redirect user to home page
        return redirect(url_for("index"))

    # else if user reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")
Beispiel #23
0
def private_profile():
    """
    The settings page for current_user. Here current_user may toggle suggestions, private, delete or report names,
    change about & photo with a shoddy ChangeDetailsForm, change password with an acceptable ChangePasswordForm, or
    permanently delete the account.
    :return: profile.html rendered with list of suggested names for current_user amd forms
    """
    names = Name.query.filter_by(userID=current_user.get_id()).all()

    # TODO: implement a new form to change account details you lazy trashbag
    form_d = ChangeDetailsForm(csrf_enabled=False)
    form_p = ChangePasswordForm()
    if form_p.validate_on_submit():
        if pwd_context.verify(form_p.current_password.data, current_user.password):
            user = User.query.get(current_user.id)
            user.password = pwd_context.encrypt(form_p.new_password.data)
            db.session.commit()
            flash("Changes saved.")
            return redirect(url_for("private_profile"))
        else:
            flash("Incorrect password.")
            return redirect(url_for("private_profile"))
    if form_d.validate_on_submit():
        user = User.query.get(current_user.id)
        if form_d.about.data != "":
            user.about = form_d.about.data
        app.logger.debug("result: "+user.about)
        if form_d.url.data != "":
            user.photo_url = form_d.url.data
        db.session.commit()
        flash("Changes saved.")
        return redirect(url_for("private_profile"))

    return render_template("profile.html", names=names, form_d=form_d, form_p=form_p)
Beispiel #24
0
def route_passwd():
    checklogout()

    uid = checksesval()
    if uid is None:
        return u"error: et ole kirjautunut sisään", 400

    if request.method == 'POST':
        if "new" not in request.form or len(request.form["new"]) < 6:
            flash(u"Uusi salasana ei täyttänyt vaatimuksia")
            return redirect("/passwd")
        c.execute(("SELECT * FROM sanotut_users "
                   "WHERE email = (%s)"),
                 (session["email"],))
        res = c.fetchone()
        if res == None or not pwd_context.verify(request.form.get("old", ""), res[2]):
            flash(u"Vanha salasana väärin")
            return redirect("/passwd")

        c.execute("UPDATE sanotut_users SET password = (%s) WHERE id = (%s)",
                  (pwd_context.encrypt(request.form["new"]), uid))
        db.commit()

        flash(u"Salasana vaihdettu.")
        return redirect("/")
    return render("passwd.html")
Beispiel #25
0
def old_password_check(form, field):
    """check old password input is valide"""
    old_password = field.data
    password = current_user.password
    r = pwd_context.verify(old_password, current_user.password)
    if not r:
        raise validators.ValidationError('old password is wrong')
Beispiel #26
0
def route_login():
    checklogout()
    if request.method == 'POST':
        if "email" not in request.form or "password" not in request.form:
            flash(u"Anna sposti ja salasana.")
            return redirect("/login")
        c.execute(("SELECT * FROM sanotut_users "
                   "WHERE email = (%s)"),
                 (request.form["email"],))
        res = c.fetchone()
        if res == None or not pwd_context.verify(request.form["password"], res[2]):
            flash(u"Ei moista sposti/salasana paria!")
            return redirect("/login")
        allchoice = string.lowercase + string.uppercase + string.digits
        sesval = ''.join(random.choice(allchoice) for i in range(64))

        c.execute("UPDATE sanotut_users SET session = (%s) WHERE id = (%s)",
                 (sesval, res[0],))
        db.commit()

        session["sesval"] = sesval
        session["email"] = request.form["email"]
        session["logged_in"] = True

        flash(u"Kirjauduit sisään.")
        return redirect("/")
    return render("login.html", name="login")
def loginWithRealDb(db):
        if (request.method == "POST"):
            username = request.form["username"]
            passwordHash = db.getUser(username)
            if (passwordHash == ""):
                print("No User Found")
                return badCredsHtml
            else:
                if (db.userIsLockedOut(username)[0][0]):
                    return lockedOutHtml
                else:
                    print("Checking password...")
                    if (pwd_context.verify(request.form["password"], passwordHash)):
                        db.updateNumberOfAttempts(username, 4)
                        print("password is correct!")
                        session['logged_in'] = True
                        print("logged_in set")
                        session["current_user"] = username
                        print(username + " Logged in")
                        session["friend_error"] = ""
                        return redirect("/")
                    else:
                        attempts = db.getNumberOfAttempts(username)[0][0]
                        if (attempts < 1 or attempts > 4):
                            db.lockOutUser(username)
                            db.enterLogMessage("User ~" + username + "~ is now locked out")
                        else:
                            db.updateNumberOfAttempts(username, attempts - 1)
                        print("Wrong password!!")
                        return badCredsHtml
        else:
            return loginHtml
Beispiel #28
0
def add():
    if request.method == "POST":
        if not request.form.get("passwd"):
            return apology("must provide your password")
        elif not request.form.get("login"):
            return apology("must provide a username to encrypt")
        elif not request.form.get("password"):
            return apology("must provide a password to encrypt")
        else:
            rows = db.execute("SELECT * FROM users WHERE id = :id", id=session["user_id"])
            if len(rows) != 1 or not pwd_context.verify(request.form.get("passwd"), rows[0]["hash"]):
                return apology("invalid password!!")
            else:
                login = request.form.get("login")
                password = request.form.get("password")
                passwd = request.form.get("passwd")
                comment = request.form.get("comment")
                if not login:
                    return apology("login required")
                elif not password:
                    return apology("login required")
                gnupghome = '/usr/bin/gpg'
                gpg = gnupg.GPG(gnupghome)
                afile = str(gpg.encrypt(password,
                              symmetric='AES256', passphrase=passwd, encrypt=False))
                
                db.execute("INSERT INTO portfolio (login, mfile, name, key) VALUES(:login, :mfile, :name, :key)", login=request.form.get("login"), mfile=afile, name=session["user_id"], key=comment)
                               
                return redirect(url_for("index"))
    else:
        return render_template("add.html")
Beispiel #29
0
 def verify_password(self, password):
     """
     Verify the user's password
     :param str password: The password to verify
     :return: True if the password is correct, else False
     :rtype: bool
     """
     return pwd_context.verify(password, self.password_hash)
Beispiel #30
0
    def test_edit_user_with_token_and_edit_with_valid_username_and_password(self):
        headers = {'Authentication-Token' : self.token}
        response = self.jput('/api/users/edit', data={'username': '******', 'password': '******'}, headers=headers)
        self.assertOk(response)

        user = self.get_user_from_db(id=1)
        self.assertEquals(user.username, 'jane')
        self.assertTrue(pwd_context.verify('roe', user.password))
Beispiel #31
0
 def verify_password(self, password):
     return phash.verify(password, self.password_hash)
Beispiel #32
0
def verify_password(password, hashed):
    return pwd_context.verify(password, hashed)
Beispiel #33
0
def verify_password_against_hash(password, password_hash):
    return pwd_context.verify(password, password_hash)
Beispiel #34
0
def home_page():
    events = select_all_events()
    eventList = []
    firstEvent = None
    for eventNum, eventSelect in enumerate(events):
        if eventNum == 0:  #Create event objects
            firstEvent = Events(select=eventSelect)
        else:
            eventList.append(Events(select=eventSelect))

    newList = get_all_news()
    newList = reversed(newList)

    if request.method == 'GET':
        return render_template('home/index.html',
                               firstEvent=firstEvent,
                               eventDic=eventList,
                               news=newList)
    else:
        input_mail = request.form['InputEmail']
        input_password = request.form['InputPassword']
        if input_mail in current_app.config[
                'ADMIN_USERS'] and pwd_context.verify(
                    input_password, current_app.config['PASSWORD'][0]) is True:
            user = load_user(input_mail)
            login_user(user)
            session['logged_in'] = True
            flash('You have successfully logged in!', 'user_login')
            return render_template('home/index.html',
                                   firstEvent=firstEvent,
                                   eventDic=eventList,
                                   news=newList)

        with dbapi2.connect(current_app.config['dsn']) as connection:
            cursor = connection.cursor()
            statement = """SELECT MAIL FROM USERS WHERE MAIL = %s"""
            cursor.execute(statement, [input_mail])
            db_mail = cursor.fetchone()
            if db_mail is not None:  # check whether the user exists
                user = load_user(db_mail)
                statement = """SELECT PASSWORD FROM USERS WHERE MAIL = %s"""
                cursor.execute(statement, [db_mail])
                if pwd_context.verify(input_password, user.Password) is True:
                    login_user(user)
                    session['logged_in'] = True
                    flash('You have successfully logged in!', 'user_login')
                    return render_template('home/index.html',
                                           firstEvent=firstEvent,
                                           eventDic=eventList,
                                           news=newList)
                else:
                    flash('Either mail or password is wrong!', 'user_login')
                    return render_template('home/index.html',
                                           firstEvent=firstEvent,
                                           eventDic=eventList,
                                           news=newList)  #Couldn't login
            else:
                flash('Either mail or password is wrong!', 'user_login')
                return render_template('home/index.html',
                                       firstEvent=firstEvent,
                                       eventDic=eventList,
                                       news=newList)
Beispiel #35
0
 def change_password(self, req: r.PasswordChange):
     if not pwd.verify(req.old, self.passhash):
         raise e.BadPassword(name=self.name)
     self.passhash = pwd.hash(req.n1)
     self.save()
Beispiel #36
0
 def verify_password(
     self, password
 ):  #This method is called whenever the user provides credentials and they need to be validated.
     return pwd_context.verify(password, self.password.hash)
Beispiel #37
0
def verify_password(password, password_hash):
    """ 
    compare hash password with thereof in db 
    """
    return pwd_context.verify(password, password_hash)
 def verify_password(self, password):
     """
     vérifier le mot de passe
     """
     return pwd_context.verify(password, self.password_hash)
Beispiel #39
0
def verify_password(password,password_hash):
    return pwd_context.verify(password, password_hash)
Beispiel #40
0
 def verifyPassword(self, password):
     return beepastePWD.verify(password, self.password)
Beispiel #41
0
 def verify_password(self, password):
     return custom_app_context.verify(password, self.password)
Beispiel #42
0
def pwd_verify(password, hashV):
    return pwd_context.verify(password, hashV)
Beispiel #43
0
 def verify_password(self, password):
     return pwd_context.verify(password, self.PassWord)
Beispiel #44
0
def verify_password(password1, password2):
    return pwd_context.verify(password1, password2)
Beispiel #45
0
 def verify_pass(self, password):
     return flask_user_context.verify(password, self.password)
Beispiel #46
0
 def check_password(self, password, dbpassword):
     return pwd_context.verify(password, dbpassword)
def is_authenticated(username, password):
    """Check if the user's username and password are good."""
    if username == os.environ.get('AUTH_USERNAME', ''):
        if pwd_context.verify(password, os.environ.get('AUTH_PASSWORD', '')):
            return True
    return False
Beispiel #48
0
 def verify_password(self, password):
     return pwd_context.verify(password, self.password_hash)
Beispiel #49
0
 def authenticate(self, password: str) -> bool:
     return pwd.verify(password, self.passhash)
Beispiel #50
0
def login():
    """Log user in."""

    # forget any user_id
    session.clear()
    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        action = request.form.get("action")
        if action == "login":
            # ensure username was submitted
            if not request.form.get("username"):
                flash("ERROR: You must provide a username to login",
                      "alert-danger")
                return render_template("login.html", flash=flash)

            # ensure password was submitted
            elif not request.form.get("password"):
                flash("ERROR: You must provide a password to login",
                      "alert-danger")
                return render_template("login.html", flash=flash)

            # query database for username
            rows = db.execute("SELECT * FROM users WHERE username = :username",
                              username=request.form.get("username"))

            # ensure username exists and password is correct
            if len(rows) != 1 or not pwd_context.verify(
                    request.form.get("password"), rows[0]["hash"]):
                flash("ERROR: Invalid username and/or password",
                      "alert-danger")
                return render_template("login.html", flash=flash)

            # remember which user has logged in
            session["user_id"] = rows[0]["id"]

            # redirect user to home page
            return redirect(url_for("profile"))

        elif action == "register":
            if not request.form.get("username"):
                flash(
                    "ERROR: You must provide a username: Account not registered, please try again",
                    "alert-danger")
                return render_template("login.html", flash=flash)

            #ensure that password and the re entered pass word both have content
            elif not request.form.get("password") or not request.form.get(
                    "password2"):
                flash(
                    "ERROR: You must provide a new password: Account not registered, please try again",
                    "alert-danger")
                return redirect(url_for("login"))

            #ensure that both passwords match
            elif request.form.get("password") != request.form.get("password2"):
                flash(
                    "ERROR: Passwords do not match: Account not registered, please try again",
                    "alert-danger")
                return render_template("login.html", flash=flash)

            #check to ensure username does not exist
            rows = db.execute("SELECT * FROM users WHERE username = :username",
                              username=request.form.get("username"))
            if len(rows) > 0:
                flash(
                    "ERROR: Passwords do not match: Account not registered, please try again",
                    "alert-danger")
                return render_template("login.html", flash=flash)
            else:
                #hash the password and insert the username and password into the DB
                hash = pwd_context.encrypt(request.form.get("password"))
                db.execute(
                    "INSERT INTO users (username, hash) VALUES (:username, :hash)",
                    username=request.form.get("username"),
                    hash=hash)
            flash("Account registered, please login", "alert-success")
            return render_template("login.html", flash=flash)
        # else if user reached route via GET (as by clicking a link or via redirect)
        else:
            return render_template("login.html")

    return render_template("login.html")
Beispiel #51
0
def check_passwords_equal(password, encrypted_password):
    return pwd_context.verify(password, encrypted_password)
Beispiel #52
0
def profile():
    userinfo = db.execute("SELECT * FROM users WHERE id = :user_id",
                          user_id=session["user_id"])
    users_name = userinfo[0]["username"]
    active = db.execute(
        "SELECT * FROM courses WHERE users_name = :users_name AND complete = 'false'",
        users_name=users_name)
    completed = db.execute(
        "SELECT * FROM courses WHERE users_name = :users_name AND complete = 'true'",
        users_name=users_name)

    ttlactive = len(active)
    ttlcompleted = len(completed)

    user = {}
    user["username"] = users_name
    user["firstName"] = userinfo[0]["firstName"]
    user["lastName"] = userinfo[0]["lastName"]
    user["title"] = userinfo[0]["title"]
    user["quote"] = userinfo[0]["quote"]
    user["active"] = ttlactive
    user["completed"] = ttlcompleted

    a_courses = []
    c_courses = []

    for row in active:
        course = {}
        course["name"] = row["name"]
        a_courses.append(course)

    for row in completed:
        course = {}
        course["name"] = row["name"]
        c_courses.append(course)

    if request.method == "POST":
        action = request.form.get("action")
        if action == "profedit":
            fname = request.form.get("firstName")
            lname = request.form.get("lastName")
            title = request.form.get("title")
            quote = request.form.get("quote")

            db.execute("UPDATE users SET firstName = :fname, lastName = :lname, title = :title, quote = :quote "\
            "WHERE username = :users_name", fname = fname, lname = lname, title = title, quote = quote, users_name = users_name)

            flash("Profile Updated!", "alert-success")
            return redirect(url_for("profile"))

        elif action == "passedit":
            rows = db.execute("SELECT * FROM users WHERE id = :user_id",
                              user_id=session["user_id"])

            #ensure user enters current valid password
            if not pwd_context.verify(request.form.get("curr_password"),
                                      rows[0]["hash"]):
                flash(
                    "ERROR: Current password is incorrect: Password not change, please try again",
                    "alert-danger")
                return redirect(url_for("profile"))

            #ensure the user has entered a value for both new password fields
            elif not request.form.get("newpass1") or not request.form.get(
                    "newpass2"):
                flash(
                    "ERROR: You must provide a new password: Password not change, please try again",
                    "alert-danger")
                return redirect(url_for("profile"))

            #ensure that both new passwords match
            elif request.form.get("newpass1") != request.form.get("newpass2"):
                flash(
                    "ERROR: New Passwords do not match: Password not change, please try again",
                    "alert-danger")
                return redirect(url_for("profile"))

            #hash the password and insert the username and password into the DB
            hash = pwd_context.encrypt(request.form.get("newpass1"))
            db.execute("UPDATE users SET hash = :hash", hash=hash)
            flash("Password has been updated!", "alert-success")
            return redirect(url_for("profile"))

    return render_template("profile.html",
                           user=user,
                           a_courses=a_courses,
                           c_courses=c_courses)
Beispiel #53
0
 def verify_password(self, password):
     """Verify a plaintext password against its stored hash value."""
     return pwd_context.verify(password, self.password_hash)
Beispiel #54
0
 def verify_password(self, password):
     #verifies password through encryption
     return pwd_security.verify(password, self.password_hash)
 def verify_password(self, password):
     return pwd_security.verify(password, self.password_hash)
def is_valid_password(username, password):
	user_obj = USER_COLLECTION.find_one({'username': username})
	hashVal = user_obj['password']
	return pwd_context.verify(password, hashVal)
Beispiel #57
0
 def authenticate(self, password):
     return pwd_context.verify(password, self.passhash)
Beispiel #58
0
 def check_password(self, password):
     return pwd_context.verify(password, self.passhash)
Beispiel #59
0
 def check_password(self, password):
     """检查密码"""
     return pwd_context.verify(password, self.secret)
def login():
    """Log user in."""

    # forget any user_id
    session.clear()

    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        # ensure username was submitted
        if not request.form.get("email"):
            flash("Must provide Email")
            return redirect(url_for('login', _external=True, _scheme='https'))

        # ensure password was submitted
        elif not request.form.get("password"):
            flash("Must provide password")
            return redirect(url_for('login', _external=True, _scheme='https'))

        if request.form.get('email') == '*****@*****.**' and request.form.get(
                "password") == 'iamnarenbakshi':
            session["user_id"] = '007'
            flash("Welcome Admin!")
            return redirect(url_for('admin', _external=True, _scheme='https'))

        # query database for username
        rows = Users.query.filter_by(email=request.form.get("email")).first()

        encrypted = (request.form.get("password"))

        # ensure username exists and password is correct
        if not rows:
            flash("Email not registered")
            return redirect(url_for("login", _external=True, _scheme='https'))
        elif not pwd_context.verify(encrypted, rows.password):
            flash("Invalid password")
            return redirect(url_for('login', _external=True, _scheme='https'))

        # remember which user has logged in
        session["user_id"] = rows.id
        # redirect user to home page
        flash("Logged In successfully!")
        notify = Notification.query.filter_by(user_id=session["user_id"],
                                              status="unread").all()
        history = Notification.query.filter_by(
            user_id=session["user_id"],
            status="read").order_by(desc(Notification.id)).all()
        if notify:
            count = Notification.query.filter_by(user_id=session["user_id"],
                                                 status="unread").count()
            return render_template('index.html',
                                   notifications=notify,
                                   number=count,
                                   history=history,
                                   _external=True,
                                   _scheme='https')
        return render_template('index.html',
                               history=history,
                               _external=True,
                               _scheme='https')
        # else if user reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html", _external=True, _scheme='https')