def add_property(): form = PropertyForm() if request.method == 'POST': name = request.form['property_name'] details = request.form['property_details'] property_info = name + details ph = PasswordHasher() user_hash = ph.hash(current_user.address) key = blockchain.add_property(property_info, user_hash) from blockchain.api.models import Property, Notifications property = Property(token=key, name=name, body=details) ph = PasswordHasher() user_address_hash = ph.hash(current_user.address) no = Notifications( user_address_hash=user_address_hash, time=str(datetime.datetime.now().strftime("%d/%m/%y %I:%M%p")), headline='Property Added', text=key, read=False) # TODO: if exists in db then update row to match name and details db.session.add(property) db.session.add(no) db.session.commit() message = "Property added successfully with key:{}".format(key) return render_template('message.html', message=message) return render_template('new_property.html', form=form)
def _console_test(argv): pw = argv[1] salt_length = int(argv[2]) hash_length = int(argv[3]) print('Password: %s' % pw) print('Salt Length: %s' % salt_length) print('Hash Length: %s' % hash_length) print('------------------------------') print('Calculating hash...') ph = PasswordHasher(hash_len=hash_length, salt_len=salt_length, encoding='utf-8', time_cost=1000, memory_cost=1024) pwhash = ph.hash(pw) print('Verifying hash...') ph2 = PasswordHasher() verified = ph2.verify(pwhash, pw) parsed = parse_argon_hash(pwhash) print('Results:') print('Hash : %s' % pwhash) print('Verified: %s' % verified) print('Parsed : %s' % parsed) """
def mutate(self, info, email=None, name=None, role=None, get_alerts=None, old_password=None, new_password=None): if get_jwt_claims()['role'] == 'Admin' and email and email != get_jwt_identity(): user = User.query.filter_by(email=email).first() if name: user.name = name if role: user.role = role if get_alerts is not None: user.get_alerts = get_alerts if new_password: ph = PasswordHasher() user.password = ph.hash(new_password) db.session.commit() else: user = User.query.filter_by(email=get_jwt_identity()).first() ph = PasswordHasher() if name: user.name = name if get_alerts is not None: user.get_alerts = get_alerts if old_password and new_password and ph.verify(user.password, old_password): user.password = ph.hash(new_password) db.session.commit() return UpdateUserMutation(user=user)
def test_check_needs_rehash_yes(self): """ Return True if any of the parameters changes. """ ph = PasswordHasher(1, 8, 1, 16, 16) ph_old = PasswordHasher(1, 8, 1, 8, 8) assert ph.check_needs_rehash(ph_old.hash("foo"))
def test_type_is_configurable(self): """ Argon2id is default but can be changed. """ ph = PasswordHasher(time_cost=1, memory_cost=64) default_hash = ph.hash("foo") assert Type.ID is ph.type is ph._parameters.type assert Type.ID is extract_parameters(default_hash).type ph = PasswordHasher(time_cost=1, memory_cost=64, type=Type.I) assert Type.I is ph.type is ph._parameters.type assert Type.I is extract_parameters(ph.hash("foo")).type assert ph.check_needs_rehash(default_hash)
def login(): message = "" site_login = request.form.get("site_login") password = request.form.get("password") result = db.execute( "SELECT password,visible_name,user_id FROM users WHERE login=:login", { "login": site_login }).fetchone() ### users table schema ### user_id | login | password | visible_name if result is None: message = "Login or password is incorrect. Please try again." return render_template("index.html", message=message) password_hash = result[0] message = password_hash visible_name = result[1] user_id = result[2] try: pwd_hasher = PasswordHasher() pwd_hasher.verify(password_hash, password) except argon2.exceptions.VerifyMismatchError: message = "Login or password is incorrect. Please try again." return render_template("index.html", message=message) except: message = "An error has occured during authentication. Please try again." return render_template("index.html", message=message) session['site_login'] = site_login session['visible_name'] = visible_name session['user_id'] = user_id return redirect(url_for('homepage'))
def createAccount():#create account sequence try: usr = sys.argv[2] except: print('Usage: ./pythenticator < -c | -l > username') exit(0) print('Creating user: '******':') if u == usr: print('user already exists') exit(0) pw = getpass.getpass(prompt='Enter password for user {}:'.format(usr))#password prompt if not policy.test(pw):#policy.test() returns empty list if it passes ph = PasswordHasher() pwhash = ph.hash(pw) with open("users.db", "a") as file: file.write(usr) file.write(':') file.write(pwhash) file.write('\n') print('User creation successful') else: print('The password you entered does not meet the following requriements: ', policy.test(pw))
def test_hash_password(self): kdf = PasswordHasher() password = '******' hash = kdf.hash(password) self.assertTrue(kdf.verify(hash, password))
def createuser(): """ Adds new user to database based on JSON data. """ # Get data data = request.get_json() # Check that all required fields are included if not data.get('username') or not data.get('password'): return jsonify(success=False, messages=["Username and password required"]) # Assign user variables username = str(data['username']) password = str(data['password']) # Check that username is unique user = check_collection_contains(db.collection('users'), 'username', username) if user is not None: return jsonify(success=False, messages=["Username already taken"]) # Hash password passhash = PasswordHasher().hash(password) # Create and add user to database db.collection('users').add({'username': username, 'passhash': passhash}) # Return success return jsonify(success=True)
def verificar_senha(self, password): ph = PasswordHasher() try: ph.verify(self.password, password) return {'status': True, 'msg': 'senha correta'} except Exception: return {'status': False, 'msg': 'senha incorreta'}
def login(): """Retrieve a token""" data = request.get_json() user = User.query.filter_by(username=data["username"]).first() if not user: return jsonify({"message": "Invalid credentials"}), 401 try: hasher = PasswordHasher() hasher.verify(user.password, data["password"]) except (VerifyMismatchError, VerificationError, InvalidHash, AttributeError): # This must also return 401 or else the user may learn # private information return jsonify({"message": "Invalid credentials"}), 401 # Rehash password if the parameters of the PasswordHasher change. # https://argon2-cffi.readthedocs.io/en/stable/api.html if hasher.check_needs_rehash(user.password): user.password = hasher.hash(data["password"]) db.session.add(user) db.session.commit() access_token = create_access_token(identity=user.username, fresh=True) refresh_token = create_refresh_token(user.username) return (jsonify({ "access_token": access_token, "refresh_token": refresh_token }), 200)
def post(self): required_fields = ["username", "password", "isAdmin"] # Get JSON data from request json_data = request.get_json(force=True) for field in required_fields: if field not in json_data.keys(): return jsonify({ "success": -1, "error": "Missing {} field".format(field) }) # create database session session = getSession(app.config["DB_USER"], app.config["DB_PASS"]) # check to see if username is taken if session.query(User).filter_by( username=json_data["username"]).first(): return jsonify({"success": -1, "error": "User already registered"}) # hash password ph = PasswordHasher() hash = ph.hash(json_data["password"]) try: new_user = User(username=json_data["username"], password=hash, admin=json_data["isAdmin"]) session.add(new_user) session.commit() return jsonify({"success": 1}) except: return jsonify({ "success": -1, "error": "Error adding new user to db" })
def login(request): if request.session.get('is_login', None): return redirect('search_view') if request.method == "POST": login_form = UserForm(request.POST) message = "Please check all fields" if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] try: user = models.User.objects.get(name=username) if not user.has_confirmed: #Check if the email is verified or not. message = "This account currently is disabled, please check your email." return render(request, 'login/login.html', locals()) ph = PasswordHasher() if ph.verify(user.password, password): #Check if the password is correct, thows exception if it is not #Write user status and data into Session dict request.session['is_login'] = True request.session['user_id'] = user.id request.session['user_name'] = user.name request.session['user_email'] = user.email request.session['user_password'] = user.password request.session['user_phone'] = user.phone return redirect('search_view') except: message = "Username or password is incorrect" return render(request, 'login/login.html', locals()) login_form = UserForm() return render(request, 'login/login.html', locals())
def get_credentials(self, client, login, passwd): import argon2 from argon2 import PasswordHasher # returncode, data = self.get_user_phash(login) # if returncode != 0: # raise ValueError(data) # ph = PasswordHasher() # # print("DATA iS ", data[0]) # if ph.verify(data[0], passwd): # self.verified_connections.add((id(client), client.getpeername())) # return [0, "=>Verification successfull."] # else: # raise ValueError("Verification faild") response = self.get_user_phash(login) if response['returncode'] != 0: return self.prepare_response(1, response['data'], "err") ph = PasswordHasher() try: ph.verify(response['data'], passwd) self.verified_connections.add((id(client), client.getpeername())) answer = "=>Verification successfull." return self.prepare_response(0, answer, "answer") except argon2.exceptions.VerifyMismatchError as e: print("!=> ", traceback.format_exc()) return self.prepare_response(1, str(e), "err")
def __init__(self, currentPassword, *args, **kwargs): super().__init__(*args, **kwargs) self.currentPassword = None if currentPassword is None else str(currentPassword) self.addWidgets() self.pwdhsr = PasswordHasher() self.passwordTimer = QtCore.QTimer(timeout=self.validateCurrentPassword) self.passwordTimer.setSingleShot(True)
def signup(): if request.method == "POST": data = request.form.to_dict() if data.get("password1"): if data.get("password1") == data.get("password2"): password_hash = PasswordHasher().hash(data.get("password1")) data.pop("password1", None) data.pop("password2", None) data["password_hash"] = password_hash exists = User.query.filter_by( email=data.get("email")).scalar() is not None if not exists: user = User(**data) db.session.add(user) db.session.commit() else: return render_template("signup.html", message="Email already in use.") else: return render_template("signup.html", message="Passwords don't match.") else: return render_template("signup.html", message="Must enter a password.") return redirect(url_for("auth.signup")) else: return render_template("signup.html")
def registration(useremail, password): try: ph = PasswordHasher() conn = psycopg2.connect(database=conn_db, user=conn_username, password=conn_password, host=conn_host, port=conn_port) cur = conn.cursor() cur.execute( "SELECT username from forumuser WHERE forumuser.username = "******"'" + useremail + "'") conn.commit() #is there for the sql injecton rows = cur.fetchall() if (len(rows) >= 1): return "This email already exists" else: randuserid = str(uuid.uuid1()) print("The password is: " + password) pwhash = ph.hash(password) cur.execute( "INSERT into forumuser(randuserid, username, passwordhash) VALUES(%s,%s,%s)", (randuserid, useremail, pwhash)) conn.commit() conn.close() return "Registration successful" except psycopg2.OperationalError as e: return "An Error occured during the registration\n{0}".format(e)
def gen_passwd_hash(pw): ph = PasswordHasher(hash_len=hash_length, salt_len=salt_length, encoding=encoding, time_cost=time_cost, memory_cost=memory_cost) pwhash = ph.hash(pw)
def encrypting_password(self): if not self.password: return {'status': False, 'msg': 'password not allow blank'} password_hash = PasswordHasher() self.password = password_hash.hash(self.password) return {'status': True, 'msg': 'senha encripitada'}
def signup(): form = Signup(prefix="a") print("hi") if request.method == "POST": psswd = form.password.data psswd_confirm = form.confirm.data if psswd != psswd_confirm: flash( "Input for Password and Confirm Password field doesn't match") return redirect(url_for("signup")) existing_name = user.query.filter_by(name=form.username.data).first() existing_email = user.query.filter_by(email=form.email.data).first() if existing_name or existing_email: print("This is bad news") flash("The email or username are already created") else: print("hi") ph = PasswordHasher() name = form.username.data email = form.email.data hashed_pw = ph.hash(form.password.data) usr = user(name=name, email=email, password=hashed_pw) db.session.add(usr) print(usr) db.session.commit() print("Saved") flash('Thanks for registering') return redirect(url_for("home")) return render_template("signup.html", form=form)
def __init__(self, auth_database: Union[str, Path]): if isinstance(auth_database, str): self.auth_db = Path(auth_database) elif isinstance(auth_database, Path): self.auth_db = auth_database self.ph = PasswordHasher() self.logger = logging.getLogger("ModernRelay.log")
def check_password_hash(hash: str, password: str) -> bool: ph = PasswordHasher() try: if ph.verify(hash, password): return True except argon2.exceptions.VerifyMismatchError: return False
def validateuser(): """ Validates that the username and password matches. """ # Get data data = request.get_json() # Check that all required fields are included if not data.get('username') or not data.get('password'): return jsonify(success=False, messages=["Username and assword required"]) # Assign user variables username = str(data['username']) password = str(data['password']) # Get user user = check_collection_contains(db.collection('users'), 'username', username) # Check that user exists if user is None: return jsonify(success=False, messages=["User does not exist"]) # Verify whether or not password is valid try: valid = PasswordHasher().verify(user.to_dict()['passhash'], password) except VerifyMismatchError: return jsonify(success=False, messages=["Invalid password"]) # Return success return jsonify(success=True)
async def resolve_register(_, info, data: RegisterInput): user = await user_collection.find_one({"email": data["email"]}) if user: return { "errors": [ { "type": "email_exists", "field": "email", "message": "That email already exists", } ] } try: RegisterInput(**data) except ValidationError as e: return { "errors": [ { "type": error["type"], "field": error["loc"][0], "message": error["msg"], } for error in e.errors() ] } else: hashed_password = PasswordHasher().hash(data["password"]) data["password"] = hashed_password data = add_created_at_updated_at(data) user = await user_collection.insert_one(camelize(data)) added_user = await user_collection.find_one({"_id": user.inserted_id}) print(added_user) return {"user": added_user}
def create_app(loop): """Starts the aiohttp process to serve the REST API""" setproctitle('socialite-api') logger.debug("boot") # init app app = web.Application() # pylint: disable=invalid-name app.on_startup.append(init_pg) app.middlewares.append(middleware_check_auth) app['settings'] = settings app['hasher'] = PasswordHasher() app['signer'] = TimestampSigner(settings.SECRET) # routes app.router.add_route('GET', '/api/status', status) app.router.add_route('POST', '/api/check_auth', check_auth) # routes for account app.router.add_route('POST', '/api/account/new', account_new) app.router.add_route('POST', '/api/account/login', account_login) # routes for wiki app.router.add_route('GET', '/api/wiki/{title}/latest', wiki_latest) app.router.add_route('POST', '/api/wiki/{title}/edit', wiki_edit) return app
async def login(_, info, email: str, password: str): print(info.context["request"]) print(dir(info.context["request"])) user = await user_collection.find_one({"email": email}) if not user: return { "errors": [ { "type": "user_not_found", "field": "email", "message": "User not found", } ] } try: PasswordHasher().verify(user["password"], password) except VerifyMismatchError: return { "errors": [ { "type": "incorrect_password", "field": "password", "message": "Incorrect password", } ] } return {"user": user}
def check_argon(uid, user_lst_3, password_1): ph = PasswordHasher() try: ph.verify(user_lst_3[uid], password_1) return True except argon2.exceptions.VerifyMismatchError: return False
def signin(user): __password = user['password'] try: __id = user['id'] users = User.objects.filter(id=__id) except: try: __email = user['email'] users = User.objects.filter(email=__email) except: pass ph = PasswordHasher() for u in users: if (u.active == 'false'): return None try: ph.verify(u.password, __password) __logged_user = { 'id': u.id, 'name': u.name, 'email': u.email, 'level': u.level } return __logged_user except: return None
def get_transactions(self, user_hash: str = ''): user_transactions = [] ph = PasswordHasher() if user_hash != '': for block in self.chain: for transaction in block['transactions']: try: if ph.verify(transaction['sender'], user_hash): temp_transaction = deepcopy(transaction) temp_transaction['sender'] = 'self' user_transactions.append(temp_transaction) except Exception: try: if ph.verify(transaction['reciever'], user_hash): temp_transaction = deepcopy(transaction) temp_transaction['recipient'] = 'self' user_transactions.append(temp_transaction) except Exception: continue return user_transactions for block in self.chain: for transaction in block['transactions']: user_transactions.append(transaction) return user_transactions
def update_user_by_id(id): if g.user.id == id: user = g.user else: user = User.query.filter(User.id == id).one_or_none() if user is None: return error(404) body = request.json password = body.get("password") role = body.get("role") if password: if len(password) < 8: return error(400, type="ShortPassword") hasher = PasswordHasher() hash = hasher.hash(password) user.password_hash = hash if role: if g.user.role != UserRole.ADMIN: return error(401, type="InsufficientPermission") if role != "normal" and role != "admin": return error(400, message="`role` must be one of {normal, admin}.") user.role = UserRole.ADMIN if (role == "admin") else UserRole.NORMAL db.session.commit() return serialize_user(user)