Ejemplo n.º 1
0
    def test_change_password(self, _session):
        sample_user = mock.Mock()

        with mock.patch.object(UserMeta, "query", _session.query_property()) as _query:
            _query.filter_by.return_value.first.return_value = sample_user

            UserMeta.change_password("Bob", "changedpassword")

            pbkdf2_sha256.verify("changedpassword", sample_user.password)
            _session.add.assert_called_once_with(sample_user)
            _session.commit.assert_called_once_with()
            _session.close.assert_called_once_with()
Ejemplo n.º 2
0
 def autenticate(cls, user, psw):
     try:
         user_model = cls.objects.get(user=user)
         if pbkdf2_sha256.verify(psw, user_model.psw):
             return True
     except cls.DoesNotExist, e:
         pass
Ejemplo n.º 3
0
def do_login(username="", passwd=""):
    """performs user login authentication"""
    if username != app.config["ADMIN_USERNAME"]:
        raise ValueError
    if not pbkdf2_sha256.verify(passwd, app.config["ADMIN_PASSWORD"]):
        raise ValueError
    session["logged_in"] = True
Ejemplo n.º 4
0
def verifyPass(password, user):
    if not existsInDB(user):
        sys.exit(exits['userNotInDb'])
    dbPass = (list(collection.find({'username':user}))[0])['password']
    if not pbkdf2_sha256.verify(password,dbPass):
        sys.exit(exits['userpasscombo'])
    return True
Ejemplo n.º 5
0
def password():
    status = Status()
    form = Form(request.forms)
    username = open_session()['u']
    if request.method == 'POST' and form.validate():
        conn = db.engine.connect()
        result = conn.execute(
            select([
                users.c.pbkdf2]).where(
                    users.c.id == username))
        conn.close()
        row = result.fetchone()
        verify = pbkdf2_sha256.verify(
            form.current_password.data, row['pbkdf2'])
        if verify:
            new_pbkdf2 = to_bytes(pbkdf2_sha256.encrypt(
                form.new_password.data))
            conn = db.engine.connect()
            conn.execute(
                users.update().values(
                    pbkdf2=new_pbkdf2).where(
                        users.c.id == username))
            conn.close()
            status.success = "Changed password"
        else:
            status.warning = "Wrong password for this account"
    return dict(status=status,
                form=form)
Ejemplo n.º 6
0
def user_login(username, password):
    """User Login"""
    password_hash = ''
    conn = conn_db.connect()
    cursor = conn.cursor()
    query = """SELECT Password FROM Users WHERE Username = '******' LIMIT 1""".format(username)
    cursor.execute(query)
    for database_password in cursor:
        password_hash = ''.join(map(str, database_password))
    try:
        login = pbkdf2_sha256.verify(password, password_hash)
    except ValueError:
        login = False
    if not login:
        cursor.close()
        conn_db.close_connection(conn)
        user_name = ''
        return user_name
    else:
        user_name = ''
        conn = conn_db.connect()
        cursor = conn.cursor()
        query = """SELECT Name FROM Users WHERE Username = '******' LIMIT 1""".format(username)
        cursor.execute(query)
        for user_name in cursor:
            user_name = ''.join(map(str, user_name))
        cursor.close()
        conn_db.close_connection(conn)
        return user_name
Ejemplo n.º 7
0
def do_login(db_pwd, user_id, username='', passwd=''):
    if username not in get_all_user_names():
        raise ValueError("Invalid Username or Password")
    if not pbkdf2_sha256.verify(passwd, db_pwd):
        raise ValueError("Invalid Username or Password")
    session['logged_in'] = True
    session['user_id'] = user_id
Ejemplo n.º 8
0
    def _execute(self, transforms, *args, **kwargs):
        # executed before everything else.
        receivedAuth = self.request.headers.get("Authorization")

        if receivedAuth is not None:
            authMode, auth_b64 = receivedAuth.split(" ")
            if authMode != "Basic":
                logging.error("Used other HTTP authmode than 'Basic', '%s'." % authMode)
            else:
                auth = base64.b64decode(auth_b64.encode('ascii'))
                username_b, _, password_b = auth.partition(b":")
                username = username_b.decode('utf-8')
                password = password_b.decode('utf-8')
                users = self.application.users

                from passlib.hash import pbkdf2_sha256
                if username not in users:
                    logging.debug("Received nonexistent user '%s'." % username)
                elif not pbkdf2_sha256.verify(password, users[username]):
                    logging.error("Failed login for %s from %s." % (username, self.request.remote_ip))
                else:
                    self.request.netsecus_user = username
                    return super(RequestHandlerWithAuth, self)._execute(transforms, *args, **kwargs)

        self.set_status(401)
        realm = getattr(self.application, 'realm', '')
        self.set_header("WWW-Authenticate", "Basic realm=\"%s\"" % realm)
        self._transforms = []
        self.write("401: Authentifizierung erforderlich.")
        self.finish()
Ejemplo n.º 9
0
 def check_password(cls, username, password):
     user_mata_info = cls.query.filter_by(username=username).first()
     session.close()
     if user_mata_info:
         return pbkdf2_sha256.verify(password, user_mata_info.password)
     else:
         return False
Ejemplo n.º 10
0
    def login_user(self, user, password):
        """Tries to login user using username and password, returns Account object when succeed, otherwise None"""
        # Get user
        user = self.get_user(user=user)

        # Check if user exists
        if user is None:
            logging.info("Someone tried to log in with username {}, but cannot find that user in database".format(user.user))
            return None

        # Check user password
        if not pbkdf2_sha256.verify(password, user.password):
            logging.warning("User {} supplied wrong password".format(user.user))
            return None

        # Everything ok
        # Update session key and lastlogin value in database
        user.session = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
        user.lastlogin = int(time.time())
        user.commit()

        # Create cookies
        cherrypy.response.cookie["user"] = user.user
        cherrypy.response.cookie["user"]["path"] = "/"
        cherrypy.response.cookie["user"]["max-age"] = 3600 * 6
        cherrypy.response.cookie["session"] = user.session
        cherrypy.response.cookie["session"]["path"] = "/"
        cherrypy.response.cookie["session"]["max-age"] = 3600 * 6
        logging.info("User {} ({}) logged in".format(user.user, self.core.get_client_ip()))

        # Return user account
        libs.statistics.Statistics.snooper(2)
        return user
