Exemplo n.º 1
0
    def post(self):
        ret = {}
        ret_code = HTTP_OK

        try:
            pseudo = self.get_argument(PSEUDO_KEY)
            password = self.get_argument(PASSWORD_KEY)

            cached_usr = self.application.cache.get_user(pseudo)
            is_auth = False
            if cached_usr is not None:
                if sha512_crypt.verify(password, cached_usr[PASSWHASH_KEY]):
                    is_auth = True
            else:
                us = self.ormdb.query(User).filter_by(pseudo=pseudo).first()
                if us is not None:
                    self.application.cache.set_user(us)
                    if sha512_crypt.verify(password, us.passwhash):
                        is_auth = True
                else:
                    ret_code = HTTP_NOT_FOUND
                    ret = {ERROR_KEY: ENTITY_NOT_FOUND_MSG}

            ret = {RESSOURCE_KEY: is_auth}

        except tornado.web.MissingArgumentError as e:
            ret_code = HTTP_BAD_REQUEST
            ret = {ERROR_KEY: MISSING_ARGS_MSG}

        self.respond(ret, ret_code)
Exemplo n.º 2
0
    def post(self):
        logging.info("Initiating PasswordHandler post")

        data = json.loads(self.request.body)
        if "username" not in data:
            raise HTTPError(400, reason="Missing username in body request.")

        if "password" not in data:
            raise HTTPError(400, reason="Missing password in body request.")

        username = data["username"]
        password = data["password"]

        user = yield self.settings["database"].Users.find_one(
            {"username": username})
        if not user:
            logging.debug("Username '%s' not found.", username)
            raise HTTPError(401, reason="Invalid username or password.")

        encoded_user_password = user["password"]["hash"].encode("utf-8")
        if sha512_crypt.verify(
            (password + user["password"]["salt"]).encode("utf-8"),
                encoded_user_password):
            token = yield self.authenticate_user(user)
            self.write(token)
            self.flush()
        else:
            logging.info("Invalid password for user '%s'.", username)
            raise HTTPError(401, reason="Invalid username or password.")
Exemplo n.º 3
0
Arquivo: mrpg.py Projeto: mrsmyl/mRPG
 def dologout():
     if (lenow >= 3):
         logout_char_name = msg_split[1]
         logout_password = msg_split[2]
         self.db = DBPool('mrpg.db')
         char_exists = yield self.db.does_char_name_exist(logout_char_name)
         self.db.shutdown("")
         if(char_exists[0][0] == 0):
             self.privateMessage(user, "There is not a character by that name.")
         else:
             self.db = DBPool('mrpg.db')
             is_online = yield self.db.is_char_online(logout_char_name)
             self.db.shutdown("")
             if(is_online[0][0]==1):
                 self.db = DBPool('mrpg.db')
                 passhash = yield self.db.get_password(logout_char_name)
                 passhash = passhash[0][0]
                 self.db.shutdown("")
                 if (sc.verify(logout_password, passhash)):
                     self.db = DBPool('mrpg.db')
                     self.db.executeQuery("UPDATE users SET online = 0, hostname = ? WHERE char_name = ?",(hostname,logout_char_name))
                     self.db.shutdown("")
                     self.privateMessage(user, "You are now logged out.")
                 else:
                     self.privateMessage(user, "Password incorrect.")
             else:
                 self.privateMessage(user, "You are not logged in")
     else:
         self.privateMessage(user, "Not enough information was supplied.")
Exemplo n.º 4
0
def handle_login(params, json_data):
    if (not _check_flood_protect(params['ip'][0])):
        return (False, '')
    if 'username' not in params or 'password' not in params:
        return (False, '')

    try:
        q = Query(
            'SELECT gebr_id, gebr_wachtwoord FROM tblgebruiker WHERE gebr_naam = %s'
        )
        q.run((params['username'][0], ))
        results = q.rows()
    except DatabaseError:
        raise InternalServerError

    if (len(results) != 1):
        _add_flood_protect(params['ip'][0])
        return (False, '')
    if not sha512_crypt.verify(params['password'][0], results[0][1]):
        _add_flood_protect(params['ip'][0])
        return (False, '')

    #Generate session key
    session_key = _create_session(params['ip'][0], results[0][0])

    return (True, session_key)
Exemplo n.º 5
0
def signin():
    form = Signin(request.form)
    if request.method == 'GET':  # make sure the method used is define above
        return render_template('signin.html', form=form), print(
            "you are under the signin page now, well done mrbacco")
    if request.method == 'POST' and form.validate():
        # the following are the data from the init form
        username = form.username.data
        password_form = form.password.data
        print("these are the email and password inserted", username,
              password_form)

        user_db = mycol_u.find_one({'username': username})
        #for key, value in user_db.items():
        #print ("these are the fields in the db ", key, value)

        if user_db is None:
            flash("No USER FOUND!!, please try again or signup!", "danger")
            return render_template('signin.html', form=form), print(
                "user not found, flashed a message on the web page")

        if sha512_crypt.verify(password_form, user_db['password']):

            #setting the session on for this user till he/she signs out!!
            session["logged_in"] = True
            session["username"] = username

            flash("You are now logged in, start web scraping below", "success")
            return redirect(url_for("dashboard")), print(
                "Password match: flashing a message")
        else:
            flash("credential not correct, please try again", "danger")

    return render_template('signin.html', form=form)
