def change_password(db: alchemy, user: User, password: str, settings: AuthSettings): db.add(UsedPassword(password=user.password, user_id=user.id)) user.password = encrypt(password) user.must_change_password = False user.last_password_change_datetime, user.last_password_change_epoch = current_datetime_epoch( ) user.password_expiration_epoch = user.last_password_change_epoch + settings.password_expiration_epoch user.password_expiration_datetime = datetime.fromtimestamp( float(user.password_expiration_epoch)) db.commit()
def validate(user: User, settings: AuthSettings, password: str, db) -> str: if user is None: return WRONG_USERNAME_PASSWORD if user.id is not None and (password_exists(db, user.id, password) or user.password == encrypt(password)): return PASSWORD_USED if len(password) < settings.min_password_len: return PASSWORD_TOO_SHORT % settings.min_password_len if not has_enough(password, settings.min_special_letters_number, SPECIAL_CHARS): return FEW_SPECIALS % settings.min_special_letters_number if not has_enough(password, settings.min_uppercase_letters_number, UPPERCASE_LETTERS): return FEW_UPPERCASE % settings.min_uppercase_letters_number return VALID
def get_user_by_username_password(db: alchemy, username: str, password: str) -> User: return db.query(User).filter(User.username == username).filter( User.password == encrypt(password)).first()
def password_exists(db: alchemy, user_id, password) -> bool: return db.query(UsedPassword).filter( UsedPassword.user_id == user_id).filter( UsedPassword.password == encrypt(password)).first() is not None
from domain.models import AuthSettings, User settings = ConfigParser() settings.read('settings.ini') m = import_module(settings['alembic']['models_location'] + '.models') base = getattr(m, 'Base') engine = create_engine(settings['alembic']['sqlalchemy.url']) base.metadata.create_all(engine, checkfirst=True) db = sessionmaker(bind=engine, autoflush=False)() db.add( AuthSettings(failed_login_maximum_number=3, password_expiration_epoch=100000, session_expiration_epoch=100000, simultaneous_sessions_nro_allowed=1, min_special_letters_number=1, min_uppercase_letters_number=1, min_password_len=8)) db.add( User( id_number='666666', name='Pedro', last_name='Yupanqui', email_address='*****@*****.**', birthday=datetime(1985, 6, 17), username='******', password=encrypt('Admin6543!'), password_expire=True, is_admin=True, )) db.commit()