Ejemplo n.º 11
0
def submitEmailPassword():

    for k in request.forms.keys():
        print k, request.forms[k]

    username = request.forms.get('email')
    password = request.forms.get('password')

    password_hashed = base64.urlsafe_b64encode(pbkdf2_sha256.encrypt(password, rounds=NOF_HASH_ROUNDS, salt_size=16))

    username_encrypted = base64.urlsafe_b64encode(encrypt(ENCRYPTION_PASSWORD, username))

    usersTable = db.table('users')

    existingUser = usersTable.search(where('key') == username_encrypted)
    if existingUser:
        if pbkdf2_sha256.verify(existingUser['values']['password'],password_hashed):
            pass
        else:
            print "wrong login"
    else:
        usersTable.insert({'key':username_encrypted, 'values':{'password':password_hashed}})
        videosTable = db.table('videos')
        existing_cookie = request.get_cookie('sebifyme',secret=GLOBAL_COOKIE_SECRET)
        uid = existing_cookie['uid']
        elements = videosTable.search((where('values').has('uploaded_by_uid') == uid) & (where('values').has('uploaded_by_user') == None))
        for el in elements:
            currentValues = el['values']
            currentValues['uploaded_by_user'] = username_encrypted
            videosTable.update({'values':currentValues}, eids=[el.eid])

    website_content = template('video',video_name='joke.mp4')

    return website_content
Ejemplo n.º 12
0
    def post(self):
        email = self.get_argument('email', None)
        password = self.get_argument('password', None)
        next = self.get_argument("next", "/")

        if not email or not password or email == "" or password == "":
            self.render("login.html", message = "Please enter an email and password")
            return

        with db.getCur() as cur:
            cur.execute("SELECT Id, Password FROM Users WHERE Email = LOWER(?)", (email,))

            row = cur.fetchone()
            if row is not None:
                result = row[0]
                passhash = row[1]

                if pbkdf2_sha256.verify(password, passhash):
                    self.set_secure_cookie("user", str(result))
                    cur.execute("SELECT EXISTS(SELECT * FROM Admins WHERE Id = ?)", (result,))
                    if cur.fetchone()[0] == 1:
                        self.set_secure_cookie("admin", "1")

                    if result != None:
                        self.redirect(next)
                        return
        self.render("login.html", message = "Incorrect email and password")
Ejemplo n.º 13
0
def login():
    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('panel'))
    form = LoginForm()
    if form.validate_on_submit():
        #logging_in_user = User.objects(username=form.username.data)
        #logging_in_user = User.all().filter('username ='******'next') or url_for('panel'))
            else:
                flash('Invalid login. Please try again.', 'error')
                redirect(url_for('login'))
        else:
            flash('Invalid login. Please try again.', 'error')
            redirect(url_for('login'))
    return render_template('users/login.html',
        title='Sign In',
        form=form)
Ejemplo n.º 14
0
def processLogin():
    session["user_id"] = None
    session["user_name"] = None

    email = request.form.get("userEmail").lower()
    password = request.form.get("password")

    user = modelPG.User.getUserByEmail(email)
    pwordcheck = modelPG.User.getUserPasswordByEmail(email)

    if user:
        if pbkdf2_sha256.verify(password, pwordcheck):
            flash("Welcome, %s" % (user.user_name))
        # if the user is already logged in do the first part
            if "user" in session:
                session["user_id"] = user.id
                session["user_name"] = user.user_name

            else:
                do_login(user.id, email, user.user_name)
        else:
            flash("Invalid Email or Password. Please try again")
            flash('<a href = "/resetpword">Reset Password</a>')
            return render_template("login.html")

    else:
        flash("New User? Please create an account.")
        session["user_id"] = None
        session["user_name"] = None
        return render_template("login.html")
    return redirect("/userRecipes/%d" % user.id)
Ejemplo n.º 15
0
	def valid_login_credentials( cls, request ):
		user_name = request.json_body['email']
		psw 			= request.json_body['password']
		user 		  = request.db.users.find({ 'profile.email' : user_name })

		request.headers.update({
	  	'Access-Control-Allow-Origin' 		 : '*',
	  	'Access-Control-Allow-Methods' 		 : 'POST,GET,DELETE,PUT',
	  	'Access-Control-Allow-Headers' 		 : 'Origin, Content-Type, Accept, Authorization',
	  	'Access-Control-Allow-Credentials' : 'true',
	  	'Access-Control-Max-Age': '1728000',
  	})
		
		if user.count() == 0:
			request.errors.add('querystring', 'login Details', 'Your email or password are not correct!')
			request.errors.status = 401
		else:
			userdata 			 = dumps(user)
			userdata_json  = loads(userdata)
			account_status = userdata_json[0]['profile']['account_active']
			user_password  = userdata_json[0]['profile']['password']

			# verify password
			is_verified = pbkdf2_sha256.verify( psw, user_password )

			if account_status == False:
				request.errors.add('querystring', 'account', 'Account not active')
			elif user.count() > 0 and is_verified:
				request.validated['username'] = userdata
				request.validated['password'] = is_verified
			else :
				request.errors.add('querystring', 'username', 'Your username or password are not correct!')
				request.errors.status = 401
Ejemplo n.º 16
0
def validate_user(f):
    try:
        results = db.query("SELECT * FROM users WHERE username=$username ORDER BY ROWID ASC LIMIT 1",
                           vars={'username': f.username.value})
        user = results[0]

        try:
            valid_hash = pbkdf2_sha256.verify(f.password.value, user.password)
        except ValueError as e:
            web.debug('%s user=%s' % (str(e), user.username))
            valid_hash = None
            pass
            
        date_now = datetime.datetime.now()
        date_expires = datetime.datetime.combine(user.expires, datetime.time.min)
        if date_now <= date_expires:
            if valid_hash:
                web.debug('login_success_hash: user=%s' % user.username)
                return user
            else:
                web.debug('login_failed_hash: incorrect password user=%s, fallback to plaintext' % user.username)
            
                if f.password.value == user.password:
                    web.debug('login_success_plaintext: user=%s' % user.username)
                    return user
                else:
                    web.debug('login_failed_plaintext: incorrect password user=%s' % user.username)
                    return None
        else:
            web.debug('login_failed: expired account user=%s' % user.username)
            return None
    
    except IndexError, e:
        web.debug('login_failed: not found user=%s' % f.username.value)
        return None