Exemplo n.º 6
0
    def post(self):
        logging.info("Initiating PasswordHandler post")

        data = json.loads(self.request.body)
        if "username" not in data:
            raise HTTPError(400, reason="Missing username in body request.")

        if "password" not in data:
            raise HTTPError(400, reason="Missing password in body request.")

        username = data["username"]
        password = data["password"]

        user = yield self.settings["database"].Users.find_one({"username": username})
        if not user:
            logging.debug("Username '%s' not found.", username)
            raise HTTPError(401, reason="Invalid username or password.")

        encoded_user_password = '******'.format(user["password"]["rounds"], user["password"]["hash"])
        if sha512_crypt.verify((password + user["password"]["salt"]).encode("utf-8"), encoded_user_password):
            token = yield self.authenticate_user(user)
            self.write(token)
            self.flush()
        else:
            logging.info("Invalid password for user '%s'.", username)
            raise HTTPError(401, reason="Invalid username or password.")
Exemplo n.º 7
0
    def login(self):
        facade = Facade()

        hash = self.gerar_hash()
        response.set_cookie("KIM", hash, path='/', secret=KEY_HASH)

        observador_logado = facade.search_observador_email_facade(
            email=self.email)
        if observador_logado != None:
            if sha512_crypt.verify(self.senha, observador_logado['senha']):
                response.set_cookie("BUMBA",
                                    observador_logado,
                                    path='/',
                                    secret=hash)
                now = datetime.now()
                facade.login_date_facade(observador_logado['id'], now)
                facade.create_estrutura_facade(
                    tipo_estrutura=TIPO_ESTRUTURA['historico'],
                    nome_usuario=observador_logado['nome'],
                    tipo_usuario=observador_logado['tipo'])

                return PAGINA_INICIAL[TIPO_USUARIOS_ID[
                    observador_logado['tipo']].lower()]
            else:
                return PAGINA_INICIAL['error']
        else:
            print("Usuario não encontrado !")
            return PAGINA_INICIAL['error']
Exemplo n.º 8
0
    def is_login_valid(email, password):
        """
        This method verifies that an e-mail/password combo (as sent by the site forms) is valid or not.
        Checks that the e-mail exists, and that the password associated to that e-mail is correct.
        :param email: The user's email
        :param password: A sha512 hashed password
        :return: True if valid, False otherwise
        """
        user_data = Database.find_one(UserConstants.COLLECTION,
                                      {"email": email})
        admin_created_user = Database.find_one(UserConstants.COLLECTION, {
            "email": email,
            "admin_created": "Yes"
        })
        if user_data is None:
            # Tell the user that their e-mail doesn't exist
            raise UserErrors.UserNotExistsError(
                "Email is not recognized.  Please use link below to sign-up if you have not created an account."
            )
        if admin_created_user is not None:
            # Tell the user to sign up
            raise UserErrors.AdminCreatedUserError(
                "Your account was created by an admin.  Please register with HHT to enjoy the full functionality of the site."
            )
        if not sha512_crypt.verify(password, user_data['password']):
            # Tell the user that their password is wrong
            raise UserErrors.IncorrectPasswordError(
                "Password does not match the one registered.")

        return True
Exemplo n.º 9
0
def processLogin(form):
    username = sanitize(form.username.data)
    password = sanitize(form.password.data)
    persistent = form.persistent.data

    status = False
    try:
        cursor, dbconn = dbConnection()
        query = "SELECT user_id, username, password FROM users WHERE username = %s"
        query_result = cursor.execute(query, [username])
        query_result = cursor.fetchone()
        user_id = query_result[0]
        query_result = query_result[2]
    except:
        status = "No Such User Exists..!!"
    else:
        if sha512_crypt.verify(password, query_result):
            session['logged_in'] = True
            session['username'] = username
            if persistent:
                session.permanent = True
            status = True
        else:
            status = "Invalid Credentials..!!"
        query = "SELECT reviewer_id, subject from reviewers where user_id = %s"
        query_result = cursor.execute(query, [user_id])
        if int(query_result) > 0:
            query_result = cursor.fetchone()
            session['reviewer'] = query_result[0]
            session['subject'] = query_result[1]
    cursor.close()
    dbconn.close()
    return status
Exemplo n.º 10
0
def verify_login(user, password):
    ###
    # Summary:
    #   Diese Funktion überprüft die eingegebenen Login Parameter und checkt ob sie im passwd.json vorhanden sind
    # Args:
    #   user(string) = Eingegebner Username
    #   password(string) = Eingegebenes Passwort im cleartext
    # Return:
    #   Boolscher Wert: True = Credentials sind korrekt; False = Credentials sind falsch
    ###

    # Wenn irgendetwas falsch ist soll False zurückgegeben werden. z.B wenn User nicht gefunden wird
    # deshalb wird ein try verwendet, damit wird der Fehler bei einem nicht existierenden Key im Dict abgefangen
    try:
        f_info = load_user()
        for k, v in f_info.items():
            if k == user:
                s_user = k
                s_pass = v[0]
                # Wenn der Username und der Passworthash korrekt sind wird True zurückgegeben
        if s_user == user and sha512_crypt.verify(password, s_pass) is True:
            return True
        else:
            # Wenn die Daten falsch ist -> False
            return False
    # Falls im während der Überprüfung des User, Passwort ein Fehler passiert, gibt es kein erfolgreiches login
    except:
        return False
