Esempio n. 1
0
 def return_pbkdf2sha512(self, secret, options):
     from passlib.hash import pbkdf2_sha512
     if sys.version_info.major == 2:
         return pbkdf2_sha512.hash(secret,
                                   salt=bytes(self.find_salt(options)),
                                   rounds=58000)
     else:
         return pbkdf2_sha512.hash(secret,
                                   salt=bytes(self.find_salt(options),
                                              encoding='utf8'),
                                   rounds=58000)
Esempio n. 2
0
def create_dummy_account(pg):
    """Create dummy account with liked and bookmarked recipes"""

    from application.models import User
    from passlib.hash import pbkdf2_sha512
    import datetime

    # If user entry already exists, do nothing, otherwise create it
    user = User.query.filter_by(username=pg.dummy_name).first()

    if not user:
        user = User(
            username=pg.dummy_name,
            password=pbkdf2_sha512.hash(pg.dummy_password),
            email=pg.dummy_email,
            confirmed=False,
            created_on=datetime.datetime.utcnow(),
            optin_news=True,
        )
        pg.session.add(user)
        pg.session.commit()
        user = User.query.filter_by(username=pg.dummy_name).first()

    # Add item to cookbook
    pg.add_to_cookbook(user.userID, pg.url)

    # Like a recipe
    pg.rate_recipe(user.userID, pg.url, 5)

    user = User.query.filter_by(username=pg.dummy_name).first()
    assert user.email == pg.dummy_email
Esempio n. 3
0
def hash_password(password):
    """
    Hashes a password using pbkdf2_sha512
    :param password: The sha512 password from the login/register form
    :return: A sha512->pbkdf2_sha512 encrypted password
    """
    return pbkdf2_sha512.hash(password)
Esempio n. 4
0
    def modify_user(self, userid, name, fullname, email, admin,
                    password=None):

        # pylint: disable=too-many-arguments

        with session_scope(self.session) as s:
            try:
                u = s.query(User).filter(User.id == userid).one()
            except NoResultFound:
                raise ElbeDBError("no user with id %i" % userid)

            # If a user name change is requested, check for uniqueness
            if name != u.name:
                if s.query(User).filter(User.name == name).count() > 0:
                    raise ElbeDBError(
                        "user %s already exists in the database" % name)

            u.name = name
            u.fullname = fullname
            u.email = email
            u.admin = admin

            # Update password only if given
            if password is not None:
                # encrypt is deprecated but hash is not available in jessie
                try:
                    u.pwhash = pbkdf2_sha512.hash(password)
                except AttributeError:
                    u.pwhash = pbkdf2_sha512.encrypt(password)
Esempio n. 5
0
def change_password_route():
    old_password = request.form['old_password']
    new_password = request.form['new_password']
    confirm_new_password = request.form['confirm_new_password']
    if len(new_password) > 256:
        return json.dumps({
            'error':
            'New password cannot be more than 256 characters long\n'
        }), 409
    if new_password != confirm_new_password:
        return json.dumps({'error': 'New passwords do not match\n'}), 409

    username = current_user.get_id()
    with connect_to_database() as cur:
        cur.execute("SELECT password FROM userInfo WHERE username='******';" %
                    username)
        db_response = cur.fetchone()

    correct_password = db_response['password']
    correct_old_password = hasher.verify(old_password, correct_password)

    if correct_old_password:
        hashed_new_password = hasher.hash(new_password)
        with connect_to_database() as cur:
            cur.execute(
                "UPDATE userInfo SET password='******' WHERE username='******';" %
                (hashed_new_password, username))
        return json.dumps({'success': 'Password changed successfully\n'}), 200
    else:
        return json.dumps({'error': 'Old password is incorrect\n'}), 409
Esempio n. 6
0
    def password(self, new_password):
        """Sets the password for a user, and encrypts it.

        Args:
            new_password (str): The new password for the User.
        """
        self._password = pbkdf2_sha512.hash(new_password)
Esempio n. 7
0
def create_user():
    ks = {'username','password','nick_name','age','gender','street',\
          'suberb','city','postcode','description'}
    if set(request.form.keys()).issuperset(
            ks) and request.form["username"] and request.form["password"]:
        rows = ""
        values = ""
        for k in ks:
            rows += f"`{k}`,"
            if k == 'age' or k == 'gender':
                v = escape_string(request.form[k])
                values += f"{v if v else 'NULL'},"
            elif k == 'password':
                hash = pbkdf2_sha512.hash(request.form[k])
                values += f"'{hash}',"
            else:
                values += f"'{escape_string(request.form[k])}',"
        rows = rows[:-1]
        values = values[:-1]
        try:
            db = get_db(current_app)
            with db.cursor() as c:
                sql = " INSERT INTO `filmfinder`.`users`(%s) VALUES (%s);"
                print(sql % (rows, values))
                c.execute(sql % (rows, values))
            db.commit()
        except MySQLError as err:
            db.rollback()
            print(err)
        else:
            return f"OK", 200
    abort(400)