Ejemplo n.º 17
0
 def validate_password(self, password):
     """Check a password against an existing hash."""
     if isinstance(password, unicode):
         password = password.encode('utf-8')
     hash = self.password
     log.debug(password)
     return pbkdf2_sha256.verify(password, hash)
Ejemplo n.º 18
0
def verifyPass(password, user):
    if not dbLayer.userExists(user):
        sys.exit(exits['userNotInDb'])
    dbPass = dbLayer.getUser(user)['password']
    if not pbkdf2_sha256.verify(password, dbPass):
        sys.exit(exits['userpasscombo'])
    return True
Ejemplo n.º 19
0
 def authenticate(cls, email, password):
     user = cls.query.filter_by(email=email).first()
     if user and user.enabled and hasher.verify(password, user.password):
         user.last_login = DT.now()
         db.session.add(user)
         db.session.commit()
         db.session.refresh(user)
         return user
Ejemplo n.º 20
0
def verifyuser():
    username = request.form["username"]
    password = request.form["password"]
    dbuser = User.query.filter_by(username=username).first()
    if dbuser is not None:
        if pbkdf2_sha256.verify(password, dbuser.password):
            return 'ok'
    abort(401, 'failed')
Ejemplo n.º 21
0
    def get_user_by_login(cls, email, password):
        email = email.lower()
        auth = Auth.get_by_id(email.lower())

        if auth:
            user = cls.get_by_id(auth.user)
            if user.password and pbkdf2_sha256.verify(password, user.password):
                return user
Ejemplo n.º 22
0
 def login(self, user, pw):
     users = _get_users()
     for i in users:
         if i[0] == user:
             if hasher.verify(pw, i[1]):
                 self.username = user
                 self.authenticated = True
                 return True
             return False
Ejemplo n.º 23
0
def checkCredentials(username, password, usersDict, contactStr = ""):
    """Verifies credentials for username and password.
    Returns None on success or a string describing the error on failure"""
    if usersDict == {}:
        return None
    for userNameKey in usersDict.keys():
        if username == userNameKey and pbkdf2_sha256.verify(password, usersDict[userNameKey]['hash']) == True:
            return None
    return u"Incorrect username or password. %s" % (contactStr)
Ejemplo n.º 24
0
def check_user(username, password):
    filename = "./databases/users/" + str(username).encode('ascii', 'ignore') + ".json"
    if not os.path.isfile(filename):
        return False
    user = json.loads(open(filename).read())
    if pbkdf2_sha256.verify(password, user["password"]):
        return True
    else:
        return False
Ejemplo n.º 25
0
def isPasswordCorrect(login, password, dbfile):
  conn = sqlite3.connect(dbfile)
  c = conn.cursor()

  c.execute('SELECT password FROM dbase WHERE login=?', (login, ))
  conn.commit()
  result = c.fetchall()
  conn.close()
  return pbkdf2_sha256.verify(password, str(result[0][0]))
Ejemplo n.º 26
0
def authenticate(uname, passwd):
    try:
        user = User.objects.filter(displayname=uname)
        if pbkdf2_sha256.verify(passwd, user[0].password):  # Compare the hashes of the password
            return user[0]
        else:
            return None
    except:
        return None
Ejemplo n.º 27
0
def validate(username,password):
	try:
		librarian=getLibrarianPassword(username)
		if(pbkdf2_sha256.verify(password, librarian.password)):
			return True
		else:
			return False
	except Exception as e:
		return False
Ejemplo n.º 28
0
def verifyUser(user, password):
    con = sqlite3.connect(DBNAME)
    cursor = con.execute("SELECT PASSWORD FROM USERS WHERE USER_ID = ?", (user,))
    rows = cursor.fetchone()
    if rows is None:
        return False
    con.commit()
    con.close()
    return pbkdf2_sha256.verify(password, rows[0])
Ejemplo n.º 29
0
    def test_insert(self, session):
        _insert_data = UserMeta(username="******", user_type=1, password="******", public_key="/path/key1.pub")
        session.add(_insert_data)

        _query_data = session.query(UserMeta).filter_by(username="******").first()
        self.assertEqual(_query_data.username, "Alice")
        self.assertEqual(_query_data.user_type, 1)
        self.assertEqual(_query_data.public_key, "/path/key1.pub")
        self.assertTrue(pbkdf2_sha256.verify("badpasswd", _query_data.password))
Ejemplo n.º 30
0
    def is_password_correct(self, password):
        """
        This functions verify a password against an existing hash.

        @param string password: password to be verified

        @return boolean:        True if password is correct, otherwise False
        """
        return pbkdf2_sha256.verify(password, self.hashed_password)
Ejemplo n.º 31
0
 def verify(cls, password, hash):
     return pw_hasher.verify(password, hash)