def login():
    form = LoginForm()
    context = {
        'copyright': COPYRIGHT,
        'form': form
    }
    if request.method == 'POST':
        if context['form'].validate():
            # Get user info from database:
            user = db.session.query(User).filter_by(
                email = context['form'].email.data).first()
            pw = context['form'].password.data
            # Check that user exists in database:
            if user is not None:
                # verify input password matches stored hash:
                if sha512_crypt.verify(pw, user.pwhash):
                    # Log user in:
                    session['logged_in'] = True
                    return redirect(url_for('index'))
                else:
                    flash('Incorrect password.')
                    return render_template('login.html', **context)
            else:
                flash('Email address not found.')
                return render_template('login.html', **context)
        else:
            return render_template('login.html', **context)
    elif request.method == 'GET':
        return render_template('login.html', **context)
Exemplo n.º 12
0
def login():
    error = None  #declaration for this variable
    if request.method == 'POST':
        username = request.form.get('username')
        password_req = request.form.get('password')
        newuser = username
        if request.form.get('username') is not "" and request.form.get(
                'password') is not "":
            newuser = mycol.find_one({'username': username})
            if newuser is not None:
                password = newuser[
                    "password"]  #return PasswordField for that username
                print("inserted username is: ", newuser)
            else:
                error = 'Invalid credentials again 2'
                print("user not present therefore moving on")
                return render_template('login.html', error=error)
            if sha512_crypt.verify(password_req, password):
                print("password matched", password_req, password)
                #creating a session for the user just logged in
                session["logged_in"] = True
                session["username"] = username
                return redirect(url_for("dashboard"))
                print("under the dashboard page now")
            else:
                error = 'Invalid credentials again 1'
                print("password DON'T match", password_req, password)
                return render_template('login.html', error=error)
        else:
            error = 'Empty credentials, try again please.'
            print(error, "inserted username is: ", newuser)
    return render_template('login.html', error=error)
Exemplo n.º 13
0
def main():
	try:
		form = cgi.FieldStorage()
		email= form.getvalue('email')
		password = form.getvalue('password')
		
		cur = con.cursor()
		command = "SELECT password FROM Users WHERE email = %s";
		cur.execute(command, (email))
		row = cur.fetchone()
		
		if (row != None):
			enc_password = row[0]
			verify = sha512_crypt.verify(password, enc_password)
			if (verify):
				sess = session.Session(expires=365*24*60*60, cookie_path='/')
				sess.data['lastvisit'] = repr(time.time())
				sess.data['user'] = email
				print "Location: home.py?\r\n"
			else:
				print "Location: login.py?redirect=0\r\n"
		else:
			print "Location: login.py?redirect=0\r\n"
	except KeyError:
		print "Location: login.py\r\n"
Exemplo n.º 14
0
def update_password(username: str, password: str, new_password: str,
                    salt: str) -> User:
    """
    Update a user's password.

    :param username: The user's username.
    :type username: str
    :param password: The user's current password.
    :type password: str
    :param new_password: The user's new password.
    :type new_password: str
    :param salt: The user's salt.
    :type salt: str
    :return: User
    """
    user = User.query.filter(User.username == username).one()

    if sha512_crypt.verify(salt_password(password, salt), user.password):
        user.password = sha512_crypt.hash(salt_password(new_password, salt))
        db.session.add(user)
        db.session.commit()

        return user
    else:
        raise PasswordException(message='Current password is not correct.')
Exemplo n.º 15
0
 def authUser(self, name, password):
     c = self._conn.cursor()
     c.execute("SELECT password FROM user WHERE name = ? LIMIT 1", (name, ))
     r = c.fetchone()
     if r is None:
         return False
     return sha512_crypt.verify(password, r[0])
Exemplo n.º 16
0
Arquivo: auth.py Projeto: 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
Exemplo n.º 17
0
def authenticate(session, Account, **kwargs):
    login = kwargs.get('login')
    password = kwargs.get('password')
    user = session.query(Account).filter(Account.login == login).one()
    if not sha512_crypt.verify(password, user.password):
        raise Exception("No user with this password")
    return user