Esempio n. 8
0
def update_user():
    print(current_app.login_manager.login_view)
    ks = {'username','password','nick_name','age','gender','street',\
          'suberb','city','postcode','description'}
    if ks.issuperset(set(request.form.keys())):
        values = ""
        for k in request.form.keys():
            if k == 'age' or k == 'gender':
                v = escape_string(request.form[k])
                values += f"{k} = {v if v else 'NULL'},"
            elif k == 'password':
                hash = pbkdf2_sha512.hash(request.form[k])
                values += f"{k} = '{hash}',"
            else:
                values += f"{k} = '{escape_string(request.form[k])}',"
        values = values[:-1]
        try:
            db = get_db(current_app)
            with db.cursor() as c:
                sql = " UPDATE `filmfinder`.`users` SET %s WHERE user_id = '%s';"
                print(sql % (values, current_user.get_id()))
                c.execute(sql % (values, current_user.get_id()))
            db.commit()
        except MySQLError as err:
            db.rollback()
            print(err)
        else:
            if "password" in request.form.keys():
                logout_user()
                return redirect(current_app.login_manager.login_view)
            else:
                return f"OK", 200
    abort(400)
Esempio n. 9
0
def Sign_Up():
    usrnm = request.form["username"]
    passwd = request.form['newpass']
    mail = request.form["email"]
    passphrase = pbkdf2_sha512.hash(passwd)
    file = open("app/static/images/generic_avatar.png", "rb")
    user = User.query.filter((User.username == usrnm)).first()
    if (user == None):
        user = User(
            username=usrnm,
            password=passphrase,
            display_name=usrnm,
            email=mail,
            profile_image="generic_avatar",
            profile_image_data=file.read(),
        )
        db.session.add(user)
        db.session.commit()
        # flash('Your account has been created! You are now able to log in', 'success')
        session['user'] = usrnm
        pic = b64encode(user.profile_image_data)
        pic2 = pic.decode('ascii')
        return render_template('User_HomePage.html',
                               username=user.display_name,
                               logged_in=True,
                               userinfo=user,
                               image=pic2)
    else:
        return render_template("index.html", logged_in=False, user_exists=True)
Esempio n. 10
0
    def password(self, new_password):
        """Sets the password for a user, and encrypts it.

        Args:
            new_password (str): The new password for the User.
        """
        self._password = pbkdf2_sha512.hash(new_password)
Esempio n. 11
0
def change_password():
    """
    POST endpoint that changes the current user's password without revoking all the access
    and refresh tokens.
    """

    user = get_current_user()
    club = user.club

    json = g.clean_json

    old_password = json['old_password']
    new_password = json['new_password']

    if not hash_manager.verify(old_password, user.password):
        raise JsonError(status='error', reason='The old password is incorrect.')

    # Check if the password is the same
    if old_password == new_password:
        raise JsonError(status='error', reason='The old and new passwords are identical.')

    # Check if the password is strong enough
    is_password_strong = flask_exts.password_checker.check(new_password)
    if not is_password_strong:
        raise JsonError(status='error', reason='The new password is not strong enough')

    # Only set the new password if the old password is verified
    user.password = hash_manager.hash(new_password)
    user.save()

    return {'status': 'success'}
Esempio n. 12
0
    def modify_user(self, userid, name, fullname, email, admin, password=None):

        # pylint: disable=too-many-arguments

        with session_scope(self.session) as s:
            try:
                u = s.query(User).filter(User.id == userid).one()
            except NoResultFound:
                raise ElbeDBError("no user with id %i" % userid)

            # If a user name change is requested, check for uniqueness
            if name != u.name:
                if s.query(User).filter(User.name == name).count() > 0:
                    raise ElbeDBError(
                        "user %s already exists in the database" % name)

            u.name = name
            u.fullname = fullname
            u.email = email
            u.admin = admin

            # Update password only if given
            if password is not None:
                # encrypt is deprecated but hash is not available in jessie
                try:
                    u.pwhash = pbkdf2_sha512.hash(password)
                except AttributeError:
                    u.pwhash = pbkdf2_sha512.encrypt(password)
