示例#1
0
文件: main.py 项目: khockenj/ssw322
def login():
    final = "Couldn't connect to the database. Please reload."
    email = request.form.get('email')   #email/pw post
    password = request.form.get('pass')
    try:
        dbconn = sql.connect(sqlitedb)
        dbconn.text_factory = str
        c = dbconn.cursor()
        sel = c.execute("SELECT * FROM `users` WHERE `email` = (?) ", (email,))
        finder = sel.fetchone()
        if session.get('uid'):  #session already set
            final = "You are already logged in."
        elif not finder:    #email not found
            final = "Sorry, that E-mail doesn't exist."
        elif not bcrypt.verify(password, finder[4]):    #not correct password
            final = "Sorry, that is the wrong password."
        elif bcrypt.verify(password, finder[4]) and finder: #probably doublelogic somewhere here but just in case, logged in
            final = "logged"
            session['uid'] = finder[0]  #set session
        else:
            final = "An unexpected error occurred. Please try again."
        dbconn.close()
    except:
        final = "ERROR: Couldn't connect to the database. Please reload."

    return final
示例#2
0
async def change_password(document):
    decoded_token = document['authToken']
    current_password = document['currentPassword']
    new_password = document['newPassword']
    user = await conf.mongo_accounts.find_one(
        filter = {'authTokens': {'$elemMatch': {'authToken': decoded_token}}},
        projection = ['_id', 'password']
    )
    if not bcrypt.verify(current_password, user['password']):
        return Response(
            {
                "success": False,
                "error": _("Incorrect password.")
            },
            403
        )
    if bcrypt.verify(new_password, user['password']):
        return Response({
            "success": False,
            "error": _("This is the same password as the current one.")
        })
    hashed_new_password = bcrypt.hash(new_password)
    await conf.mongo_accounts.update_one(
        filter = {'_id': user['_id']},
        update = {'$set': {'password': hashed_new_password}}
    )
    return Response({"success": True})
示例#3
0
    def delete(self):
        jsonvalue = request.json
        userName = jsonvalue.get("username")
        password = jsonvalue.get("password")
        result = DB.readData(
            "select password from login_details where username='******'")

        if (len(result)) == 0:
            response = "User Doesnt Exist"
        else:
            for row in result:
                hashed_password = row[0]
            login_success = False
            print(bcrypt.verify(password, hashed_password))
            if bcrypt.verify(password, hashed_password):
                login_success = True
            if (login_success):
                updateMsg = DB.updateData(
                    "Delete from login_details where username='******'")
                if updateMsg.find("Successful") >= 0:
                    response = "Account Got Deleted Successfully"
                else:
                    response = "Please Enter valid credentials"
        return response
示例#4
0
    def delete(self):
        jsonvalue = request.json
        userName = jsonvalue.get("username")
        password = jsonvalue.get("password")
        result = DB.readData(
            "select password from mydb.login_details where username='******';")
        response = None
        if not result:
            response = jsonify({"message": "User Doesnt Exist"})
        else:
            hashed_password = ""
            for row in result:
                hashed_password = row.password

            for row in result:
                hashed_password = row[0]
            login_success = False
            print(bcrypt.verify(password, hashed_password))
            if bcrypt.verify(password, hashed_password):
                login_success = True
            if (login_success):
                result = DB.readData(
                    "delete from mydb.login_details where username='******';")

                response = jsonify({"message": "Successfully Deleted"})
                redisconnection.delRedisValue(userName)

            else:
                response = jsonify({"message": "Invalid Credentials"})
        return response
示例#5
0
文件: auth.py 项目: iandioch/dia-log
 def check_user_pass(self, user, password):
     """Returns True if the given user & pass is valid,
     and False otherwise."""
     if user not in self.db:
         return False
     if self.debug:
         return self.db[user] == password or \
                 bcrypt.verify(password, self.db[user])
     try:
         return bcrypt.verify(password, self.db[user])
     except ValueError:
         # happens when password is in plaintext, for debug
         # mode
         return False