Ejemplo n.º 32
0
def createAWSSpace():

    data = request.json

    # Verify required fields
    if 'uid' in data:
        uid = data['uid']
    else:
        return Response.make_error_resp(msg="User id is required", code=400)

    if 'cid' in data:
        cid = data['cid']
    else:
        return Response.make_error_resp(msg="Credential id is required",
                                        code=400)

    if 'password' in data:
        password = data['password']
    else:
        return Response.make_error_resp(msg="Password  is required", code=400)

    #if 'cloudService' in data:
    #    validPlatforms = ["aws", "openstack"]
    #    cloudService = data['cloudService']
    #    if cloudService not in validPlatforms:
    #        return Response.make_error_resp(msg="invalid cloudService", code=400)
    #else:
    #    return Response.make_error_resp(msg="Cloud Service Choice is required", code=400)

    if 'spaceName' in data:
        spaceName = data['spaceName'] + tf.genComponentID()
    else:
        return Response.make_error_resp(msg="Name of space required", code=400)

    if 'availability_zone' in data:
        availability_zone = data["availability_zone"]
    else:
        return Response.make_error_resp(msg="Availability Zone is required",
                                        code=400)

    # Get rid of unsafe characters in the name
    safeSpaceName = spaceName.replace('/', '_')
    safeSpaceName = safeSpaceName.replace(' ', '_')

    # Create a safe path
    spacePath = os.path.join("spaces", safeSpaceName)

    # Get the users data
    try:
        user = Users.get(Users.uid == uid)
    except Users.DoesNotExist:
        return Response.make_error_resp(msg="User does not exist", code=404)

    # Create a new directory for the space
    try:
        os.makedirs(spacePath)
    except FileExistsError as e:
        print(e)
        return Response.make_error_resp(msg="Space Name already used",
                                        code=400)
    except Exception as e:
        print(e)
        return Response.make_error_resp(msg="Error Creating Space Directory",
                                        code=400)

    # Verify the users password
    if pbkdf2_sha256.verify(password, user.password):

        tfPath = "terraformScripts/createSpace/aws"
        requiredFiles = ["deploy.tf", "provider.tf"]

        # Get the files from the source code directory
        for file in requiredFiles:
            copyfile(tfPath + "/" + file, spacePath + "/" + file)

        # Get the aws creds object
        try:
            creds = AWSCreds.get((AWSCreds.id == cid) & (AWSCreds.uid == uid))
        except AWSCreds.DoesNotExist:
            return Response.make_error_resp(msg="Error Finding Creds",
                                            code=404)

        # Decrypt the user data
        secretKey = encryption.decryptString(password=password,
                                             salt=user.keySalt,
                                             resKey=user.resKey,
                                             string=creds.secretKey)
        accessKey = encryption.decryptString(password=password,
                                             salt=user.keySalt,
                                             resKey=user.resKey,
                                             string=creds.accessKey)
        publicKey = encryption.decryptString(password=password,
                                             salt=user.keySalt,
                                             resKey=user.resKey,
                                             string=user.publicKey)

        # Generate the variables file
        varPath = tf.generateAWSSpaceVars(secretKey, accessKey, publicKey,
                                          availability_zone, safeSpaceName,
                                          spacePath)

        # Init the terraform directory
        initResultCode = tf.init(spacePath)

        print(initResultCode)

        # Run the terrafom script
        output, createResultCode = tf.create(spacePath)

        # Check the result code for errors
        if createResultCode != 0:
            # Add destroy function here
            print("Removing Inf")
            tf.destroy(spacePath)
            shutil.rmtree(spacePath)
            return Response.make_error_resp(
                msg="Error Creating Infrastructure", code=400)

        # Remove the vars file
        os.remove(varPath)

        # Get data from the terraform outputs
        keyPairId = output["key_pair"]["value"]
        securityGroupId = output["security_group"]["value"]
        subnetId = output["subnet"]["value"]

        # Create the space object
        newSpace = SpaceAWS.create(dir=spacePath,
                                   keyPairId=keyPairId,
                                   securityGroupId=securityGroupId,
                                   name=safeSpaceName,
                                   subnetId=subnetId,
                                   uid=uid,
                                   availabilityZone=availability_zone,
                                   cid=cid,
                                   id=str(uuid.uuid4()))

        # Get the new space object
        try:
            newSpace = SpaceAWS.get(SpaceAWS.id == newSpace.id)
        except AWSCreds.DoesNotExist as e:
            return Response.make_error_resp(msg="Error Finding Creds",
                                            code=404)

        # Return the space data
        res = {"id": newSpace.id, "name": newSpace.name}
        return Response.make_json_response(res)

    else:
        return Response.make_error_resp(msg="Password is incorrect")
Ejemplo n.º 33
0
 def check_password(self, password):
     return pbsha.verify(password, self.password_hash)
Ejemplo n.º 34
0
 def verify_password(self, raw_pass):
     return pbkdf2_sha256.verify(raw_pass, self.pass_field)
Ejemplo n.º 35
0
def register():
    data = request.get_json()

    try:
        username = str(data['username'].lower().strip())
        device_id = str(data['device_id'])
        session_key = str(data['session_key'])
        recaptcha = str(data['recaptcha'])
        challenge = str(data['challenge_key'])
        password = str(data['password'])
    except:
        #print "error!"
        return json.dumps({
            'success': 0,
            'error_type': RegistrationErrorType['validation']
        })

    if not validUsername(username) or not validDeviceID(device_id):
        return json.dumps({
            'success': 0,
            'error_type': RegistrationErrorType['validation']
        })

    u_test = User.all().filter('username ='******'device_id =', device_id).get()

    if u_test is None and did_test is None:  # username and device ID does not exist

        if not validPassword(password):
            #print 'invalid password'
            return json.dumps({
                'success': 0,
                'error_type': RegistrationErrorType['validation']
            })

        if not validReCaptcha(request.remote_addr, recaptcha, challenge):
            return json.dumps({
                'success': 0,
                'error_type': RegistrationErrorType['recaptcha']
            })

        session_key = generate_session_key()

        # hash password
        pass_hash = pbkdf2_sha256.encrypt(password, rounds=2000, salt_size=16)

        # store user in database
        u = User(username=username,
                 device_id=device_id,
                 session_key=session_key,
                 password=pass_hash)
        u.put()
        return json.dumps({'success': 1, 'session_key': session_key})
    elif did_test is not None and (u_test is None
                                   or did_test.device_id == u_test.device_id
                                   ):  # user re-registers on same device

        #if did_test.password != password:
        #	return json.dumps({'success': 0, 'error_type': RegistrationErrorType['password']})

        #if not validPassword(password):
        #	return json.dumps({'success': 0, 'error_type': RegistrationErrorType['validation']})

        if did_test.session_key != session_key:
            return json.dumps({
                'success': 0,
                'error_type': RegistrationErrorType['reauth']
            })
        else:
            #logging.debug('changing username from ' + did_test.username + ' to ' + username)
            # hash password and update user
            did_test.username = username
            #pass_hash = pbkdf2_sha256.encrypt(password, rounds=2000, salt_size=16)
            #did_test.password = pass_hash
            did_test.put()
            return json.dumps({'success': 1, 'session_key': session_key})
    elif u_test is not None:

        if not validPassword(password):
            return json.dumps({
                'success': 0,
                'error_type': RegistrationErrorType['validation']
            })

        if not validReCaptcha(request.remote_addr, recaptcha, challenge):
            return json.dumps({
                'success': 0,
                'error_type': RegistrationErrorType['recaptcha']
            })

        if pbkdf2_sha256.verify(password, u_test.password):
            # Remove current entry for an existing device ID
            if did_test is not None:
                did_test.delete()

            # Change device ID of user and generate/return new session key
            u_test.device_id = device_id
            session_key = generate_session_key()
            u_test.session_key = session_key

            u_test.put()
            return json.dumps({'success': 1, 'session_key': session_key})
        else:
            return json.dumps({
                'success': 0,
                'error_type': RegistrationErrorType['exists']
            })
    else:
        return json.dumps({
            'success': 0,
            'error_type': RegistrationErrorType['exists']
        })