Esempio n. 13
0
async def register_user(req: request):
    """
    Tries to register an user inside the app. As long as the username doesn't exists already
    :param req:
    :return:
    """
    if 'username' not in req.form or 'password' not in req.form:
        return json_r({"error": "Username or password not sent"}, 400)
    async with req.app.pool.acquire() as connection:
        async with connection.transaction():
            # Check if the user already exists
            user_search = await connection.fetch(
                "SELECT * FROM users WHERE username=$1",
                req.form["username"][0]
            )
            # If exists, then return error
            if len(user_search) != 0:
                return json_r({"error": "Username already exists"}, 400)

            # Register the user
            await connection.execute(
                "INSERT INTO users(username, password) VALUES($1,$2)",
                req.form["username"][0], pbk.hash(req.form["password"][0])
            )
            return json_r({"success": True})
Esempio n. 14
0
    def hash_password(password):
        """ Hash the password, create salt and encrypt

        :param password:  plaintext password
        :return: hashed password using sha512
        """

        return pbkdf2_sha512.hash(password)
Esempio n. 15
0
    def __init__(self, name, password):
        """Initializes a new User object

        Args:
            name (str): The username for the User.
            password (str): The password for the User.
        """
        self.username = name
        self._password = pbkdf2_sha512.hash(password)
Esempio n. 16
0
def register(username: str, password: str) -> None:
    """ Registers a new user account. """
    users = load_file("users")
    user = users[username] = {}
    user["hash"] = pbkdf2_sha512.hash(password)
    user["scope"] = "default"
    user["keys"] = []
    user["encrypt"] = True
    dump_file(users, "users")
Esempio n. 17
0
    def __init__(self, nome, sobrenome, email, senha):
        self.__id = Usuario.contador + 1
        self.__nome = nome.strip().title()
        self.__sobrenome = sobrenome.strip().title()
        self.__email = email
        self.__senha = cryp.hash(senha, rounds=2000000, salt_size=28)
        Usuario.contador = self.__id

        print(f"Usuário criado: {self.__gera_usuario()}")
Esempio n. 18
0
 def authkey_generate(self):
     """
     Generaty authkey, return list: [authkey_plain, authkey_hash]
     authkey_salt and authkey_hash are to be stored in DB, authkey_plain is to be returned to the REST client
     """
     authkey_plain = ''.join(
         random.choice(string.ascii_letters + string.digits)
         for _ in range(64))
     authkey_hash = pbkdf2_sha512.hash(authkey_plain)
     return [authkey_plain, authkey_hash]
Esempio n. 19
0
    def __init__(self, username, password, home_node=NODE_NAME, active=True):
        self.username = self.get_fqn(username, home_node)
        self.hash = pbkdf2_sha512.hash(password)

        self.home_node = home_node
        if home_node == NODE_NAME:
            self.external = False
        else:
            self.external = True
            self.last_synced = datetime.datetime.now()
        self.active = active
Esempio n. 20
0
def addPassword(password, email):
    conn = db.get_db()
    cur = conn.cursor()
    userID = getID(email)
    passwordHash = passHash.hash(password)
    cur.execute(
        "INSERT INTO PasswordPairs (UserID, PasswordHash) VALUES (?, ?)",
        (userID, passwordHash))
    cur.execute("UPDATE Registrants SET PasswordHash = ? WHERE UserID = ?",
                (passwordHash, userID))
    db.close_db()
Esempio n. 21
0
    async def hash_and_set_password(self, password: str):
        """Verifies that the input password matches with the stored password.

        Args:
            password_attempt(str): The input password.

        Returns:
            (bool): True if the passwords match, False if not.
        """

        self.password = pbkdf2_sha512.hash(password)
Esempio n. 22
0
    def update_password(self, userid: UserID, password: str) -> None:
        """
        Given a userid and a new password, update the password for that user.

        Parameters:
            userid - Integer user ID, as looked up by one of the above functions.
            password - String, plaintext password that will be hashed
        """
        passhash = pbkdf2_sha512.hash(password)
        sql = "UPDATE user SET password = :hash WHERE id = :userid"
        self.execute(sql, {'hash': passhash, 'userid': userid})
Esempio n. 23
0
    def register_user(self, login, password, char_data=None):
        if char_data is None:
            char_data = [0, 0, "none", "biography"]

        pass_hash = pbkdf2_sha512.hash(password)
        if self.is_available(login):
            request = 'INSERT INTO users (login, pass_hash, nickname, max_mana, learning_const, school, biography_file, status) VALUES (%s, %s, %s, %s, %s, %s, %s, 0)'
            self.cursor.execute(request, (login, pass_hash, login, *char_data))
            self.con.commit()
            return login
        return False