Exemplo n.º 18
0
Arquivo: mrpg.py Projeto: mozor/mRPG
 def dologin():
     if (lenow >= 3):
         login_char_name = msg_split[1]
         login_password = msg_split[2]
         self.db = DBPool('mrpg.db')
         char_exists = yield self.db.does_char_name_exist(login_char_name)
         self.db.shutdown("")
         if(char_exists[0][0] == 0):
             self.privateMessage(user, "There is not a character by that name.")
         else:
             self.db = DBPool('mrpg.db')
             is_online = yield self.db.is_char_online(login_char_name)
             self.db = DBPool('mrpg.db')
             if (is_online[0][0] == 0):
                 self.db = DBPool('mrpg.db')
                 temppass = yield self.db.get_password(login_char_name)
                 passhash = temppass[0][0]
                 self.db.shutdown("")
                 if (sc.verify(login_password, passhash)):
                     self.db = DBPool('mrpg.db')
                     self.db.executeQuery("UPDATE users SET online = 1, hostname = ? WHERE char_name = ?",(hostname,login_char_name))
                     self.db.shutdown("")
                     self.mode(self.factory.channel, True, 'v', user=user)
                     self.privateMessage(user, "You are now logged in.")
                 else:
                     self.privateMessage(user, "Password incorrect.")
             else:
                 self.privateMessage(user, "You are already logged in")
     else:
         self.privateMessage(user, "Not enough information was supplied.")
Exemplo n.º 19
0
def login():
    if session:
        return redirect(url_for('index'))

    if request.method == 'POST':

        tasks = mongo.db.Credentials.find({})
        username = request.form.get("name")
        pswd = request.form.get("password")
        for element in tasks:
            if element["User"] == username:
                x = (element["Pass"])
                if (sha512_crypt.verify(str(pswd), str(x))):
                    session['username'] = username
                    session['admin'] = element["Admin"]
                    session.permanent = True
                    app.permanent_session_lifetime = timedelta(minutes=10)
                    return redirect(url_for('index'))

            else:
                pass
            #return("Wrong username or password")
        return render_template("Error.html",
                               message="Wrong username or password")
    else:
        return render_template("login.html")
Exemplo n.º 20
0
def login():
    if fl.request.method == 'GET':
        current = datetime.datetime.now()
        if 'logged_in' in fl.session:
            return fl.redirect(fl.url_for('index'))
        return fl.render_template('/login.html', current=current)
    else:
        username = fl.request.form['username']
        pw = fl.request.form['pw']
        # now check this against the database
        user_list = ml.User.query.filter(ml.User.email == username).all()
        if len(user_list) == 1:
            user = user_list[0]
            # check that the password is correct
            if sha512_crypt.verify(pw, user.pw_hashed):
                flog.login_user(user)
                fl.session['logged_in'] = user.id
                if user.admin:
                    fl.session['admin'] = True

                next = fl.request.args.get('next')
                return fl.redirect(fl.url_for('index'))
            else:
                fl.flash("Password incorrect!", "error")
                return fl.render_template('/login.html')
        else:
            fl.flash("Login failed!", "error")
            return fl.render_template('/login.html')
Exemplo n.º 21
0
def get_password_verification(passwordhash, password):
    """
    used when the user is loging in or when the user is attemping to change the
    password. this function should be used by any function that wants to verify
    a user password given a user password hash
    """
    return sha512_crypt.verify(password, passwordhash)
Exemplo n.º 22
0
async def login(request):
    try:
        username = payload['username']
        password = payload['password']
    except KeyError:
        raise web.HTTPBadRequest()
    async with request.app['pool'].acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(
                "SELECT password_hash FROM users WHERE username = %s;",
                (username))
            res = await cursor.fetchone()
    # TODO: Check if res has any data and check against password_hash
    try:
        (res, ) = res
    except ValueError:
        raise web.HTTPBadRequest()
    # sha512_crypt.verify(password, hash)
    if 'is_hash' in payload and payload['is_hash']:
        valid = (res == password)
    else:
        valid = sha512_crypt.verify(password, res)
    if not valid:
        raise web.HTTPBadRequest()
    session = await get_session(request)
    session['last_visit'] = time.time()
    session['user'] = username
    return web.Response(status=204)
Exemplo n.º 23
0
Arquivo: user.py Projeto: kime/kime
    def verify_password(self, password):
        """

        :param password:
        :return:
        """
        return sha512_crypt.verify(password, self.password_hash)
Exemplo n.º 24
0
Arquivo: mrpg.py Projeto: mrsmyl/mRPG
                def donewpass():
                    if (lenow >= 4):
                        newpass_char_name = msg_split[1]
                        newpass_password = msg_split[2]
                        newpass_new_password = msg_split[3]

                        self.db = DBPool('mrpg.db')
                        char_exists = yield self.db.does_char_name_exist(newpass_char_name)
                        self.db.shutdown("")
                        if(char_exists[0][0] == 0):
                            self.privateMessage(user, "There is not a character by that name.")
                        else:
                            self.db = DBPool('mrpg.db')
                            passhash = yield self.db.get_password(newpass_char_name)
                            passhash = passhash[0][0]
                            self.db.shutdown("")
                            if(sc.verify(newpass_password, passhash)):
                                hash = sc.encrypt(newpass_new_password)
                                hash
                                '$6$rounds=36122$kzMjVFTjgSVuPoS.$zx2RoZ2TYRHoKn71Y60MFmyqNPxbNnTZdwYD8y2atgoRIp923WJSbcbQc6Af3osdW96MRfwb5Hk7FymOM6D7J1'
                                self.db = DBPool('mrpg.db')
                                self.db.executeQuery("UPDATE users SET password = ? WHERE char_name = ?",(hash, newpass_char_name))
                                self.db.shutdown("")
                                self.privateMessage(user, "You have changed your password.")
                            else:
                                self.privateMessage(user, "Password incorrect.")
                    else:
                        self.privateMessage(user, "Not enough information was supplied.")