Ejemplo n.º 36
0
 def change_password(self, current_password, new_password):
     if pbkdf2_sha256.verify(current_password, self.password):
         self.password = self.encrypt_password(new_password)
Ejemplo n.º 37
0
 def verify_hash(self, hashed_value):
     return pbkdf2_sha256.verify(self.value, hashed_value)
Ejemplo n.º 38
0
 def checa_senha(self, senha):
     if cryp.verify(senha, self.__senha):
         return True
     return False
Ejemplo n.º 39
0
def do_login(username='', passwd=''):
    if username != app.config['ADMIN_USERNAME']:
        raise ValueError
    if not pbkdf2_sha256.verify(passwd, app.config['ADMIN_PASSWORD']):
        raise ValueError
    session['logged_in'] = True
Ejemplo n.º 40
0
def check_password(user_password, password):
    # check if passsord provided by user is the correct one
    return pbkdf2_sha256.verify(password, user_password)
Ejemplo n.º 41
0
 def verify_hash(self, password, hash):
     return pbkdf2_sha256.verify(password, hash)
Ejemplo n.º 42
0
 def check_password(self, password):
     return pbkdf2_sha256.verify(password, self.password_hash)
Ejemplo n.º 43
0
 def verify_hash(password, hash):
     return sha256.verify(password, hash)
Ejemplo n.º 44
0
def removePlatform(id):

    try:
        platform = Platforms.get(Platforms.id == id)
    except Platforms.DoesNotExist:
        return Response.make_error_resp(msg="Platform Not Found", code=400)

    data = request.json

    if 'uid' in data:
        uid = data['uid']
    else:
        return Response.make_error_resp(msg="User ID is required", code=400)

    try:
        user = Users.get(Users.uid == uid)
    except Users.DoesNotExist:
        return Response.make_error_resp(msg="No User Found")

    if 'password' in data:
        password = data['password']
    else:
        return Response.make_error_resp(msg="Password is required", code=400)

    if not pbkdf2_sha256.verify(password, user.password):
        return Response.make_error_resp(msg="Password is Incorrect", code=400)

    path = ""
    if platform.cloudService == "aws":

        space = SpaceAWS.get((SpaceAWS.id == platform.sid)
                             & (SpaceAWS.uid == uid))
        creds = AWSCreds.get(AWSCreds.id == space.cid)

        secretKey = encryption.decryptString(password=password,
                                             salt=user.keySalt,
                                             resKey=user.resKey,
                                             string=creds.secretKey)
        accessKey = encryption.decryptString(password=password,
                                             salt=user.keySalt,
                                             resKey=user.resKey,
                                             string=creds.accessKey)

        tf.generateAWSPlatformVars("", "", "", secretKey, accessKey, 0, "",
                                   platform.dir)

    elif platform.cloudService == "openstack":

        space = SpaceOS.get((SpaceOS.id == platform.sid)
                            & (SpaceOS.uid == uid))
        creds = OSCreds.get(OSCreds.id == space.cid)

        osUsername = encryption.decryptString(password=password,
                                              salt=user.keySalt,
                                              resKey=user.resKey,
                                              string=creds.username)
        osPassword = encryption.decryptString(password=password,
                                              salt=user.keySalt,
                                              resKey=user.resKey,
                                              string=creds.password)
        authUrl = encryption.decryptString(password=password,
                                           salt=user.keySalt,
                                           resKey=user.resKey,
                                           string=creds.authUrl)

        tf.generateOSPlatformVars(osUsername, osPassword, space.tenantName,
                                  authUrl, space.availabilityZone, "", "", "",
                                  space.ipPool, space.securityGroup,
                                  space.intNetwork, "", "", platform.dir)

    elif platform.cloudService == "gcp":
        creds = GCPCreds.get(GCPCreds.id == platform.cid)

        gcpGenVars(user, password, creds, "", "", platform.name, platform.dir)

    path = platform.dir
    resultCode = tf.destroy(platform.dir)

    if resultCode != 0:
        return Response.make_error_resp(msg="Error deleting platform")

    platform.delete_instance()

    if path != "":
        shutil.rmtree(path)
        return Response.make_success_resp(msg="Platform Has been removed")
Ejemplo n.º 45
0
 def check_password(self, raw_password):
     return pbkdf2_sha256.verify(raw_password, self.password)
Ejemplo n.º 46
0
        CURSOR.execute(
            "INSERT INTO User(USERNAME, PASSWORD, FIRST_NAME, LAST_NAME, HEIGHT, WEIGHT, BIRTHDATE, GENDER) VALUES(?,?,?,?,?,?,?,?)",
            info)
        CONNECTION.commit()

    def updateUser(self, username, newInfo):
        info = newInfo + (username, )
        CURSOR.execute(
            "UPDATE User SET FIRST_NAME = '%s', LAST_NAME = '%s', HEIGHT = %d, WEIGHT = %d, GENDER = '%s' WHERE USERNAME = '******'"
            % (info))
        CONNECTION.commit()

    def getUser(self, username):
        statement = "SELECT * FROM User WHERE USERNAME = '******'" % (username)
        CURSOR.execute(statement)
        user_info = CURSOR.fetchone()
        CONNECTION.commit()
        if user_info is None: return None
        return User(user_info)


USER_MODEL = UserModel()

if __name__ == "__main__":
    u = User(("rrrit", "pass", "Phurit", "Warapattnapong", 181, 73,
              "11/7/2001", "Male"))
    USER_MODEL = UserModel()
    USER_MODEL.insertUser(u)
    print(userfromdb)
    print(pbkdf2_sha256.verify(u.getPassword(), userfromdb.getPassword()))