Esempio n. 24
0
def index():
    reg_form = RegistrationForm()
    if reg_form.validate_on_submit():
        username = reg_form.username.data
        password = reg_form.password.data
        hashed_pwd = pbkdf2_sha512.hash(password)
        user = User(username=username, password=hashed_pwd)
        db.session.add(user)
        db.session.commit()
        flash("Registered Successfully. Please login.", category='success')
        return redirect(url_for('login'))
    return render_template("index.html", form=reg_form)
Esempio n. 25
0
def savefirst(request):

    print("welcome")
    username =  request.POST['username']
    password=  request.POST['password']
    retype= request.POST['retype']
    enc_password = pbkdf2_sha512.hash(password, salt_size=32)
    usertype = request.POST['usertype']
    phone = request.POST['contact']
    file_save = RegistrationDatas(username=username,password=enc_password,retype=retype,usertype=usertype,phone=phone)
    file_save.save()
    return redirect('login_redirect')
Esempio n. 26
0
    def __init__(self, name, password, roles=None):
        """Initializes a new User object

        Args:
            name (str): The username for the User.
            password (str): The password for the User.
            roles (list[int]): List of Role ids for the User. Defaults to None.
        """
        self.username = name
        self._password = pbkdf2_sha512.hash(password)
        self.roles = []
        if roles:
            self.set_roles(roles)
Esempio n. 27
0
    def __init__(self, name, password, roles=None):
        """Initializes a new User object

        Args:
            name (str): The username for the User.
            password (str): The password for the User.
            roles (list[int], optional): List of Role ids for the User. Defaults to None.
        """
        self.username = name
        self._password = pbkdf2_sha512.hash(password)
        self.roles = []
        if roles:
            self.set_roles(roles)
Esempio n. 28
0
def reset_password(token):
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    user = User.verify_reset_password_token(token)
    if not user:
        return redirect(url_for("main.home"))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        user.password = pbkdf2_sha512.hash(form.password.data)
        db.session.commit()
        flash("Your password has been reset.")
        return redirect(url_for("auth.signin"))
    return render_template("reset-password.html", form=form)
Esempio n. 29
0
 def run(self, cmdargs):
     parser = argparse.ArgumentParser(
         prog="%s %s" % (sys.argv[0].split(os.path.sep)[-1], self.command_name),
         description="Generate and (re)set proxy access token in config file"
     )
     parser.add_argument('-c', '--config', type=str, help="Specify an alternate config file")
     parser.add_argument('--token-length', type=int, help="Token Length", default=16)
     args, _ = parser.parse_known_args()
     if args.config:
         config.rcfile = args.config
     token = self.generate_token(length=args.token_length)
     config['proxy_access_token'] = pbkdf2_sha512.hash(token)
     config.save()
     sys.stdout.write(f'{token}\n')