示例#6
0
    def post(self):
        jsonvalue = request.json
        userName = jsonvalue.get("username")
        password = jsonvalue.get("password")
        result = DB.readData(
            "select password from mydb.login_details where username='******';")
        response = None
        if not result:
            response = jsonify({"message": "User Doesnt Exist"})
        else:
            hashed_password = ""
            for row in result:
                hashed_password = row.password

            for row in result:
                hashed_password = row[0]
            login_success = False
            print(bcrypt.verify(password, hashed_password))
            if bcrypt.verify(password, hashed_password):
                login_success = True
            if (login_success):

                print(userName)
                refToken = json.loads(
                    ApiJWTAuthentication.getRefreshToken(userName))

                refToken = refToken.get('jwt')

                encrypted_ref = EncryptionAlg.getEncryptedMsg(refToken)
                accessToken = json.loads(
                    ApiJWTAuthentication.getAccessToken(encrypted_ref))
                accessToken = accessToken.get('jwt')
                # refToken=refToken.decode('utf-8')
                # accessToken = accessToken.decode('utf-8')

                response = jsonify({
                    "refreshToken": encrypted_ref,
                    "accessToken": accessToken
                })

                redisconnection.setRedisValue(userName, refToken)

                # redis_client.__setitem__(userName,token)

            else:
                response = jsonify({"message": "Invalid Credentials"})
        return response
示例#7
0
    def verify_password(self, password):
        user = self.find()

        if not user:
            return False

        return bcrypt.verify(password, user["password"])
示例#8
0
def LoginPage():
    form = LoginForm(request.form) 
    try:
        if request.method == "POST" and form.validate():
            username = thwart(request.form['username'])
            c,conn = confconnection()
            data = c.execute("SELECT password, username FROM new_users WHERE username =(%s)",(username))
            #CheckForOldPass(username,request.form['password'])
            data = c.fetchone()
            passw = request.form['password']
            if c.rowcount == 0:
                return CheckForOldPass(username,passw)
            elif(bcrypt.verify(passw,data[0])):
                session['logged_in'] = True
                session['user'] = username
                setUserName = username #For use in logging
                SetPermissions(username)
                CreateLog("Login",username)
                conn.close()
                return redirect(url_for('Profile'))
            else:
                CreateLog('Wrong password',setUserName)
                return "Feil brukernavn eller passord"
    except Exception as e:
        return (str(e))
    return render_template('login.html', form = form, usrUpdate = userUpdate, userMessage="Det ble utført en nødvendig brukeroppdatering, venligst logg inn igjen")
示例#9
0
def load_token(token):
    max_age = app.config['REMEMBER_COOKIE_DURATION'].total_seconds()
    data = login_serializer.oads(token, max_age = max_age)
    user = User.get(data[1])
    if user and bcrypt.verify(data[2], user.password):
        return user
    return None
示例#10
0
文件: auth.py 项目: ajvb/genesis
def check_password(passw, hash):
    """
    Tests if a password is the same as the hash.

    Instance vars:

    - ``passw`` - ``str``, The password in it's original form
    - ``hash`` - ``str``, The hashed version of the password to check against
    """
    if hash.startswith('{SHA}'):
        try:
            import warnings
            warnings.warn(
                'SHA1 as a password hash may be removed in a future release.')
            passw_hash = '{SHA}' + b64encode(sha1(passw).digest())
            if passw_hash == hash:
                return True
        except:
            import traceback
            traceback.print_exc()
    elif hash.startswith('$2a$') and len(hash) == 60:
        return bcrypt.verify(passw, hash)
    elif sha512_crypt.identify(hash):
        return sha512_crypt.verify(passw, hash)
    return False
示例#11
0
def login():
    form = LoginForm(request.form)
    if form.validate_on_submit():

        user = models.Users.from_username_or_email(form.user.data)

        if not user:
            form.user.errors.append('Invalid username or email.')
            return render_template('login.html', form=form)

        if not user.password:
            flash(
                'There is no password associated with your account.  '
                'Please activate it by clicking on the link in your '
                'activation email.', 'error')
            return redirect(
                url_for('user.no_password', next=request.args.get('next')))

        if bcrypt.verify(form.password.data, user.password):
            user.authentication_change(True)
            login_user(user)
            flash('You are successfully logged in.  Welcome!', 'success')
            return redirect_back('index.index')
        else:
            form.password.errors.append('Invalid password')
            return render_template('login.html', form=form)

    return render_template('login.html', form=form)
示例#12
0
 def getToken(self):
   userCredentials = json.loads(open("passwd.json").read());
   req = self.request.body.decode('utf-8');
   username = json.loads(req)["username"];
   password = json.loads(req)["password"];
   if username in userCredentials.keys():
     if bcrypt.verify( password, userCredentials[username]["password"]):
       payload = {
         'usr': username,
         'role': userCredentials[username]["role"],
         'iss': 'http://dns.danshick.net',
         'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1),
         'iat': datetime.datetime.utcnow()
       };
       new_token = jwt.encode(payload, global_secret, 'HS512');
       self.set_status(200);
       self.write(new_token);
       return;
     else:
       self.set_status(403);
       self.write("The password you entered is incorrect.");
       return;
   else:
     self.set_status(403);
     self.write("Specified username does not yet exist.");
     return;
   self.set_status(400);
   self.write("Bad request");