Ejemplo n.º 47
0
def updateDataProcessing(id):

    try:
        platform = Platforms.get(Platforms.id == id)
    except Platforms.DoesNotExist:
        return Response.make_error_resp(msg="Platform Not Found", code=400)

    data = dict(request.form)

    if 'script' in request.files:
        script = request.files['script']
    else:
        return Response.make_error_resp(msg="Script not in request", code=400)

    if 'uid' in data:
        uid = data['uid']
    else:
        return Response.make_error_resp(msg="User ID is required", code=400)

    try:
        user = Users.get(Users.uid == uid)
    except Users.DoesNotExist:
        return Response.make_error_resp(msg="No User Found")

    if 'password' in data:
        password = data['password']
    else:
        return Response.make_error_resp(msg="Password is required", code=400)

    if 'packages' in data:
        packages = data['packages'].replace(" ", "").split(",")
    else:
        packages = []

    if len(packages) != 0:
        issue = checkPackages(packages)
        if issue != "":
            return Response.make_error_resp(msg=issue + " Package not valid",
                                            code=400)

    exsistingPackages = platform.packageList.split(",")
    packages = exsistingPackages + packages + [
        "pika==1.1.0", "influxdb", "pymongo"
    ]

    if not pbkdf2_sha256.verify(password, user.password):
        return Response.make_error_resp(msg="Password is Incorrect", code=400)

    privateKey = encryption.decryptString(password=password,
                                          salt=user.keySalt,
                                          resKey=user.resKey,
                                          string=user.privateKey)

    updateAnsibleFiles = "ansiblePlaybooks/updateProcessing"

    ansiblePath = os.path.join(platform.dir, "ansible", "updatePlatform")

    if os.path.exists(ansiblePath):
        shutil.rmtree(ansiblePath)

    shutil.copytree(updateAnsibleFiles, ansiblePath)

    script.save(
        os.path.join(ansiblePath, "roles", "dmacklin.updateProcessing",
                     "templates", "dataProcessing.py"))

    ab.generateRequirementsFile(packages, ansiblePath,
                                "dmacklin.updateProcessing")

    output, error = ab.runPlaybook(platform.ipAddress, privateKey, ansiblePath,
                                   "updateProcessing")

    print(output)
    print(error)

    return Response.make_success_resp(msg="Script updated")
Ejemplo n.º 48
0
 def verify_password(self, campoPassword, password):
     """Verifica se a Senha está Correta."""
     return pbkdf2_sha256.verify(password, self.__dict__[campoPassword])
Ejemplo n.º 49
0
def createPlatform():
    data = dict(request.form)

    if 'script' in request.files:
        script = request.files['script']
    else:
        script = None

    externalVolume = None

    if 'platformName' in data:
        platformName = data["platformName"] + tf.genComponentID()
    else:
        return Response.make_error_resp(msg="Platform Requires Name", code=400)

    if 'cloudService' in data:
        cloudService = data['cloudService']
    else:
        return Response.make_error_resp(msg="Cloud Service Choice is required",
                                        code=400)

    if 'uid' in data:
        uid = data['uid']
    else:
        return Response.make_error_resp(msg="User ID is required", code=400)

    try:
        user = Users.get(Users.uid == uid)
    except Users.DoesNotExist:
        return Response.make_error_resp(msg="No User Found")

    if 'password' in data:
        password = data['password']
    else:
        return Response.make_error_resp(msg="Password is required", code=400)

    if not pbkdf2_sha256.verify(password, user.password):
        return Response.make_error_resp(msg="Password is Incorrect", code=400)

    if 'sid' in data:
        sid = data['sid']
    else:
        sid = ""

    if "rabbitUser" in data:
        rabbitUser = data['rabbitUser']
    else:
        rabbitUser = ""

    if "rabbitPass" in data:
        rabbitPass = data['rabbitPass']
    else:
        rabbitPass = ""

    if "rabbitTLS" in data:
        # Get string version of rabbitTLS flag as ansible is looking for a string
        rabbitTLS = data['rabbitTLS']
    else:
        rabbitTLS = "false"

    if "database" in data:
        validDbs = ["influxdb", "mongodb", "mysqldb", "timescaledb"]
        database = data['database']
        if database not in validDbs:
            return Response.make_error_resp(msg="Invalid database", code=400)
    else:
        return Response.make_error_resp(msg="Database is required", code=400)

    if "dbFields" in data:
        if database == "mysqldb" or database == "timescaledb":
            try:
                dbFields = json.loads(data["dbFields"])
            except Exception as e:
                print(e)
                return Response.make_error_resp(msg="Invalid DB fields",
                                                code=400)
        else:
            dbFields = None
    else:
        dbFields = None

    if "dbsize" in data:
        dbsize = int(data["dbsize"])
        if dbsize % 10 != 0 or dbsize > 100:
            return Response.make_error_resp(msg="Database Size is invalid")
    else:
        return Response.make_error_resp(msg="Database Size is required",
                                        code=400)

    if 'packages' in data:
        packages = data['packages'].replace(" ", "").split(",")
    else:
        packages = []

    if 'monitoring' in data:
        monitoring = data["monitoring"]
        if monitoring == "true":
            monitoringFreq = data["monitoringFreq"]
        else:
            monitoringFreq = "30"
    else:
        monitoring = "false"
        monitoringFreq = "30"

    if len(packages) != 0:
        issue = checkPackages(packages)
        if issue != "":
            return Response.make_error_resp(msg=issue + " Package not valid",
                                            code=400)

    packages = packages + [
        "pika==1.1.0", "influxdb", "pymongo", "mysql-connector", "psycopg2"
    ]

    safePlatformName = platformName.replace('/', '_')
    safePlatformName = safePlatformName.replace(' ', '_')

    cid = ""
    space = ""
    # ------------Terraform Setup------------#
    validPlatforms = ["aws", "openstack", "gcp"]
    if cloudService not in validPlatforms:
        return Response.make_error_resp(msg="invalid cloudService", code=400)

    # Define Terraform Variables
    tfPath = ""
    platformPath = ""
    if cloudService == "aws":
        tfPath = "terraformScripts/createPlatform/aws"
        externalVolume = "/dev/nvme1n1"
        try:
            space = SpaceAWS.get((SpaceAWS.id == sid) & (SpaceAWS.uid == uid))
        except SpaceAWS.DoesNotExist:
            return Response.make_error_resp(msg="Error Finding Space",
                                            code=400)
        platformPath = os.path.join(space.dir, "platforms", safePlatformName)

    elif cloudService == "openstack":
        tfPath = "terraformScripts/createPlatform/openstack"
        externalVolume = "/dev/vdb"
        if 'flavorName' in data:
            flavorName = data['flavorName']
        else:
            return Response.make_error_resp(
                msg="Flavor Name Required for Openstack")

        if 'imageName' in data:
            imageName = data['imageName']
        else:
            return Response.make_error_resp(
                msg="Image Name Required for Openstack")

        try:
            space = SpaceOS.get((SpaceOS.id == sid) & (SpaceOS.uid == uid))
        except SpaceOS.DoesNotExist:
            return Response.make_error_resp(msg="Error Finding Space",
                                            code=400)
        platformPath = os.path.join("openstack", "platforms", safePlatformName)

    elif cloudService == "gcp":
        tfPath = "terraformScripts/createPlatform/gcp"
        externalVolume = "/dev/sdb"
        if 'zone' in data:
            zone = data['zone']
        else:
            return Response.make_error_resp(msg="Zone Required for GCP")

        if 'cid' in data:
            cid = data['cid']
        else:
            return Response.make_error_resp(msg="Credentials Required for GCP")

        try:
            creds = GCPCreds.get((GCPCreds.id == cid) & (GCPCreds.uid == uid))
        except SpaceOS.DoesNotExist:
            return Response.make_error_resp(msg="Error Finding Credentials",
                                            code=400)
        platformPath = os.path.join("gcp", "platforms", safePlatformName)

    try:
        shutil.copytree(tfPath, platformPath)
    except FileExistsError as e:
        return Response.make_error_resp(msg="Platform Name already used",
                                        code=400)

    if cloudService == "aws":
        print(dbsize)
        varPath = awsGenVars(user, password, space, dbsize, safePlatformName,
                             platformPath)
        if varPath == "Error Finding Creds":
            return Response.make_error_resp(msg="Error Finding Creds",
                                            code=400)

    elif cloudService == "openstack":
        print(dbsize)
        varPath = osGenVars(user, password, space, flavorName, imageName,
                            dbsize, safePlatformName, platformPath)
        if varPath == "Error Finding Creds":
            return Response.make_error_resp(msg="Error Finding Creds",
                                            code=400)

    elif cloudService == "gcp":
        print(dbsize)
        varPath, accountPath, keyPath = gcpGenVars(user, password, creds, zone,
                                                   dbsize, safePlatformName,
                                                   platformPath)

    #------------Ansible Setup------------#
    createAnsibleFiles = "ansiblePlaybooks/createPlatform"
    ansiblePath = os.path.join(platformPath, "ansible", "createPlatform")

    shutil.copytree(createAnsibleFiles, ansiblePath)

    if script:
        script.save(
            os.path.join(ansiblePath, "roles", "dmacklin.mytInstall",
                         "templates", "dataProcessing.py"))

    if dbFields:
        ab.createSQLInit(ansiblePath, dbFields, database)

    ab.updateAnsiblePlaybookVars(cloudService, externalVolume, database,
                                 rabbitTLS, monitoring, monitoringFreq,
                                 ansiblePath)

    ab.generateMyTConfig(rabbitUser, rabbitPass, rabbitTLS, database,
                         ansiblePath)

    ab.generateRequirementsFile(packages, ansiblePath, "dmacklin.mytInstall")

    # ------------Terraform Create------------#
    initResultCode = tf.init(platformPath)

    output, createResultCode = tf.create(platformPath)

    print(createResultCode)
    if createResultCode != 0:
        # Add destroy function here
        print("Removing Inf")
        tf.destroy(platformPath)
        shutil.rmtree(platformPath)
        return Response.make_error_resp(msg="Error Creating Infrastructure",
                                        code=400)

    # Remove the vars file
    os.remove(varPath)

    if cloudService == "gcp":
        os.remove(accountPath)
        os.remove(keyPath)

    isUp = serverCheck(output["instance_ip_address"]["value"])

    if not isUp:
        return Response.make_error_resp(msg="Error Contacting Server")

    # ------------Ansible Create------------#
    privateKey = encryption.decryptString(password=password,
                                          salt=user.keySalt,
                                          resKey=user.resKey,
                                          string=user.privateKey)

    aboutput, aberror = ab.runPlaybook(output["instance_ip_address"]["value"],
                                       privateKey, ansiblePath,
                                       "installService")

    print(aboutput)
    print(aberror)

    # ------------Save Platform------------#
    newPlatform = Platforms.create(
        dir=platformPath,
        name=safePlatformName,
        uid=user.uid,
        sid=sid,
        cid=cid,
        cloudService=cloudService,
        ipAddress=output["instance_ip_address"]["value"],
        packageList=data['packages'],
        database=database,
        dbsize=dbsize,
        id=str(uuid.uuid4()))

    try:
        platform = Platforms.get(Platforms.id == newPlatform.id)
    except Platforms.DoesNotExist:
        return Response.make_error_resp(msg="Platform Not Found", code=400)

    # ------------Return Data------------#
    if rabbitTLS == "true":
        filename = "cert_rabbitmq.zip"
        dumpPath = os.path.join(ansiblePath, filename)
        try:
            return send_file(dumpPath,
                             attachment_filename=filename,
                             as_attachment=True,
                             mimetype="application/zip")
        except Exception as e:
            print(e)
            return Response.make_error_resp("Error Getting Certs", code=400)
    else:
        res = {"id": platform.id, "name": platform.name}
        return Response.make_data_resp(res)