Exemplo n.º 25
0
Arquivo: auth.py Projeto: 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
Exemplo n.º 26
0
    def validate_password(self, password: str) -> bool:
        """ Check that given password is valid for given account

        :param password: password to be checked
        :return: True if password is valid equal, False otherwise
        """
        return sha512_crypt.verify(password, self.password)
Exemplo n.º 27
0
def authenticate_user(username, password):
    user = database.User.objects(username__iexact=username).first()
    if user is None:
        return None
    if (sha512_crypt.verify(password, user.hash)):
        return user
    else:
        return None
Exemplo n.º 28
0
 def check(self, username, password):
     """
     Verifies a user supplied password against the stored hash for a user
     """
     dbp_hashed = self.get(username)
     if dbp_hashed is None:
         return False
     return sha512_crypt.verify(password, dbp_hashed)
Exemplo n.º 29
0
def compute_uhash(count):
    """Generate linux system user couple of clear/hashes passwords (SHA512)"""
    result = dict()
    for i in _compute_clear_passwordlist(count):
        hashed = sha512_crypt.hash(i)
        if sha512_crypt.verify(i, hashed):
            result[sha512_crypt.hash(i)] = i
    return compute_markdown_rendering(1, result)
Exemplo n.º 30
0
def verify(session, username, password):
    """Return True if and only if username is in the users DB
    and has correct password."""
    entity = get_user(session, username)
    if entity:
        return Hasher.verify(password, entity.password)
    else:
        return False
Exemplo n.º 31
0
def login(req):
  if req.POST:
    user = req.db.users.find_one({'email': req.POST['email']})
    if user:
      print(sha512_crypt.verify(req.POST['password'], user['password']))
    else:
      req.flash('Login failed, please try again or use the reset password feature.', 'error')
  return {}
Exemplo n.º 32
0
 def check(self, username, password):
     """
     Verifies a user supplied password against the stored hash for a user
     """
     dbp_hashed = self.get(username)
     if dbp_hashed is None:
         return False
     return sha512_crypt.verify(password, dbp_hashed)
Exemplo n.º 33
0
def verify(session, username, password):
    """Return True if and only if username is in the users DB
    and has correct password."""
    entity = get_user(session, username)
    if entity:
        return Hasher.verify(password, entity.password)
    else:
        return False
Exemplo n.º 34
0
    def authenticate(session, username, password):
        u = User.get(session, username)

        if u is not None:
            h = u.passwd
            return h is not None and sha512_crypt.verify(password, h)

        return False
Exemplo n.º 35
0
    def button_handler(self, event):
        label = event.GetEventObject().GetLabel()
        self.selected_pictures.append(label)
        parentCustomTitleBar = self.GetParent().customTitleBar
        children = parentCustomTitleBar.sizerTitleBar.GetChildren()
        dotsWidget = children[1].GetWindow()

        if len(self.selected_pictures) == 4:
            dotsWidget.SetLabel("⚫ ⚫ ⚫ ⚫")
            pswd_file = open(curdir + "/9gridpassword.txt", "r+")
            file_pswd = pswd_file.read()

            print(self.selected_pictures)

            if (sha512_crypt.verify(''.join(self.selected_pictures),
                                    file_pswd)):
                print('Authentication successful')
                self.GetParent().eye_track_thread.join()
                sys.exit(0)
            else:
                self.selected_pictures = []
                dotsWidget.SetLabel("⚪ ⚪ ⚪ ⚪")
                wx.MessageBox("Authentication failed", " ",
                              wx.OK | wx.ICON_INFORMATION)

                # go back to first set of pictures
                for i in range(9):
                    picture_label = self.labels[len(self.selected_pictures)][i]
                    pictures = os.listdir(self.curdir + '/images/9_grid/' +
                                          picture_label)
                    picture_number = pictures.pop(
                        r.randint(0,
                                  len(pictures) - 1))

                    self.buttons[i].SetBitmapLabel(
                        wx.Bitmap(self.curdir +
                                  "/images/9_grid/{0}/{1}".format(
                                      picture_label, picture_number)))
                    self.buttons[i].SetLabel(picture_label)
        else:
            if (len(self.selected_pictures) == 1):
                dotsWidget.SetLabel("⚫ ⚪ ⚪ ⚪")
            if (len(self.selected_pictures) == 2):
                dotsWidget.SetLabel("⚫ ⚫ ⚪ ⚪")
            if (len(self.selected_pictures) == 3):
                dotsWidget.SetLabel("⚫ ⚫ ⚫ ⚪")

            # set next set of buttons
            for i in range(9):
                picture_label = self.labels[len(self.selected_pictures)][i]
                pictures = os.listdir(self.curdir + '/images/9_grid/' +
                                      picture_label)
                picture_number = pictures.pop(r.randint(0, len(pictures) - 1))

                self.buttons[i].SetBitmapLabel(
                    wx.Bitmap(self.curdir + "/images/9_grid/{0}/{1}".format(
                        picture_label, picture_number)))
                self.buttons[i].SetLabel(picture_label)