示例#13
0
    def verify_password(self, password):
        """Veify a given password. Encrypt it if the password is plaintext"""
        # is it cleartext?
        if password == self.password:
            self.set_password(password)

        return bcrypt.verify(password, self.password)
示例#14
0
文件: auth.py 项目: tewe/genesis
def check_password(passw, hash):
    """
    Tests if a password is the same as the hash.

    Instance vars:

    - ``passw`` - ``str``, The password in it's original form
    - ``hash`` - ``str``, The hashed version of the password to check against
    """
    if hash.startswith('{SHA}'):
        try:
            import warnings
            warnings.warn(
                'SHA1 as a password hash may be removed in a future release.')
            passw_hash = '{SHA}' + b64encode(sha1(passw).digest())
            if passw_hash == hash:
                return True
        except:
            import traceback
            traceback.print_exc()
    elif hash.startswith('$2a$') and len(hash) == 60:
        return bcrypt.verify(passw, hash)
    elif sha512_crypt.identify(hash):
        return sha512_crypt.verify(passw, hash)
    return False
示例#15
0
def login():
    """Login."""
    if request.method == "GET":
        return render_template('login.html')

    if request.method == "POST":
        username = request.form['username']
        password = request.form['password']
        remember = request.form.get("remember", "not_clicked")

        is_remember = remember == "clicked"

        error = None
        user = mongo.db.users.find_one({"username": username})

        if user is None:
            error = 'Invalid username.'
        else:
            if not bcrypt.verify(password, user["password"]):
                error = 'Incorrect password.'
            # pass_hash = bcrypt.encrypt(password)
            # if not pass_hash == user["password"]:
            #     error = 'Incorrect password.'

        if error is None:
            auth_token = encode_auth_token(str(user["_id"]), is_remember)
            return redirect(url_for('index', token=auth_token))
            # /?token=sdajndjnodnqoidaismdoaisdo
        else:
            flash(error)
            return redirect(url_for('login'))
示例#16
0
    def handleVerifyUser(self):

        db = SportEventsDB() 
        
        # get the content length (in bytes)
        length = self.headers["Content-Length"]

        # read the body to a string
        body = self.rfile.read(int(length)).decode("utf-8")
        print("Body: ", body)
        # print the body as a string
        
        parsed_body = parse_qs(body)
        print("parsed body", parsed_body)

        email = parsed_body["email"][0]  #copy each for column heading 
        plain_password = parsed_body["password"][0]

        user = db.getOneUserEmail(email)
        
        if user != None:
            if bcrypt.verify(plain_password, user["encpass"]):
                id = user["id"]
                self.session["userid"] = id
                self.send_response(201)
                self.end_headers()
            else:
                # status code 401
                self.handleNotAuthorized()

        else:
            # status code 401
            self.handleNotAuthorized()
示例#17
0
 def verify_password(self, password):
     """ return if password is right """
     user = self.find()
     if user:
         return bcrypt.verify(password, user['password'])
     else:
         return False
示例#18
0
文件: user.py 项目: matoous/newz
 def check_password(self, password: str) -> bool:
     """
     Check users password
     :param password: submitted password
     :return:
     """
     return bcrypt.verify(password, self.password)
示例#19
0
    def verify_password(self, password):
        user = self.find()

        if not user:
            return False

        return bcrypt.verify(password, user["password"])
示例#20
0
def auth_user(username: str, password: str):
    # get user
    manager = Manager.query.filter(Manager.username == username).first()
    # verify password if user is exists
    if manager is not None and bcrypt.verify(password, manager.password):
        return manager
    return None
    def authenticateWebAppUser(self, username, password):
        """ Attempts to validate authenticate the supplied username/password

        Attempt to authenticate the user against the list of users in
        web_app_user table. If successful, a dict with user innformation is
        returned. If not, the function returns False.
        """
        with TRN:
            sql = """SELECT  cast(ag_login_id as varchar(100)) as ag_login_id,
                      email, name, address, city,
                      state, zip, country,kit_password
                    FROM ag_login
                INNER JOIN ag_kit USING (ag_login_id)
                WHERE supplied_kit_id = %s"""
            TRN.add(sql, [username])
            row = TRN.execute_fetchindex()
            if not row:
                return False

            results = dict(row[0])

            if not bcrypt.verify(password, results['kit_password']):
                return False
            results['ag_login_id'] = str(results['ag_login_id'])

            return results