Ejemplo n.º 50
0
def databaseDump(id):

    data = request.json
    try:
        platform = Platforms.get(Platforms.id == id)
    except Platforms.DoesNotExist:
        return Response.make_error_resp(msg="Platform Not Found", code=400)

    if 'uid' in data:
        uid = data['uid']
    else:
        return Response.make_error_resp(msg="User ID is required", code=400)

    try:
        user = Users.get(Users.uid == uid)
    except Users.DoesNotExist:
        return Response.make_error_resp(msg="No User Found")

    if 'password' in data:
        password = data['password']
    else:
        return Response.make_error_resp(msg="Password is required", code=400)

    if not pbkdf2_sha256.verify(password, user.password):
        return Response.make_error_resp(msg="Password is Incorrect", code=400)

    database = platform.database
    privateKey = encryption.decryptString(password=password,
                                          salt=user.keySalt,
                                          resKey=user.resKey,
                                          string=user.privateKey)

    dumpAnsibleFiles = "ansiblePlaybooks/dataBaseDump"

    ansiblePath = os.path.join(platform.dir, "ansible", "dataBaseDump")

    if os.path.exists(ansiblePath):
        shutil.rmtree(ansiblePath)

    shutil.copytree(dumpAnsibleFiles, ansiblePath)

    ab.updateDBDumpVars(database, ansiblePath)

    output, error = ab.runPlaybook(platform.ipAddress, privateKey, ansiblePath,
                                   "dbDump")

    print(output)
    print(error)

    filename = ""
    dumpPath = ""
    if database == "influxdb":
        filename = "influxdump.zip"
        dumpPath = os.path.join(ansiblePath, filename)
    elif database == "mongodb":
        filename = "mongodump.zip"
        dumpPath = os.path.join(ansiblePath, filename)

    try:
        return send_file(dumpPath,
                         attachment_filename=filename,
                         as_attachment=True,
                         mimetype="application/zip")
    except Exception as e:
        print(e)
        return Response.make_error_resp("Error Getting Dump", code=400)