Esempio n. 30
0
def hash_pass():
    hash_confirm = input(
        f"\n{YELLOW}are you sure you want to hash your password ? (y or n){ENDC}:"
    )
    if hash_confirm.lower() == 'y' or hash_confirm == "":
        hashed_pass = pbkdf2_sha512.hash(all_str)
        print(F"\n{BLUE}your original password : {ENDC}\n" + all_str,
              f"\n\n{BLUE}hashed password : {ENDC}\n" + hashed_pass)
        hash_save_menu()
    elif hash_confirm.lower() == 'n':
        hash_save_menu()
    else:
        print(f"{RED}Invalid Entry !!{ENDC}")
        hash_pass()
 def update_app(self):
     system_databases = ["postgres", "template1", "template0"]
     try:
         print("(odoo_postgresv2)[INFO](init) Postgres update user Odoo password")
         database = self.secret_annotations.get("custom_database_name", "odoo")
         port = self.secret_annotations.get("custom_database_port", "5432")
         query = ["SELECT datname FROM pg_catalog.pg_database;"]
         list_databases = self.postgres_execution(self.squirrel_user, self.squirrel_pass, \
             self.host, port, "postgres", query)
         databases = database.replace(" ", "")
         databases = databases.split(",")
         for d_name in databases:
             for d in list_databases[query[0]]:
                 if d[0] not in system_databases:
                     if d[0] == d_name or d_name == "*":
                         print("(odoo_postgresv2)[INFO] Processing database %s" % d[0])
                         query_version_odoo = ["SELECT latest_version FROM ir_module_module WHERE name = 'base';"]
                         version_odoo = self.postgres_execution(self.squirrel_user, self.squirrel_pass, \
                             self.host, port, d[0], query_version_odoo)
                         valid_odoo_version = True
                         if version_odoo and version_odoo[query_version_odoo[0]]:
                             output_version = int(version_odoo[query_version_odoo[0]][0][0].split(".")[0])
                             pass_hash = pbkdf2_sha512.hash(self.random_pass)
                             if output_version >= 12:
                                 update_query = ["UPDATE res_users set password='******' WHERE id=2;" \
                                     % (pass_hash)]
                             elif output_version < 12 and output_version > 7:
                                 update_query = ["UPDATE res_users set password_crypt='%s' WHERE id=1;" \
                                     % (pass_hash)]
                             elif output_version <= 7:
                                 update_query = ["UPDATE res_users set password='******' WHERE id=1;" \
                                     % (self.random_pass)]
                             else:
                                 valid_odoo_version = False
                             if valid_odoo_version:
                                 if not self.debug_mode:
                                     self.postgres_execution(self.squirrel_user, self.squirrel_pass, \
                                         self.host, port, d[0], update_query)
                                 print("(odoo_postgresv2)[INFO] Successful update in database %s" % d[0])
                             else:
                                 print("(odoo_postgresv2)[ERROR] Not valid Odoo version found")
                         else:
                             print("(odoo_postgresv2)[ERROR] Not valid database Odoo")
     except Exception as e:
         exc_type, exc_obj, exc_tb = sys.exc_info()
         fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
         print("(odoo_postgresv2)[ERROR] %s, file: %s. line: %s" % (e, fname, exc_tb.tb_lineno))
         return False
     return True
Esempio n. 32
0
def createToken(email):
    #generates token and hash.
    token = str(uuid.uuid4())
    tokenHash = passHash.hash(token)
    #gets current time and expiry time.
    currentTime = time()
    expiryTime = int(currentTime + EXPIRY_TIME)
    conn = db.get_db()
    cur = conn.cursor()
    userID = getID(email)
    cur.execute(
        "INSERT INTO Codes(TokenHash, UserID, ExpirationTime) VALUES (?, ?, ?);",
        (tokenHash, userID, expiryTime))
    db.close_db()
    return token
Esempio n. 33
0
def signup():

    if current_user.is_authenticated:
        return redirect(url_for("main.home"))

    reg_form = RegistrationForm()

    if reg_form.validate_on_submit():
        username = reg_form.username.data
        password = reg_form.password.data
        email = reg_form.email.data
        optin_news = reg_form.optin_news.data

        # Add user to DB
        user = User(
            username=username,
            password=pbkdf2_sha512.hash(password),
            email=email,
            confirmed=False,
            created_on=datetime.datetime.utcnow(),
            optin_news=optin_news,
        )
        db.session.add(user)
        db.session.commit()

        # Add consent to DB (if given)
        if optin_news:
            consent = Consent(
                userID=user.userID,
                consent_type="news",
                consent_given_on=datetime.datetime.utcnow(),
                consent_given_via="signup_form",
            )
            db.session.add(consent)
            db.session.commit()

            # email verification needed for newsletter
            send_verification_email(user)
            flash("To receive newlsetter notifications you need to \
                   verify your email address. A verification email \
                   has been sent to your address.")

        # Log user in automatically
        login_user(user, remember=False)
        flash("Account registered successfully.", "success")
        return redirect(url_for("auth.signin"))

    return render_template("signup.html", reg_form=reg_form)
Esempio n. 34
0
    def add_user(self, name, fullname, password, email, admin):

        # pylint: disable=too-many-arguments

        # encrypt is deprecated but hash is not available in jessie
        try:
            pwhash = pbkdf2_sha512.hash(password)
        except AttributeError:
            pwhash = pbkdf2_sha512.encrypt(password)

        u = User(name=name,
                 fullname=fullname,
                 pwhash=pwhash,
                 email=email,
                 admin=admin)

        with session_scope(self.session) as s:
            if s.query(User).filter(User.name == name).count() > 0:
                raise ElbeDBError("user %s already exists in the database" %
                                  name)
            s.add(u)
Esempio n. 35
0
 def hash_password(password):
     return pbkdf2_sha512.hash(password)
Esempio n. 36
0
from passlib.hash import pbkdf2_sha512

password = input("password: ")
hash_password = pbkdf2_sha512.hash(password)
print(hash_password)
print(pbkdf2_sha512.verify(password, hash_password))