示例#22
0
    def post(self):
        auth = request.get_json()
        login = auth.get('login')
        password = auth.get('password')
        login_type = auth.get('type')
        if not auth or not login or not password or not login_type:
            return make_response(
                {"message": ApiMessages.COULD_NOT_VERIFY.value}, 401,
                {'WWW-Authenticate': 'Basic realm="Login required"'})

        emplo_user = EmployeeModel.query.filter_by(login=login).first()
        time = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)

        if emplo_user and bcrypt.verify(password, emplo_user.password):
            if login_type != 'employee' and not emplo_user.isAdmin:
                return make_response(
                    jsonify(
                        {'message': ApiMessages.NO_ACCESS_PERMISSION.value}),
                    403)
            token = jwt.encode({
                'login': emplo_user.login,
                'exp': time
            }, current_app.config['SECRET_KEY'])
            return make_response(
                jsonify({
                    'token': token.decode('UTF-8'),
                    'isAdmin': emplo_user.isAdmin,
                    'name': emplo_user.name,
                    'surname': emplo_user.surname
                }), 200)

        return make_response(
            jsonify({"message":
                     ApiMessages.LOGIN_OR_PASSWORD_INCORRECT.value}), 401,
            {'WWW-Authenticate': 'Basic realm="Login required"'})
示例#23
0
文件: views.py 项目: davlum/poetson
def perfil():
    con = engine.connect()
    if session['is_person']:
        user = current_pers(con, session['email'])
    else:
        user = current_gr(con, session['email'])
    pers_gr = query_pers_gr(con, session['id'])
    result = query_perfil(con, session['id'], 'EDITOR')
    con.close()
    password_form = ChangePasswordForm(request.form)
    if request.method == 'POST' and password_form.validate():
        if user and bcrypt.verify(password_form.old_password.data, user.contrasena):
            con = engine.connect()
            password = bcrypt.using(rounds=13).hash(str(password_form.new_password.data))
            reset_pass = text("""UPDATE public.usuario SET contrasena=:password 
                                  WHERE usuario_id=:id""")
            con.execute(reset_pass, id=user.part_id, password=password)
            con.close()
            flash('Contraseña cambiada correctamente.', 'success')
        else:
            flash('El cambio de contraseña no tuvo éxito.', 'danger')
        return redirect(url_for('user.perfil', _anchor='tab_contrasena'))
    return render_template('user/perfil.html', user=user
                                              , result=result
                                              , pers_gr=pers_gr
                                              , password_form=password_form)
def login():
    if not request.json:
        return jsonify(
            {"message": "Identifier en password parameter niet gevonden"}), 400

    identifier = request.json.get('identifier', None)
    password = request.json.get('password', None)
    if not identifier:
        return jsonify({"message": "Identifier parameter niet gevonden"}), 400
    if not password:
        return jsonify({"message": "Password parameter niet gevonden"}), 400

    # Find identifier
    with pyodbc.connect(db_connection_settings) as connection:
        cursor = connection.cursor()
        query = """SELECT UUID, Gebruikersnaam, Email, Rol, Wachtwoord FROM Gebruikers WHERE Email = ?"""
        cursor.execute(query, identifier)
        result = cursor.fetchone()
    
    if result:
        result = row_to_dict(result)
        passwordhash = result['Wachtwoord']
        if passwordhash:
            if bcrypt.verify(password, passwordhash):
                identity_result = dict(result)
                identity_result.pop('Wachtwoord')
                access_token = create_access_token(identity=identity_result)
                raw_token = decode_token(access_token)
                return jsonify({'access_token':access_token, 
                                'expires':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.localtime(raw_token['exp'])),
                                'identifier':raw_token['identity'],
                                'deployment type':os.getenv('API_ENV')}), 200    
    return jsonify(
        {"message": "Wachtwoord of gebruikersnaam ongeldig"}), 401
示例#25
0
 def verify_password(self, password):
     """ return if password is right """
     user = self.find()
     if user:
         return bcrypt.verify(password, user['password'])
     else:
         return False
示例#26
0
def verify(username, password):
    if not (username and password):
        return False
    user = User.query.filter_by(username=username).first()
    if user and bcrypt.verify(password, user.password):
        return user
    return False