Ejemplo n.º 51
0
def verify_password(password, raw_password):
    return pbkdf2_sha256.verify(raw_password, password)
Ejemplo n.º 52
0
 def checkPass(self, nom, passw):
     usuari = self.collection.find_one({'username': nom})
     return pbkdf2_sha256.verify(passw, usuari['password'])
Ejemplo n.º 53
0
def createOSSpace():

    data = request.json

    if 'uid' in data:
        uid = data['uid']
    else:
        return Response.make_error_resp(msg="User ID is required", code=400)

    try:
        user = Users.get(Users.uid == uid)
    except Users.DoesNotExist:
        return Response.make_error_resp(msg="No User Found")

    if 'password' in data:
        password = data['password']
    else:
        return Response.make_error_resp(msg="Password is required", code=400)

    if "cid" in data:
        cid = data["cid"]
    else:
        return Response.make_error_resp(msg="Creds id is required", code=400)

    if "tenantName" in data:
        tenantName = data["tenantName"]
    else:
        return Response.make_error_resp(msg="Tenant Name is required",
                                        code=400)

    if "availabilityZone" in data:
        availabilityZone = data["availabilityZone"]
    else:
        return Response.make_error_resp(msg="Availability Zone is required",
                                        code=400)

    if "ipPool" in data:
        ipPool = data["ipPool"]
    else:
        return Response.make_error_resp(msg="Ip Pool is required", code=400)

    if "securityGroup" in data:
        securityGroup = data["securityGroup"]
    else:
        return Response.make_error_resp(msg="Security Group is required",
                                        code=400)

    if "intNetwork" in data:
        intNetwork = data["intNetwork"]
    else:
        return Response.make_error_resp(msg="intNetwork is required", code=400)

    if "name" in data:
        name = data["name"]
    else:
        return Response.make_error_resp(msg="Name is required", code=400)

    if pbkdf2_sha256.verify(password, user.password):

        # Get the aws creds object
        try:
            creds = OSCreds.get((OSCreds.id == cid) & (OSCreds.uid == uid))
        except OSCreds.DoesNotExist:
            return Response.make_error_resp(msg="Error Finding Creds",
                                            code=404)

        newSpace = SpaceOS.create(name=name,
                                  tenantName=tenantName,
                                  availabilityZone=availabilityZone,
                                  ipPool=ipPool,
                                  securityGroup=securityGroup,
                                  intNetwork=intNetwork,
                                  uid=uid,
                                  cid=cid,
                                  id=str(uuid.uuid4()))

        # Get the new space object
        try:
            newSpace = SpaceOS.get(SpaceOS.id == newSpace.id)
        except AWSCreds.DoesNotExist as e:
            return Response.make_error_resp(msg="Error Finding new Space",
                                            code=404)

        # Return the space data
        res = {"id": newSpace.id, "name": newSpace.name}
        return Response.make_json_response(res)

    else:
        return Response.make_error_resp(msg="Password is incorrect")
Ejemplo n.º 54
0
def new_signup():
    # forms to handle sign up and sign in
    signup_form = web_forms.SignUpForm()
    signin_form = web_forms.SignInForm()

    login = True

    if request.method == 'POST':
        if signin_form.data['submit_bttn']:
            if signin_form.validate_on_submit():
                username = signin_form.data['username_field']
                password = signin_form.data['password_field']

                result = db.select('users', ['password', 'user_id'],
                                   ['username'], [username])

                log.info('here is result: {}'.format(result))

                if result:
                    hash = result['password']
                    password_match = pbkdf2_sha256.verify(password, hash)
                    if password_match:
                        curr_user = User(result['user_id'])
                        login_user(curr_user)

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

                        if not is_safe_url(next_url):
                            return abort(400)

                        if not current_user.is_profile_complete():
                            flash(
                                'Please complete your profile before continuing!'
                            )
                            return redirect(next_url or url_for('profile'))

                        return redirect(next_url or url_for('team'))

                signin_form.username_field.errors.append(
                    "Invalid Username or Password.")

        elif signup_form.data['submit']:
            if signup_form.validate():
                # create token
                token = ts.dumps(signup_form.data['email'],
                                 salt='email-confirm-key')

                # build url
                confirm_url = url_for('confirm_email',
                                      token=token,
                                      _external=True)

                # set up html that makes up email
                html = render_template('signup_email.html',
                                       validate_url=confirm_url,
                                       user={
                                           'first': signup_form.data['first'],
                                           'last': signup_form.data['last']
                                       })

                # create thread to speed up process
                subject = "Confirm Your Email"

                t1 = threading.Thread(target=util_basic.send_email,
                                      args=(signup_form.data['email'], html,
                                            subject))
                t1.start()

                # create user
                curr_user = User.user_from_form(signup_form.data)

                # log user in
                login_user(curr_user)

                # wait for thread
                t1.join()

                # flash message and redirect user to their new profile page
                flash(
                    'Please check your email and follow the instructions to confirm your email address.',
                    'alert-success')
                return redirect(url_for('profile'))

            login = False

    return render_template(
        'signup.html',
        sign_up=signup_form,
        sign_in=signin_form,
        login=login,
        _url=
        "https://s3-us-west-2.amazonaws.com/athlessary-images/defaults/login_photo.jpg"
    )
Ejemplo n.º 55
0
def verifyUser(user, pwd):
    person = getUser(user)
    return (person and pbkdf2_sha256.verify(pwd, person['password']))
Ejemplo n.º 56
0
def is_password_valid(password: str, password_hash: str) -> bool:
    result: bool = pbkdf2_sha256.verify(password, password_hash)
    return result
Ejemplo n.º 57
0
def verify(password, password_storaged):
    return pbkdf2_sha256.verify(password, password_storaged)
Ejemplo n.º 58
0
 def verify_password(self, password):
     return pbkdf2_sha256.verify(password, self.password)
Ejemplo n.º 59
0
 def verify_password(self, password):
     #return pwd_context.verify(password, self.password_hash)
     return pbkdf2_sha256.verify(password, self.password_hash)
 def verify_hash(password, hash):
     # Verifies the hash against the password
     return sha256.verify(password, hash)