Exemplo n.º 36
0
    def userLogin(args):
        user = args[USERNAME]

        # Yubikey OTP is 44-characters so if there's not at least 45 chars then
        # we assume there's only a single factor and fail them out of spite
        # also fail out of spite if the user does not have a yubikey in their password entry
        if user not in p.users:
            print(FAILED)
            logit("User not in table")
            return

        if (len(args['password']) < 45):
            print(FAILED)
            logit("Password too short to have yubi token")
            return

        if p.users[user]['yubikeyid'] is None:
            print(FAILED)
            logit("User has no yubi token in the passwd file")
            return

        # Otherwise split the first and second factors apart
        password = args['password'][0:-44]
        yubiotp = args['password'][-44:]

        userobject = p.users[user]

        # Check the first factor against the hash
        if not sha512_crypt.verify(password, userobject['hash']):
            print(FAILED)
            logit("First factor failed")
            return


            # does the yubikey belong to this user?
            # We should have pretty good assurance at this point that the userobject has a yubikeyid
            # value.  Our check above should have promised that
        if yubiotp[0:12] != userobject['yubikeyid']:
            print(FAILED)
            logit(
                "Yubi token presented %s does not match what is on file %s" % (yubiotp[0:12], userobject['yubikeyid']))
            return

        try:
            # Now FINALLY we go to yubicloud and ask
            yubi = Yubico(yubicloud_client_id, yubicloud_secret_key)
            if yubi.verify(yubiotp):
                print(SUCCESS)
                return
        except Exception as e:
            logging.error("Exception in yubi verify", e)
            print(FAILED)
            return

        # If we fall all the way out
        logit("Fell out the bottom")
        print(FAILED)
Exemplo n.º 37
0
 def check_hashed_password(password, hashed_password):
     """
     Checks that the password the user sent matches that of the database.
     The database password is encrypted more than the user's password at this stage.
     :param password: sha512-hashed password
     :param hashed_password: pbkdf2_sha512 encrypted password
     :return: True if passwords match, False otherwise
     """
     return sha512_crypt.verify(password, hashed_password)
Exemplo n.º 38
0
 def compareHash(self, string):
     if (self.type == "md5"):
         return md5_crypt.verify(string, self.pwd_hash)
     elif (self.type == "bcrypt"):
         return bcrypt.verify(string, self.pwd_hash)
     elif (self.type == "sha256"):
         return sha256_crypt.verify(string, self.pwd_hash)
     elif (self.type == "sha512"):
         return sha512_crypt.verify(string, self.pwd_hash)
Exemplo n.º 39
0
    def check_password(cls, username, password):
        user = cls.get_by_username(username)
        if not user:
            return False

        try:
            is_valid = crypt.verify(password, user.password)
            return is_valid
        except ValueError:
            return False
Exemplo n.º 40
0
 async def authorize(self, username, password):
     curr_user = await self.objects(username=username).first()
     if curr_user is not None:
         if sha512_crypt.verify(password, curr_user.password):
             userid = curr_user.userid
         else:
             userid = None
         return userid
     else:
         return None
Exemplo n.º 41
0
    def check_password(self, pwd_to_check: str) -> bool:
        """Checks if the provided password is correct.
        
        :param pwd_to_check: The password to check
        :type pwd_to_check: str
        :return: True if the password is correct, False otherwise
        :rtype: bool
        """

        return sha512_crypt.verify(pwd_to_check, self.password)
Exemplo n.º 42
0
def check_password(raw_password, enc_password):
    """
    Compares raw password and encoded password.
    """
    if not raw_password:
        return False
    if backends.SHOULD_HASH_PASSWORD:
        return sc.verify(raw_password, enc_password)
    else:
        return enc_password == raw_password
Exemplo n.º 43
0
def valid_login(username,password):
    try:
        c = mysql.connect().cursor()
        c.execute("SELECT * FROM USER WHERE username ='******'" %(username))
        data = c.fetchone()[2]
        if data and sha512_crypt.verify(password, data):
            return True
        else:
            return False
    except:
        return False
Exemplo n.º 44
0
Arquivo: auth.py Projeto: bneg/genesis
def check_password(passw, hash):
    if hash.startswith('{SHA}'):
        try:
            passw_hash = '{SHA}' + b64encode(sha1(passw).digest())
            if passw_hash == hash:
                return True
        except:
            import traceback
            traceback.print_exc()
    elif sha512_crypt.identify(hash):
        return sha512_crypt.verify(passw, hash)
    return False
Exemplo n.º 45
0
    def check_password(self, username, password):
        if not username in ajenti.config.tree.users:
            return False
        type = 'plain'
        saved = ajenti.config.tree.users[username].password
        if '|' in saved:
            type, saved = saved.split('|')

        if type == 'plain':
            hash = password
            return hash == saved
        elif sha512_crypt.identify(saved):
            return sha512_crypt.verify(password, saved)