示例#27
0
def login(self):
    if self.request.method == 'GET':
        message = self.flash_secure_cookie('admin_login_invalid')
        if not message:
            message = ''
        self.render('login', message=message)
    else:
        username = self.get_argument('username')
        password = self.get_argument('password')
        instructor = yield AccessType.objects.get(admin_type='Instructor')
        admin = yield Admin.objects.get(username=username,
                                        access_type__ne=instructor)
        invalid = False
        try:
            if not admin or not bcrypt.verify(password, admin.password):
                invalid = True
        except ValueError:
            invalid = True
        if invalid:
            self.set_secure_cookie('admin_login_invalid',
                                   'Invalid username and password')
            self.redirect('/admin/login')

        privileges = {}
        for i, privilege in enumerate(admin.access_type.privileges):
            privileges[privilege.module] = privilege.actions

        self.set_secure_cookie('privileges', to_json(privileges))
        self.set_secure_cookie('admin', admin.username)
        self.redirect('/admin/')
示例#28
0
def __check_password(password, password_db):

    # return True
    if password is None or len(password) == 0:
        return False

    return bcrypt.verify(password, password_db)
示例#29
0
def login():
	#if g.user is not None and g.user.is_authenticated():
	#	return redirect("/")

	if request.method == "POST":
		name = request.form["username"]
		pwd = request.form["password"]

		user = models.User.query.filter_by(name=name).first()

		if user is None:
			flash("Woah! You almost killed a unicorn!")
			return redirect(url_for("login"))

		if bcrypt.verify(pwd, user.pwdhash):
			login_user(user)
			return redirect(url_for("index"))
		else:
			flash("Woah! You almost killed a unicorn!")
			return redirect(url_for("login"))

			return redirect("/")


	# Request method is not POST or user authentication was incorrect
	# so login page has to be rendered
	return render_template("login.html")
示例#30
0
文件: models.py 项目: seymasa/turp
    def login_check(self, password):

        user = self.find()
        if user: # Önceden eklediğim verileri sildim çünkü parolalarda sıkıntı çıkartacaktı bu şekilde doğru olur..
            return bcrypt.verify(password, user['password'])
        else:
            return False
 def test_ag_update_kit_password(self):
     self.data_access.ag_update_kit_password('test', 'newpass')
     cur = self.con.cursor()
     cur.execute('select kit_password from ag_kit where supplied_kit_id = '
                 '%s', ('test',))
     rec = cur.fetchone()
     self.assertTrue(bcrypt.verify('newpass', rec[0]))
示例#32
0
def authenticate_user():
    request_data = request.data
    required_fields = ['username', 'password']

    if not all([field in request_data for field in required_fields]):
        raise exceptions.ParseError()

    username = request_data['username']
    password = request_data['password']
    # TODO: might return collection even if its just one record
    db_password = session.execute(
        """
    SELECT password
      FROM users
      WHERE username = %(username)s;""", {'username': username})

    if bcrypt.verify(password,
                     db_password):  # salt is encoded in hashed password
        return {
            'success': 'True'
        }, status.HTTP_200_OK, {
            "Content-Type": "application/json"
        }
    else:
        return {
            'success': 'False'
        }, status.HTTP_400_BAD_REQUEST, {
            "Content-Type": "application/json"
        }
示例#33
0
def login():

    form = LoginForm(request.form, meta={'csrf_context': session})

    error = None

    if request.method == 'POST' and form.validate():

        email = form.email.data
        password = form.password.data
        
        user = db.users.find_one({'email': email})

    

        if user and bcrypt.verify(password, user['password'],):
            
            session['email'] = email

            if user['role'] == 'manager':
                return redirect(url_for('manage'))
            else:
                return redirect(url_for('profile'))
        
        else:
            error = "Wrong email password combination"
    

    return render_template("login.html", error=error, form=form)
示例#34
0
 def verify_password(self, password: str) -> bool:
     """Check if `password` matches for the given user."""
     user = self.find()
     if user:
         return bcrypt.verify(password, user[0]["u"]["password"])
     else:
         return False
示例#35
0
    def handleCreateSession(self):
        db = GamesDB()
        parsed_body = self.getParsedBody()
        profile_name = parsed_body["profile_name"][0]
        password = parsed_body["password"][0]

        profile_exists = db.checkProfileName(profile_name)
        if profile_exists:
            auth_info = db.getUserAuthInfo(profile_name)
            verified = bcrypt.verify(password, auth_info[0]["encrypted_password"])
            if verified:
                self.mSession["userID"] = auth_info[0]["id"]
                user = db.getUser(auth_info[0]["id"])
                profile_name = user[0]["profile_name"]
                self.mSession["profile_name"] = profile_name
                isAdmin = db.isAdmin(profile_name)
                self.mSession["isAdmin"] = isAdmin
                user[0]["is_admin"] = isAdmin
                json_string = json.dumps(user)
                self.send_response(201)
                self.send_header("Content-Type", "application/json")
                self.end_headers()
                self.wfile.write(bytes(json_string, "utf-8"))
            else:
                self.handle401()
        else:
            self.handle401()
