def set_password(self, password): """ Sets the profile password. :param password: User profile password :since: v0.2.00 """ with self: _type = None hashed_password = None if (PasswordGeneratorsMixin.PASSWORD_TYPE_MCF in self.password_generators_available): hashed_password = argon2.hash(password) _type = PasswordGeneratorsMixin.PASSWORD_TYPE_MCF elif (PasswordGeneratorsMixin.PASSWORD_TYPE_BLAKE2B in self.password_generators_available): hashed_password = self._get_blake2b_password(password, self.local.db_instance.name) _type = PasswordGeneratorsMixin.PASSWORD_TYPE_BLAKE2B elif (PasswordGeneratorsMixin.PASSWORD_TYPE_BLAKE2S in self.password_generators_available): hashed_password = self._get_blake2s_password(password, self.local.db_instance.name) _type = PasswordGeneratorsMixin.PASSWORD_TYPE_BLAKE2S elif (PasswordGeneratorsMixin.PASSWORD_TYPE_TMD5 in self.password_generators_available): hashed_password = self._get_tmd5_password(password, self.local.db_instance.name) _type = PasswordGeneratorsMixin.PASSWORD_TYPE_TMD5 # if (hashed_password is None): raise NotImplementedException("No hash algorithm is supported") self.local.db_instance.password_type = _type self.local.db_instance.password = hashed_password
def test_login_post_deactivated(self): from passlib.hash import argon2 from ..forms import AdminLoginForm from ..interfaces import IUserLoginService from ..models import User, UserSession from ..services import UserLoginService from ..views.admin import login_post from . import mock_service self._make( User( username="******", encrypted_password=argon2.hash("passw0rd"), ident="fooident", ident_type="ident", name="Foo", deactivated=True, ) ) self.dbsession.commit() request = mock_service( self.request, {IUserLoginService: UserLoginService(self.dbsession)} ) request.method = "POST" request.content_type = "application/x-www-form-urlencoded" request.session = testing.DummySession() request.POST = MultiDict({}) request.POST["username"] = "******" request.POST["password"] = "******" request.POST["csrf_token"] = request.session.get_csrf_token() response = login_post(request) self.assertEqual(self.dbsession.query(UserSession).count(), 0) self.assertIsInstance(response["form"], AdminLoginForm)
def register_user(username, fullname, password): if username_exists(username): raise Exception("REGISTER_USER ERROR: Username already exists.") hashed_password = argon2.hash(str(password)) db.execute("INSERT INTO users (username, fullname, password) VALUES (:username, :fullname, :password)", {"username": str(username), "fullname": str(fullname), "password": hashed_password}) db.commit()
def add_user(self, username, unencrypted_pw, groups=[], overwrite=False): if self._userdict.get(username): raise ValueError("Already exists!") if groups is None: groups = [] hashed_pass = argon2.hash(unencrypted_pw) self._userdict[username] = dict(hashed_password=hashed_pass, groups=groups) self._userdict.async_sync()
def test_verify_password_argon2(app, sqlalchemy_datastore): init_app_with_options(app, sqlalchemy_datastore, **{"SECURITY_PASSWORD_HASH": "argon2"}) with app.app_context(): hashed_pwd = hash_password("pass") assert verify_password("pass", hashed_pwd) assert "t=10" in hashed_pwd # Verify double hash assert verify_password("pass", argon2.hash(get_hmac("pass")))
def update(self, **kwargs): if ( app.settings["security"]["hash_user_passwords"] and kwargs.get("password") and not kwargs["password"].startswith("$argon2i") ): kwargs["password"] = argon2.hash(kwargs["password"]) super().update(**kwargs) if not kwargs.get("import_mechanism", False): self.update_rbac()
def check_password(self, password): try: pw_hash = self.user_config['settings']['password'] except KeyError: # hash function from passlib autogenerates # salt for each password, see https://passlib.readthedocs.io/en/stable/lib/passlib.hash.argon2.html pw_hash = argon2.hash(DEFAULT_PASSWORD) self.set_default_password() # set default password if password section is missing return argon2.verify(password, pw_hash)
def create_demo_user(neo4j_session): results = neo4j_session.run("MATCH (u:User {user : '******'}) RETURN u") result = results.single() if not result: print("Adding user 'demo' to the neo4j database.") neo4j_session.run( "CREATE (a:User {user: {username}, argon_password: {hash}})", { "username": "******", "hash": argon2.hash("demo123") })
def from_form(form: RegistrationForm) -> "RegistrationData": """ Returns the registration data for the given registration form. """ from passlib.hash import argon2 return RegistrationData(username=form.username.data.lower(), email=form.email.data.lower(), first_name=form.first_name.data.title(), last_name=form.last_name.data.title(), password=argon2.hash(form.password.data))
def edit_user(self, access: UserAccessMeta, password: str = None, hashed: bool = False, add: bool = False) -> bool: db = access.to_db() if password: db["password"] = password if hashed else argon2.hash(password) if add: self._auth_collection.insert_one(db) return True else: result = self._auth_collection.update_one({"user": access.user}, {"$set": db}) return result.modified_count > 0
def put(self): try: data = request.get_json() except Exception: return {"message": "bad request"}, 400 hash = argon2.hash(data['password']) query_db('insert into user values (NULL, ?, ?)', [data['username'], hash], commit=True) return {"message": "user registered"}, 201
def edit_user(user_id): if 'user_id' in session: cur = mysql.connection.cursor() cur.execute( "SELECT name,user_name,email,phone_no,role,password FROM users where user_id = %s", user_id) rows = cur.fetchone() cur.close() if request.method == 'POST': if (request.form["name"] == "" or request.form["username"] == "" or request.form["email"] == "" or request.form["phone"] == "" or request.form["password"] == "" or request.form["npassword"] == "" or request.form["cpassword"] == "" or request.form["role"] == ""): flash("Enter all the fields") return redirect(url_for('edit_user', user_id=user_id)) else: userDetails = request.form name = userDetails['name'] username = userDetails['username'] email = userDetails['email'] phone = userDetails['phone'] role = userDetails['role'] password = userDetails['password'] npassword = userDetails['npassword'] cpassword = userDetails['cpassword'] if (argon2.verify(password, rows[5])): if npassword == cpassword: xpassword = argon2.hash(npassword) cur = mysql.connection.cursor() cur.execute( "UPDATE users SET user_name = %s,name = %s,email = %s,phone_no = %s,role = %s,password = %s where user_id = %s", (username, name, email, phone, role, xpassword, user_id)) mysql.connection.commit() cur.close() flash("Records updated") return redirect(url_for("view_user")) else: flash("Both passwords must be same") return redirect(url_for('edit_user', user_id=user_id)) else: flash("Current password is not verified") return redirect(url_for('edit_user', user_id=user_id)) else: return render_template("edit_user.html", value=rows, user_id=user_id) else: return redirect(url_for('static', filename='403-forbidden-error.jpg'))
def hash_password(plain_text: str) -> str: """ Hash the plain text using argon2 algorithm. Args: plain_text: the value to be hashed. Returns: The hashed password. """ return argon2.hash(plain_text)
def create_root(email, password, fullname): hash = argon2.hash(password) new_root = User(fullname=fullname, email=email, hash=hash, is_root=True) try: new_root.save() root = User.fetchone(email=email) root_info = UserInfo( user_id=root.id, permission_groups=[group.name for group in all_permission_groups]) root_info.save() except UniqueViolatedError: print('Duplicated root user')
def add_user(self, username, unencrypted_pw, groups=None, overwrite=False): if self._userdict.get(username) and not overwrite: raise ValueError( f"The user {username} is already present and overwrite not set to True" ) if groups is None: groups = [] hashed_pass = argon2.hash(unencrypted_pw) self._userdict[username] = dict(hashed_password=hashed_pass, groups=groups) self._userdict.sync()
async def create_user(username: str, password: str) -> None: """Create an API user.""" hashed_password = argon2.hash(password) try: await ApiUser.create(username=username, password=hashed_password) except IntegrityError: raise AuthError("User '{u}' already exists.", u=username, status_code=409) from None log.success("Added user {}", username)
def inscription(): if not current_user.is_authenticated: if request.method == "POST": firstName = request.form.get('inscription[firstName]') lastName = request.form.get('inscription[lastName]') userName = request.form.get('inscription[userName]') mail = request.form.get('inscription[mail]') password = request.form.get('inscription[password]') for res in mongo.db.users.find( {"$or": [{ "username": userName }, { "email": mail }]}): if res is not None: flash("Nom d'utilisateur et / ou mail déjà utilisé", 'signup-form--error') return render_template('pages/inscription.html', title="inscription") if firstName == "": flash('Vous devez renseignez votre prénom', 'signup-form--error') if lastName == "": flash('Vous devez renseignez votre nom', 'signup-form--error') if userName == "": flash('Vous devez renseignez un nom d\'utilsateur', 'signup-form--error') if mail == "": flash('Vous devez renseignez une adresse email', 'signup-form--error') if password == "": flash('Vous devez renseignez un mot de passe', 'signup-form--error') if firstName != "" and lastName != "" and userName != "" and mail != "" and password != "": mongo.db.users.insert_one({ "firstname": firstName, "lastname": lastName, "username": userName, "email": mail, "password": argon2.hash(password), "profile_image": "", "isAdmin": False }) return redirect(url_for('login')) return render_template('pages/inscription.html', title="inscription") return redirect(url_for('home'))
async def admin_confirm(register_token: str): """Registration confirmation and account creation. - **register_token**: Registration token received in email from /register """ try: values = from_token(register_token) passhash = argon2.hash(values['password']) await Admin.objects.create(email=values['email'], passhash=passhash) return BodyAccessToken(access_token=register_token) except IntegrityError: raise HTTPException(status_code=status.HTTP_409_CONFLICT)
def updateSelf(): """"Endpoints to handle updating an authenticate user. Returns: str -- Returns a refreshed instance of user as a JSON or an JSON containing any error encountered. """ # Validate that only the valid User properties from the JSON schema update_self.schema.json schemas_direcotry = os.path.join(current_app.root_path, current_app.config['SCHEMA_FOLDER']) schema_filepath = os.path.join(schemas_direcotry, 'update_self.schema.json') try: with open(schema_filepath) as schema_file: schema = json.loads(schema_file.read()) validate(instance=request.json, schema=schema, format_checker=draft7_format_checker) except jsonschema.exceptions.ValidationError as validation_error: return {'code': 400, 'message': validation_error.message}, 400 try: with session_scope() as db_session: user = db_session.merge(g.user) current_password = request.json.get("current_password") # Current User Password is required before applying any changes if argon2.verify(current_password, user.password) is False: return { 'code': 400, 'message': "Current password is incorrect" }, 400 # Update the values to the current User for k, v in request.json.items(): # if k == password hash password if k == "password": user.__dict__[k] = argon2.hash(v) user.reset_password = False else: user.__dict__[k] = v db_session.add(user) g.user = user db_session.expunge(g.user) db_session.merge(g.user) except DBAPIError as db_error: return { 'code': 400, 'message': re.search('DETAIL: (.*)', db_error.args[0]).group(1) }, 400 return g.user.to_json(), 200
def bf(h, dictionary): f = open(dictionary, 'r') lines = f.readlines() print('\033[1;34m[*]\033[0m Starting Brute Force - hash = ' + h) for i in lines: h2 = argon2.hash(i[:-1]) if h == h2: print('\033[1;32m[+]\033[0m Hash Cracked! - Password = ' + i) exit()
def generate_hash(username, password): # find user node in database matcher = NodeMatcher(GRAPH) user_node = matcher.match("User", username=username).first() # if the user already exists, we get their salt from the db if user_node is None: hashed = argon2.hash(password) else: hashed = user_node['hashed_password'] return hashed
def update_password(username, password): if session['username'] == username or is_admin(): user = get_user(username) if user: log.debug(user[0][2]) password_string = "{}{}".format(password, user[0][2]) password_hash = argon2.hash(password_string) success = set_data( "update users " "set hash = %s " "where username = %s", [password_hash, username]) return success return False
def register(request: Request) -> UserResponse: """User registers to Conduit app.""" body = request.openapi_validated.body user = User( email=body["user"]["email"], username=body["user"]["username"], password_hash=argon2.hash(body["user"]["password"]), ) request.db.add(user) request.db.flush() # so that user.id is set and JWT token can be generated request.response.status_code = 201 return {"user": user}
def generate_password(data: dict): if not 'userid' in data: return Response.wrong_format({ 'updated': False, 'message': 'userid missing' }) person = session.query(Person).filter_by(id=data["userid"]).first() password = ''.join( [choice('abcdefghijklmnopqrstuvwxyz0123456789-') for i in range(15)]) person.password = argon2.hash(password) session.commit() return '{ "new_password" : "{}"}'.format(password)
def register(request: Request) -> UserResponse: """User registers to {{cookiecutter.project_name}} app.""" body = request.openapi_validated.body user = User( email=body.user.email, username=body.user.username, password_hash=argon2.hash(body.user.password), ) request.db.add(user) request.db.flush() # so that user.id is set and JWT token can be generated request.response.status_code = 201 return {"user": user}
def register(): session.clear() if request.method == 'POST': hashh = argon2.hash(request.form['password']) all_users.insert_one({ 'User_name': request.form['user'], 'Email': request.form['email'], 'Password': hashh }) session['User'] = request.form['user'] return redirect(url_for('upload')) else: return render_template('register.html')
def create_user(email, password, fname, lname, phone): """Create and return a new user.""" user = User(email=email, password=argon2.hash(password), fname=fname, lname=lname, phone=phone) db.session.add(user) db.session.commit() return user
def Post_login(): username = request.forms.get('username') password = request.forms.get('password') q = query("select * from Users where username=?", params=[username]) if len(q) == 0: # prevent timing attacks argon2.hash("whatever") return Template( open("templates/login.html").read()).render(failure=True) else: user = db_dictify(q[0], SCHEMA_USER) correct = argon2.verify(password, user["password"]) if correct: new_token = str(uuid4()) response.set_cookie("login_token", new_token, path="/") login_tokens[new_token] = user["uid"] redirect("/app") return else: return Template( open("templates/login.html").read()).render(failure=True)
def post(self, args): """ --- summary: Registration description: Creates new user profile requestBody: required: true content: application/json: schema: RegistrationSchema example: $ref: '#/components/examples/Registration' responses: 201: description: OK 406: description: Invalid data provided content: application/json: schema: ErrorSchema example: message: [Invalid email] 409: description: User already exists content: application/json: schema: ErrorSchema example: message: [A user with that email already exists.] """ ORM = application.orm # if not validate_email(args["email"], check_mx=True, verify=True): if not validate_email(args["email"]): return fail_response('Invalid email', code=406) existing_user = ORM.get_user_auth_by_email(email=args["email"]) if existing_user: return fail_response('User with such email already exists', code=409) user = ORM.add_user(first_name=args["name"], last_name=args["surname"]) ORM.add_candidates_authorization(u_id=user.id, email=args["email"], password=argon2.hash( args["password"])) ORM.add_candidates_documents(u_id=user.id) ORM.add_candidates_info(candidate_id=user.id) return generic_response(201)
def init(): global HMAC_SECRET, EXPECTED_HOSTNAME, DUMMY_HASH load_dotenv(verbose=True) HMAC_SECRET = os.getenv("HMAC_SECRET_KEY").encode('utf-8') EXPECTED_HOSTNAME = os.getenv("EXPECTED_HOSTNAME") # load the argon2 parameters one by one (refer to .env for details) ARGON_PARAMS["rounds"] = int(os.getenv("ARGON_ROUNDS")) ARGON_PARAMS["memory"] = int(os.getenv("ARGON_MEMORY")) ARGON_PARAMS["threads"] = int(os.getenv("ARGON_THREADS")) ARGON_PARAMS["expected_time"] = int(os.getenv("ARGON_EXPECTED_TIME")) ARGON_PARAMS["fuzzing_time"] = int(os.getenv("ARGON_FUZZING_TIME")) DUMMY_HASH = argon2.hash("dummyhash")
def change_password(): old_password = request.form.get("old_password") new_password = request.form.get("new_password") new_password_repeat = request.form.get("new_password_repeat") if new_password != new_password_repeat: flash("passwords do not match") return redirect(url_for(".change_password_page")) if not authenticate(session["username"], old_password): flash("wrong password") return redirect(url_for(".change_password_page")) user = Users.query.filter_by(username=session["username"]).first() user.password_hash = argon2.hash(new_password) db.session.commit() return render_template("password_change_success.html")
def upload_csv(file): first_name = 'fn' surname = 'sn' mail = 'mail' if not file: return Response.wrong_format({'message': 'no file'}) try: csv_file_pandas = read_csv(file, usecols=[first_name, surname, mail]) except ValueError: return Response.wrong_format({ 'message': '.csv columns missing. Must contain {}, {}'.format( first_name, surname, mail) }) except: return Response.server_error({'message': 'error processing .csv-file'}) pw_list = [] for index, row in csv_file_pandas.iterrows(): person = Person() person.name = '{} {}'.format(row[first_name], row[surname]) password = ''.join([ choice('abcdefghijklmnopqrstuvwxyz0123456789-') for i in range(15) ]) person.password = argon2.hash(password) person.mail = row[mail] person.is_present = False person.role = '0' pw_list.append({ 'mail': person.mail, 'password': password, 'name': person.name }) session.add(person) duplicates = [] try: session.commit() except IntegrityError as e: print(e) duplicates.append(e) except: return Response.database_error() send_email(pw_list) return Response.ok({'message': 'ok', "duplicates": str(duplicates)})
def test_login_post(self): from passlib.hash import argon2 from ..interfaces import IUserLoginService from ..models import User, UserSession from ..services import UserLoginService from ..views.admin import login_post from . import mock_service self._make( User( username="******", encrypted_password=argon2.hash("passw0rd"), ident="fooident", ident_type="ident_admin", name="Foo", ) ) self.dbsession.commit() request = mock_service( self.request, {IUserLoginService: UserLoginService(self.dbsession)} ) request.method = "POST" request.content_type = "application/x-www-form-urlencoded" request.session = testing.DummySession() request.POST = MultiDict({}) request.POST["username"] = "******" request.POST["password"] = "******" request.POST["csrf_token"] = request.session.get_csrf_token() self.config.testing_securitypolicy( userid=None, remember_result=[("Set-Cookie", "foobar")] ) self.config.add_route("admin_dashboard", "/admin/dashboard") response = login_post(request) self.assertEqual(response.location, "/admin/dashboard") self.assertEqual(self.dbsession.query(UserSession).count(), 1) self.assertIn("Set-Cookie", response.headers)
def encrypt_pass(password): return argon2.hash(password)