Exemplo n.º 46
0
def do_login():
    # bottle.request.environ.get('beaker.session')
    username = request.forms.get('username')
    password = request.forms.get('password')
    if tablefunctions.retrieve_password(username) == None:
        return "<p>Username or password is not correct.</p>"
    elif sha512_crypt.verify(password, tablefunctions.retrieve_password(username)):
        # s['user_id'] = True
        # response.set_cookie("account", username, secret='some-secret-key')
        # s.save()
        return serve_home()
    else:
        return "<p>Username or password is not correct.</p>"
Exemplo n.º 47
0
 def check_password(self):
     password = self.password
     userid = self.userid
     logging.debug('username/password to check is %s/%s' % (userid, password))
     dbpassword = passwd.get_password(self)
     if dbpassword is not None:
         if sha512_crypt.verify(password,dbpassword):
             logging.debug('password correct')
             return True
         else:
             logging.debug('password incorrect')
             return False
     else:
         return False
Exemplo n.º 48
0
	def auth(self, data): #Needs 1 array with two elements: 0 = username  1 = password
		con = mdb.connect(host='localhost', user='******', passwd='12adam12', db='IT490')
		query = "select password from users where user_name = \"%s\"" % data[0]
		
		try:
			cur = con.cursor()
			cur.execute(query)
			pwd = cur.fetchall()
			result = sha512_crypt.verify(data[1],pwd[0][0])
		except: 
			print "Error: unable to fetch data"
			return False

		con.close();
		return result
Exemplo n.º 49
0
def login():
	form = LoginForm()
	login_failed = False
	if form.validate_on_submit():
		# Find the user.
		user = db.session.query(User).filter_by(name=request.form["username"]).first()

		# No user by that name.
		if user is None or not sha512_crypt.verify(sha384(request.form["password"]).hexdigest(), user.password):
			login_failed = True
		else:
			# Login succeeded. Set up the user's session.
			session["user"] = user.id
			session["username"] = user.name
			return redirect(url_for("index"))
	return render_template("login.j2", form=form, login_failed=login_failed)
Exemplo n.º 50
0
def do_login():
    username = request.form['username']
    password = request.form['password']
    next = request.form['next']

    userdetails = None
    with get_connection() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cur.execute('SELECT id, password FROM users WHERE username = %s', [username])
        userdetails = cur.fetchone()
    
    if userdetails is not None and sha512_crypt.verify(password, userdetails['password']):
        login_user(User(userdetails['id']), remember=True)
        return redirect(next)

    return render_template('login.html', next=next, username=username)
Exemplo n.º 51
0
def do_login():

    # This post function will check if the user log-in credentials are correct.

    # Get the user details from the login form.
    username = request.forms.get('username')
    password = request.forms.get('password')

    try:
        # Connect to the database.
        conn = sqlite3.connect(config["paths"]["file_auth_database"])
        c = conn.cursor()
        c.execute("SELECT Password FROM secure_login WHERE Username = ?", (str(username),))
        rows = c.fetchall()
        c.close()
    except OperationalError:
        # If the user is not found in the database and we don't know the password, exit authentication.
        abort(403, "Authentication failed.")

    if len(rows) == 0:
        abort(403, "Authentication failed.")

    # Check if the password from the user matches the passwored stored in the database.
    for row in rows:
        for col in row:
            check = sha512_crypt.verify(password, col)
            if check == True:
                # Password and username checks passed. Now proceeding for setting authenticated session cookie.

                # Generate unique session ID.
                session_start_time = str(datetime.datetime.now())
                secret = sha512_crypt.encrypt(session_start_time)

                # Save cookie secret and session start time to the db.
                conn = sqlite3.connect(config["paths"]["file_auth_database"])
                c = conn.cursor()
                c.execute("UPDATE secure_login SET SessionID = (?) WHERE Username = (?)", (secret, username))
                c.execute("UPDATE secure_login SET SessionStartTime = (?) WHERE Username = (?)", (session_start_time, username))
                conn.commit()
                c.close()

                response.set_cookie("username", username, secret=secret)
                response.status = 303
                response.set_header('Location', '/dashboard')
            else:
                abort(403, "Authentication failed.")
Exemplo n.º 52
0
def login():
	form = UserForm()
	site_title = 'Login'
	error = None
	if request.method == 'POST':
		if form.validate_on_submit:
			user = models.User.query.filter_by(email=request.form['email']).first()
			if user is not None and sha512_crypt.verify(request.form['password'], user.passwordhash):
				session['logged_in'] = True
				session['nickname'] = user.nickname
				session['uid'] = user.id
				return redirect(url_for('dashboard'))
			else:
				error = 'Invalid username or password.'
	return render_template('login.html',
							form=form,
							site_title = site_title,
							error = error
							)