示例#36
0
    def verify_password(self, password):
        """Verifies given password with stored hashed password

        :param str password: raw password to be matched with hashed password
        :return bool: True for correct and False for wrong password
        """
        return bcrypt.verify(password, self.hashed_password)
示例#37
0
def login():
    if request.method == 'POST':
        if request.form['type'] == 'signin':
            # Query Database
            cur = conn.cursor()
            cur.execute("select email, username, password from accounts where email=%s", [request.form['email']])
            data = cur.fetchone()
            # Fail conditions [no user by that email or password does not match]
            if data == None: return '', 298
            if not bcrypt.verify(request.form['pass'], data[2]): return '', 299
            # If good go to home page
            login_user(User(data[0], data[1]), remember=True, duration=timedelta(days=1))
            return redirect(url_for('home'), 303)

        elif request.form['type'] == 'signup':
            try:
                albums = json.dumps([{ 'album_name': "My Gallery", 'images': [] }])
                #Query Database
                cur = conn.cursor()
                # Attempt to add new user and login
                password = bcrypt.hash(request.form['pass'])
                cur.execute("insert into accounts (email, username, password, albums) values (%s, %s, %s, %s)",
                            [request.form['email'], request.form['user'], password, albums])
                conn.commit()
                login_user(User(request.form['email'], request.form['user']), remember=True, duration=timedelta(days=1))
                return redirect(url_for('home'), 303)
            except psycopg2.IntegrityError:
                cur.execute('ROLLBACK')
                return '', 299

    if current_user.is_authenticated:
        return redirect(url_for('home'))
    else:
        return render_template('login.html')
示例#38
0
class User:
  def __init__(self, username):
    self.username = username

  def find(self):
    user = graph.find_one("User", "username", self.username)
    return self

  def set_password(self, pasword):
    self.password = bcrypt.encrypt(password)
    return self

  def register(self):
    if not self.find():
      user = Node("User", username=self.username, password=self.password)
      graph.create(user)
      return True
    else:
      return False

  def verify_password(self.password):
    user = self.find()
    if user:
      return bcrypt.verify(password, user['password'])
    else:
      return False
示例#39
0
def user_query(db_name, usr, pswd):
    """

    Args:
        db_name:
        usr:
        pswd:

    Returns:
        username - str, password verification - bool

    """

    # Making a connection to the database
    # If it does not yet exist, SQLite will create it
    con = sqlite3.connect(database=db_name)

    # Creating our cursor object and then using it to execute the creation of the table
    cursor = con.cursor()

    # Querying the database and then using the fetchall() method to return the data
    cursor.execute("""SELECT username, password, name FROM users WHERE username=?""",
                   (usr,))
    result = cursor.fetchall()

    # Catch for when nothing is returned
    if len(result) == 0:
        return False, False, False

    # If a user was successfully returned, we need to make sure that the password matches
    # Thankfully, bcrypt has a nice convenience function that returns a BOOL
    return result[0][0], bcrypt.verify(pswd, result[0][1])
def loginConfirm(user_name_input, password_input):
	#check to see if the user exists
	check_user = userValidate(user_name_input)
	if check_user == False:
		return "User doesn't exist"	
	else:
		password_query_text = "select password from testing_login where user_name ='%s'" % user_name_input
		cur.execute(password_query_text)
		hashed = cur.fetchone()[0]
		print hashed
		print str(bcrypt.verify(password_input, hashed))
		if bcrypt.verify(password_input, hashed) == True:
			return "It matches"
		else:
			return "It does not match"
	db.close()
示例#41
0
文件: user.py 项目: tordans/frontend
 def check_password(self, password):
     """
     Ueberprueft das Passwort des Nutzers
     """
     if self.password is None:
         return False
     return bcrypt.verify(password, self.password)
示例#42
0
def verify_password(password, pw_hash):
    try:
        return bcrypt.verify(password, pw_hash)
    except ValueError:
        return False
    except TypeError:
        return False
示例#43
0
    def handleSessionCreate(self):
        length = self.headers["Content-length"]
        #ready body data from client
        body = self.rfile.read(int(length)).decode("utf-8")
        #parse the body into a dictionary with values of arrays
        data = parse_qs(body)

        email = data['email'][0]
        pw = data['password'][0]

        #send to the database
        db = RecipesDB()

        user = db.getUserByEmail(email)
        if user == None:
            #failure
            self.handle401()
        else:
            if bcrypt.verify(pw, user['encrypted_password']):
                #YAY
                self.session["userID"] = user["id"]
                self.send_response(201)
                self.end_headers()
            else:
                #failure
                self.handle401()
示例#44
0
def test_change_user_password(test_user):
    ''' change user password in churchtools '''
    with ct_connect.session_scope() as ct_session:
        # check if test_user password is the one in the churchtools-db
        db_user = ct_connect.get_person_from_id(ct_session, test_user['id'])[0]

        assert bcrypt.verify(test_user['password'], db_user.password)

        # new password
        password = '******'
        ct_connect.change_user_password(ct_session, test_user['id'], password)
        db_user = ct_connect.get_person_from_id(ct_session, test_user['id'])[0]

        assert bcrypt.verify(password, db_user.password)

        # reset password
        ct_connect.change_user_password(ct_session, test_user['id'],
                                        test_user['password'])
示例#45
0
 def check_password(self, password):
     try:
         return bcrypt.verify(password, self.password)
     except ValueError:
         if hashlib.sha1(password).hexdigest() == self.password:
             self.password = User.make_password(password)
             return True
         else:
             return False
示例#46
0
def is_password_valid(real_encrypted_password, given_password):
    """
    Take an encrypted password, and verifies it. Returns bool.
    """

    try:
        return bcrypt.verify(given_password, real_encrypted_password)
    except:
        return False
示例#47
0
文件: user.py 项目: cyocom/newauth
    def check_password(self, password):
        """Check if given password checks out.

        :param password: The password to compare
        :type password: str
        :returns: bool -- If the password checks out or not

        """
        return bcrypt.verify(password, self.password)
示例#48
0
    def verify_password(self, password):
        """Verify an encrypted password using ``password`` as a salt.
        :param password: hashable str
        :returns: True when valid, false otherwise
        """

        if not self.password:
            return False
        return bcrypt.verify(password, self.password)
示例#49
0
def authenticate_user(form, dbmaker):
        if form.validate():
            username = form.data['username']
            password = form.data['password']
            with db_session(dbmaker) as session:
                user = session.query(User).filter(User.username==username).first()
                if user and bcrypt.verify(password, user.password):
                    return True
        return False
示例#50
0
文件: user.py 项目: Folashade/sagefy
    def is_password_valid(self, password):
        """
        Take an encrypted password, and verifies it. Returns bool.
        """

        try:
            return bcrypt.verify(password, self["password"])
        except:
            return False
示例#51
0
    def POST(self):
        name, pwd = web.input().username, web.input().password
        user = models.User.get(username=name)
        if not user:
            return render.login(is_loggedin(), True)

        if bcrypt.verify(pwd, user.password):
            raise authorize(user)
        return render.login(is_loggedin(), True)
示例#52
0
    def checkPass(self, uid, password):
        """
        This function checks the password for a given uid.
        If ``password`` is a unicode object, it is converted to the database encoding first.
        - returns true in case of success
        -         false if password does not match

        """

        res = False
        userinfo = self.getUserInfo(uid)
        if isinstance(password, unicode):
            password = password.encode(self.encoding)

        database_pw = userinfo.get("password", "XXXXXXX")
        if database_pw[:2] in ["$P", "$S"]:
            # We have a phpass (wordpress) password
            PH = PasswordHash()
            res = PH.check_password(password, userinfo.get("password"))
        # check salted hashed passwords
#        elif database_pw[:2] == "$6":
#            res = sha512_crypt.verify(password, userinfo.get("password"))
        elif database_pw[:6].upper() == "{SSHA}":
            res = check_ssha(database_pw, password, hashlib.sha1, 20)
        elif database_pw[:9].upper() == "{SSHA256}":
            res = check_ssha(database_pw, password, hashlib.sha256, 32)
        elif database_pw[:9].upper() == "{SSHA512}":
            res = check_ssha(database_pw, password, hashlib.sha512, 64)
        # check for hashed password.
        elif userinfo.get("password", "XXXXX")[:5].upper() == "{SHA}":
            res = check_sha(database_pw, password)
        elif len(userinfo.get("password")) == 64:
            # OTRS sha256 password
            res = otrs_sha256(database_pw, password)
        elif database_pw[:3] in ["$1$", "$6$"]:
            res = check_crypt(database_pw, password)
        elif database_pw[:4] in ["$2a$", "$2b$", "$2y$"]:
            # Do bcrypt hashing
            res = bcrypt.verify(password, database_pw)
        elif database_pw[:6] in ["1|$2a$", "1|$2b$", "1|$2y$"]:
            # Do bcrypt hashing with some owncloud format
            res = bcrypt.verify(password, database_pw[2:])

        return res