Exemplo n.º 53
0
def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    def any_(l):
        """Check if any element in the list is true, in constant time.
        """
        ret = False
        for e in l:
            if e:
                ret = True
        return ret

    user_ok = False
    pass_sha1_ok = pbkdf2_sha256_ok = pass_sha512_ok = pass_sha512_crypt_ok = pass_bcrypt_crypt_ok = False

    user_ok = app.conf['wapt_user'] == username

    pass_sha1_ok = app.conf['wapt_password'] == hashlib.sha1(
        password.encode('utf8')).hexdigest()
    pass_sha512_ok = app.conf['wapt_password'] == hashlib.sha512(
        password.encode('utf8')).hexdigest()

    if '$pbkdf2-sha256$' in app.conf['wapt_password']:
        pbkdf2_sha256_ok = pbkdf2_sha256.verify(password, app.conf['wapt_password'])
    elif sha512_crypt.identify(app.conf['wapt_password']):
        pass_sha512_crypt_ok = sha512_crypt.verify(
            password,
            app.conf['wapt_password'])
    else:
        try:
            if bcrypt.identify(app.conf['wapt_password']):
                pass_bcrypt_crypt_ok = bcrypt.verify(
                    password,
                    app.conf['wapt_password'])

        except Exception:
            pass

    basic_auth = any_([pbkdf2_sha256_ok, pass_sha1_ok, pass_sha512_ok,
                 pass_sha512_crypt_ok, pass_bcrypt_crypt_ok]) and user_ok

    return basic_auth or (auth_module_ad is not None and auth_module_ad.check_credentials_ad(app.conf, username, password))
Exemplo n.º 54
0
def local_authenticate(login, password):
    """ Checks the validity of a username/password against what
        is stored in the database. """

    try:
        q = DBSession.query(User)
        q = q.filter(User.user_name == login)
        db_user = q.one()
    except Exception as e:
        log.debug("%s (%s)" % (Exception, e))
        # Should return invalid username here somehow
        return None

    try:
        if sha512_crypt.verify(password, db_user.password):
            return [login]
    except Exception as e:
        log.error("%s (%s)" % (Exception, e))
        pass

    return None
Exemplo n.º 55
0
def authenticate(username=None, password=None, http_abort=True):
    if not username:
        username = request.values['username']
    if not password:
        password = request.values['password']

    # Refuse the login if there has been 3 previous failed attempts
    fails = cache.get(request.remote_addr+'-'+username+'-authfails') or 0
    # Minimal protection against passwords guess attempts
    if fails > 2:
        cache.set(request.remote_addr+'-'+username+'-authfails', fails, 120)
        abort(401, '3 previous attempts failed, please wait 2 minutes')
        # The following line is there only for the translation in OSPFM-web
        # self.forbidden('3 previous attempts failed, please wait 2 minutes')

    user = core.User.query.filter(
                core.User.username == username
            ).first()
    if not user:
        if http_abort:
            cache.set(request.remote_addr+'-'+username+'-authfails',
                      fails+1, 120)
            abort(401, 'Wrong username or password')
            # The following line is there only for the translation in OSPFM-web
            # self.forbidden('Wrong username or password')
        else:
            return False
    if sha512_crypt.verify(password, user.passhash):
        # Last login was not a fail, remove the fail info in the cache
        cache.delete(request.remote_addr+'-'+username+'-authfails')
        key = str(uuid.uuid4())
        cache.set(request.remote_addr+'---'+key, username, 3600)
        return jsonify(status=200, response={'key': key})
    elif http_abort:
        # Minimal protection against passwords guess attempts: each login
        # failure increments this counter
        cache.set(request.remote_addr+'-'+username+'-authfails', fails+1, 120)
        abort(401, 'Wrong username or password')
    else:
        return False
Exemplo n.º 56
0
def handle_login(params, json_data):
	if (not _check_flood_protect(params['ip'][0])):
		return (False, '')
	if 'username' not in params or 'password' not in params:
		return (False,'')
	
	try:
		q = Query('SELECT gebr_id, gebr_wachtwoord FROM tblgebruiker WHERE gebr_naam = %s')
		q.run((params['username'][0],))
		results = q.rows()
	except DatabaseError:
		raise InternalServerError
	
	if (len(results) != 1):
		_add_flood_protect(params['ip'][0])
		return (False,'')
	if not sha512_crypt.verify(params['password'][0], results[0][1]):
		_add_flood_protect(params['ip'][0])
		return (False,'')
	
	#Generate session key
	session_key = _create_session(params['ip'][0], results[0][0])
	
	return (True, session_key)
Exemplo n.º 57
0
Arquivo: mrpg.py Projeto: mrsmyl/mRPG
                def dodelete():
                    if (lenow >= 3):
                        delete_char_name = msg_split[1]
                        delete_password = msg_split[2]

                        self.db = DBPool('mrpg.db')
                        char_exists = yield self.db.does_char_name_exist(delete_char_name)
                        self.db.shutdown("")
                        if(char_exists[0][0] == 0):
                            self.privateMessage(user, "There is not a character by that name.")
                        else:
                            self.db = DBPool('mrpg.db')
                            passhash = yield self.db.get_password(delete_char_name)
                            passhash = passhash[0][0]
                            self.db.shutdown("")
                            if (sc.verify(delete_password, passhash)):
                                self.db = DBPool('mrpg.db')
                                self.db.executeQuery("DELETE FROM users WHERE char_name = ?",delete_char_name)
                                self.db.shutdown("")
                                self.privateMessage(user, delete_char_name + " has been deleted.")
                            else:
                                self.privateMessage(user, "Password incorrect.")
                    else:
                        self.privateMessage(user, "Not enough information was supplied.")
Exemplo n.º 58
0
 def verify(self, clearvalue, hashed_value):
     return sha512_crypt.verify(clearvalue, hashed_value)