示例#53
0
def authenticate(username, password):
    sleep(1.2) # Slowing down attacks
    uid = dbcon.io.get('username:'******':uid')
    if uid is None:
        return False
    password_hash = dbcon.io.get('uid:' + uid + ':password')
    if not password_hash:
        return False
        #return (False, 'Your user account has expired. Please contact your supervisor.')
    return bcrypt.verify(password, password_hash)
示例#54
0
文件: auth.py 项目: bmoar/flask-truss
def attempt_logon(attempted_name, attempted_password):
    """Attempt to login the user and return a matching user model instance if successful"""
    user = User.query.filter(User.user_name == attempted_name).first()
    try:
        if bcrypt.verify(attempted_password, user.password):
            return user
        else:
            return None
    except (ValueError, AttributeError):
        return None
示例#55
0
    def verify_password(self, password):
        """Validated a submitted password.

        Args:
                password (str): The plain text password entered by human

        Returns:
                True if successful, False otherwise.
        """
        return bcrypt.verify(password, self.password)
    def handoutCheck(self, username, password):
        with TRN:
            sql = "SELECT password FROM ag.ag_handout_kits WHERE kit_id = %s"
            TRN.add(sql, [username])
            to_check = TRN.execute_fetchindex()

            if not to_check:
                return False
            else:
                return bcrypt.verify(password, to_check[0][0])
示例#57
0
 def verify_password(cls, password, request):
     #cls is used instead of self, see PEP-8
     log.debug('verify_password with {0}, {1}'.format(password,cls.user_password))
     try:
         if bcrypt.verify(password,cls.user_password):
             return True
         else:
             return False
     except Exception as e:
         log.debug('Error verifying password: {0}'.format(e))
         return False
    def user_signin(self,sql,conn, username, password=None, confirmation=None) :
        skeptical, user = None, None
        skip_validate = False
        try :
            if confirmation is not None:
                query = """
                    SELECT user_id, confirmation FROM want2hack.account
                    WHERE username = %s
                """
                sql.execute(query, [username])
                skeptical = sql.fetchone()
                if(skeptical is None  or skeptical['confirmation'] is None or not bcrypt.verify((str(datetime.now().date())+skeptical['confirmation']),confirmation)):
                    return None
                if password is not None:
                    password = bcrypt.encrypt(password)
                query = """
                    UPDATE want2hack.account SET confirmation = NULL, password=%s WHERE user_id = %s;
                """

                # this breaks if the confirmation was invalid
                # and thus exits try, returning None
                sql.execute(query, [password,skeptical['user_id']])

                conn.commit()
                skip_validate = True
            else :
                query = """
                    SELECT user_id, password FROM want2hack.account 
                    WHERE username = %s;
                """
                sql.execute(query, [username])
                skeptical = sql.fetchone()    

            # skip_validate only ever runs once per use, during their account confirmation
            # ~= one time pad. Not quite equal to a one time pad.
            if (skip_validate or (not skeptical is None and not skeptical['password'] is None and bcrypt.verify(password,skeptical['password']))) :
                sesh = self.genkey(128)
                query = """
                    UPDATE account SET 
                        session_token = %s, 
                        date_last_session = NOW() 
                    WHERE user_id = %s 
                    RETURNING *;
                """
                sql.execute(query, [sesh, skeptical['user_id']])
                user = sql.fetchone()
                user["session_token"] = str(user["user_id"])+"|"+user["session_token"]
                if user is not None :
                    conn.commit()
                else :
                    conn.rollback()

        except Exception, e :
            self.app.logger.warning('user_signin '+str(e))
示例#59
0
 def authenticate(self, password):
     if not self.is_enabled():
         api_error(ValueError, "User is not enabled.", 403)
     # sanitize inputs and validate the user
     if is_sanitary(self.email):
         if bcrypt.verify(password, self.hash):
             # basic login token expires after 15 minutes
             return self.genJWToken(900)
         else:
             api_error(ValueError, "Unauthorized, Wrong Password.", 401)
     abort(400)
示例#60
0
    def handoutCheck(self, username, password):
        cursor = self.get_cursor()
        cursor.execute("""SELECT password
                          FROM ag.ag_handout_kits
                          WHERE kit_id=%s""", [username])
        to_check = cursor.fetchone()

        if not to_check:
            return False
        else:
            return bcrypt.verify(password, to_check[0])