def crypt_context(): return CryptContext(schemes=['sha256_crypt'])
def hashPassword(password): pwd_context = CryptContext(schemes=["pbkdf2_sha256"], default="pbkdf2_sha256", pbkdf2_sha256__default_rounds=30000) return pwd_context.hash(password)
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from jose import JWTError, jwt from passlib.context import CryptContext pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto') oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token')
# pkg from passlib.context import CryptContext from passlib.exc import ExpectedTypeError from passlib.ext.django.utils import _PatchManager, hasher_to_passlib_name, \ get_passlib_hasher, get_preset_config from passlib.utils.compat import callable, unicode, bytes # local __all__ = ["password_context"] #============================================================================= # global attrs #============================================================================= # the context object which this patches contrib.auth to use for password hashing. # configuration controlled by ``settings.PASSLIB_CONFIG``. password_context = CryptContext() # function mapping User objects -> passlib user category. # may be overridden via ``settings.PASSLIB_GET_CATEGORY``. def _get_category(user): """default get_category() implementation""" if user.is_superuser: return "superuser" elif user.is_staff: return "staff" else: return None # object used to track state of patches applied to django.
from flask_cors import CORS class Cors(): """Creates a class for COS in the backend. [cors]_ [fcors]_ Per the CORS documentation, the settings for CORS are determined in the following order: 1. Resource level settings (e.g when passed as a dictionary) 2. Keyword argument settings 3. App level configuration settings (e.g. CORS_*) 4. Default settings """ def init_app(self, app, *args, **kwargs): """ Defines arguments to leverage flasks CORS method Parameters: app (Flask app): the Flask app from which to configure CORS model. """ CORS(app, *args, **kwargs) cors = Cors() db = SQLAlchemy() jwt = JWTManager() ma = Marshmallow() migrate = Migrate() pwd_context = CryptContext(schemes=['pbkdf2_sha256'], deprecated='auto')
def password_context(self): return CryptContext(schemes=["pbkdf2_sha256"], default="pbkdf2_sha256", pbkdf2_sha256__default_rounds=30000)
# # import the CryptContext class, used to handle all hashing... # from passlib.context import CryptContext # # create a single global instance for your app... # pwd_context = CryptContext( schemes=["sha512_crypt"], default="sha512_crypt", )
def _get_pwd_context() -> CryptContext: return CryptContext(schemes=['bcrypt'], deprecated='auto')
import docxtpl import flask import convertapi import yagmail from flask import request from flask_httpauth import HTTPBasicAuth from passlib.context import CryptContext from pathlib import Path from dotenv import load_dotenv import os from random import randrange load_dotenv() app = flask.Flask(__name__) auth = HTTPBasicAuth() pwd_context = CryptContext(schemes=['sha512_crypt']) my_email = '*****@*****.**' recipient_email = my_email path = Path() convertapi.api_secret = os.environ['CONVERTAPI_SECRET'] password_hash = os.environ['AUTH_HASH'] image_folder = Path("images") ALLOWED_FILETYPES = {'txt', 'jpg', 'jpeg', 'png', 'gif', 'svg'} def send_email(order_number, body, attachments): yag = yagmail.SMTP(my_email) yag.send(to=recipient_email, subject=f"Order {order_number} from Zana", contents=body, attachments=attachments,
) import sqlalchemy as sa from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, ) from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() password_context = CryptContext(schemes=['pbkdf2_sha512']) class MyModel(Base): __tablename__ = 'models' id = Column(Integer, primary_key=True) name = Column(Text) value = Column(Integer) Index('my_index', MyModel.name, unique=True, mysql_length=255) class Entry(Base): __tablename__ = 'entries' id = Column(Integer, primary_key=True)
def identify(cls, hash): (salt, hash) = cls._get_salt_and_hash(hash) return salt and hash @classmethod def hash(cls, secret, **kwds): salt = newsalt() hash = getpwhash(secret, salt) return "%s:%s" % (salt, hash) @classmethod def verify(cls, secret, hash): (salt, hash) = cls._get_salt_and_hash(hash) return salt and hash and (getpwhash(secret, salt) == hash) pwd_context = CryptContext(schemes=["argon2", DevpiHandler], deprecated="auto") def verify_and_update_password_hash(password, hash, salt=None): if salt is not None: hash = "%s:%s" % (salt, hash) (valid, newhash) = pwd_context.verify_and_update(password, hash) if newhash: newhash = py.builtin._totext(newhash) return (valid, newhash) def hash_password(password): return py.builtin._totext(pwd_context.hash(password))
class User(Model): """Serve as root entities for Comments and Practices.""" # see config.auth_types last_login = sndb.DateTimeProperty(auto_now_add=True) auth_id = sndb.StringProperty(required=True, validator=lambda prop, value: value.lower()) facebook_id = sndb.StringProperty(default=None, search_type=search.TextField) google_id = sndb.StringProperty(default=None, search_type=search.TextField) hashed_password = sndb.StringProperty(default=None) first_name = sndb.StringProperty(default='', search_type=search.TextField) last_name = sndb.StringProperty(default='', search_type=search.TextField) email = sndb.StringProperty(required=True, validator=lambda prop, value: value.lower(), search_type=search.TextField) is_admin = sndb.BooleanProperty(default=False) receives_updates = sndb.BooleanProperty(default=True) image_url = sndb.StringProperty(default='') short_bio = sndb.StringProperty(default='') # Username for display username = sndb.StringProperty(search_type=search.TextField) # Username for uniqueness checking canonical_username = sndb.ComputedProperty( lambda self: self.username.lower() if self.username else '') authorship_invites = sndb.StringProperty(repeated=True, default=None) # App Engine can only run pure-python external libraries, and so we can't get # a native (C-based) implementation of bcrypt. Pure python implementations are # so slow that [the feasible number of rounds is insecure][1]. This uses the # [algorithm recommended by passlib][2]. # [1]: http://stackoverflow.com/questions/7027196/how-can-i-use-bcrypt-scrypt-on-appengine-for-python # [2]: https://pythonhosted.org/passlib/new_app_quickstart.html#sha512-crypt password_hashing_context = CryptContext( schemes=['sha512_crypt', 'sha256_crypt'], default='sha512_crypt', all__vary_rounds=0.1, # Can change hashing rounds here. 656,000 is the default. # sha512_crypt__default_rounds=656000, # sha256_crypt__default_rounds=656000, ) @classmethod def create(klass, check_uniqueness=True, **kwargs): """Checks email uniqueness before creating; raises DuplicateUser. Checking uniqueness always generates a Unique entity (an entity of class 'Unique') that permanently reserves the email address. But checking is also optional, and can be passed as False for testing. See http://webapp-improved.appspot.com/_modules/webapp2_extras/appengine/auth/models.html#User.create_user """ # If no username, generate one! if 'username' not in kwargs: kwargs['username'] = User.create_username(**kwargs) else: if User.is_valid_username(kwargs['username']): raise InvalidUsername( "Invalid username {}. Use only letters, numbers, dashes, and underscores." .format(kwargs['username'])) # Check for uniqueness of email and username if check_uniqueness: uniqueness_key = 'User.email:' + kwargs['email'] is_unique_email = Unique.create(uniqueness_key) if not is_unique_email: raise DuplicateUser( "There is already a user with email {}.".format( kwargs['email'])) uniqueness_key = 'User.username:'******'username'].lower() is_unique_username = Unique.create(uniqueness_key) if not is_unique_username: # Need to also delete the unused email! # To ensure that this works on retry is_unique_email.delete() raise DuplicateUser( "There is already a user with username {}.".format( kwargs['username'])) # Register user for the mailchimp list should_subscribe = kwargs.pop('should_subscribe', False) if should_subscribe is not False: fields = {} if 'first_name' in kwargs: fields['first_name'] = kwargs['first_name'] if 'last_name' in kwargs: fields['last_name'] = kwargs['last_name'] subscribed = mailchimp.subscribe(kwargs['email'], **fields) if subscribed: kwargs['receives_updates'] = True # Add new user to user full text search index kwargs['listed'] = True kwargs['created'] = datetime.datetime.now() kwargs['modified'] = datetime.datetime.now() newUser = super(klass, klass).create(**kwargs) index = search.Index(config.user_index) index.put(newUser.to_search_document()) return newUser @classmethod def hash_password(klass, password): if re.match(config.password_pattern, password) is None: raise BadPassword(u'Bad password: {}'.format(password)) return klass.password_hashing_context.encrypt(password) @classmethod def verify_password(klass, password, hashed_password): return (klass.password_hashing_context.verify( password, hashed_password) if hashed_password else False) @classmethod def get_auth_id(klass, auth_type, third_party_id): if auth_type not in config.auth_types: raise Exception("Invalid auth type: {}.".format(auth_type)) return '{}:{}'.format(auth_type, third_party_id) @property def auth_type(self): return self.auth_id.split(':')[0] @property def full_name(self): if self.first_name and self.last_name: return self.first_name + ' ' + self.last_name if self.first_name: return self.first_name return self.username @property def profile_image(self): return self.image_url or '{}/static/images/default-user.png'.format( os.environ['HOSTING_DOMAIN']) def set_password(self, new_password): """May raise BadPassword.""" logging.info("Setting new password {} for user {}.".format( new_password, self)) self.hashed_password = self.hash_password(new_password) # Alert the user that their password has been changed. mandrill.send( to_address=self.email, subject="Your BELE Library password has been changed.", template="change_password.html", template_data={ 'domain': 'https://{}'.format(os.environ['HOSTING_DOMAIN']), 'year': datetime.date.today().year, }, ) @classmethod def check_email_uniqueness(self, email): """Check if email is used""" unique = Unique.get_by_id('User.email:' + email.lower()) return unique is None @classmethod def check_username_uniqueness(self, username): """Check if username is used""" unique = Unique.get_by_id('User.username:'******'[^A-Za-z0-9\-\_]') return username != regex.sub('', username) @classmethod def create_username(klass, **kwargs): unformatted_username = '' if 'first_name' in kwargs and 'last_name' in kwargs: if kwargs['last_name'] is not None: unformatted_username = kwargs['first_name'] + kwargs[ 'last_name'] else: unformatted_username = kwargs['first_name'] elif 'email' not in kwargs: logging.error( u"User doesn't have an email address {}".format(kwargs)) else: unformatted_username = kwargs['email'].split('@')[0] regex = re.compile('[^A-Za-z0-9\-\_]') username = regex.sub('', unformatted_username) if not User.check_username_uniqueness(username): # If not unique, iterate through available names raw_username = username for n in range(1, 1000): username = raw_username + str(n) if User.check_username_uniqueness(username): break if n == 999: raise Exception( "No unique username found after 1000 tries.") return username @classmethod def set_subscription(self, email, should_subscribe): """Sets user's subscription status to Update List on mailchimp """ # Use 'resubscribe' and 'unsubscribe' methods if should_subscribe is True: subscribed = mailchimp.resubscribe(email) # if resubscription failed, they might not be subscribed at all! if not subscribed: subscribed = mailchimp.subscribe(email) elif should_subscribe is False: subscribed = mailchimp.unsubscribe(email) return subscribed def _post_put_hook(self, value): super(User, self)._post_put_hook(value) index = search.Index(config.user_index) if self.listed: index.put(self.to_search_document()) else: index.delete(self.uid) def _post_delete_hook(self, key, value): search.Index(config.user_index).delete(key.id()) super(User, self)._post_delete_hook(key, value) def update_email(self, email): # Remove old email from unique keys so it can be re-used! old_email = self.email uniqueness_key = 'User.email:' + old_email Unique.delete_multi([uniqueness_key]) # Update to new email and check uniqueness setattr(self, 'email', email) uniqueness_key = 'User.email:' + email unique = Unique.create(uniqueness_key) if not unique: raise DuplicateField( "There is already a user with email {}.".format(email)) # Also need to update the user in our mailchimp mailchimp.unsubscribe(old_email) if self.receives_updates: subscribed = mailchimp.subscribe(email) # if subscription failed, they might need to resubscribe! if not subscribed: subscribed = mailchimp.resubscribe(email) return unique def update_username(self, username): if self.username is not None: uniqueness_key = 'User.username:'******'username', username) uniqueness_key = 'User.username:'******'User.email:' + self.email uniqueness_key_username = '******' + self.username Unique.delete_multi([uniqueness_key_email, uniqueness_key_username]) def add_user_image(self, blob_key): """Save dictionary of user image urls. Create permenant link to user image -- You can resize and crop the image dynamically by specifying the arguments in the URL '=sxx' where xx is an integer from 0-1600 representing the length, in pixels, of the image's longest side Reference: https://cloud.google.com/appengine/docs/python/images/#Python_Transforming_images_from_the_Blobstore """ image_url = images.get_serving_url(blob_key, secure_url=True) self.image_url = image_url # Create a UserImage object pointing to blobstore object # Reference used for removal of old UserImages user_image = UserImage.create( user_id=self.uid, blob_key=blob_key, ) user_image.put() def remove_user_image(self): """Removes existing user's image completely""" self.image_url = '' # Find associated UserImage user_image = UserImage.query(user_id=self.uid) # Remove permenant link for image images.delete_serving_url(user_image.blob_key) user_image.deleted = True user_image.put()
def random_passwd(self, num): """ 生成随机密码 :return: """ __numlist = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "q", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "W", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", ] rang = num if rang == None: passwd = "".join(random.choice(__numlist) for i in range(8)) else: passwd = "".join( random.choice(__numlist) for i in range(int(rang))) crypt_context = CryptContext(schemes=["pbkdf2_sha512", "plaintext"], deprecated=["plaintext"]) hash_password = (crypt_context.hash if hasattr(crypt_context, "hash") else crypt_context.encrypt) return hash_password(passwd)
def create_password_crypt_context(self, authc_settings): context = dict(schemes=[authc_settings.preferred_algorithm]) context.update(authc_settings.preferred_algorithm_context) return CryptContext(**context)
from passlib.context import CryptContext pwd_context = CryptContext( schemes=["pbkdf2_sha256"], default="pbkdf2_sha256", all__vary_rounds=0.1, pbkdf2_sha256__default_rounds=8000, )
class UsersService: """Users management service""" __PWD_CONTEXT__ = CryptContext(schemes=["bcrypt"], deprecated="auto") def __init__(self, users: UsersDAO): self.__dao__ = users def authenticate_user(self, username: str, password: str) -> Optional[User]: """ Authenticates an user given username/password Parameters ---------- username: The user name password: The password Returns ------- An user instance if authentication success. None otherwise """ user = self.__dao__.get_user(username) if user and self.__verify_password__(password, user.hashed_password): return user @staticmethod def create_access_token( username: str, expires_delta: Optional[timedelta] = None ) -> str: """ Creates an access token Parameters ---------- username: The user name expires_delta: Token expiration Returns ------- An access token string """ to_encode = { "sub": username, "exp": datetime.utcnow() + (expires_delta or timedelta(minutes=15)), } return jwt.encode( to_encode, settings.secret_key, algorithm=settings.algorithm, ) def fetch_token_user(self, token: str) -> Optional[User]: """ Fetch the user for a given access token Parameters ---------- token: The access token Returns ------- An User instance if a valid token was provided. None otherwise """ try: payload = jwt.decode( token, settings.secret_key, algorithms=[settings.algorithm], ) username: str = payload.get("sub") if username: return self.__dao__.get_user(user_name=username) except JWTError: return None def __verify_password__(self, password: str, hashed_password: str) -> bool: return self.__PWD_CONTEXT__.verify(password, hashed_password) def __get_password_hash__(self, password: str): return self.__PWD_CONTEXT__.hash(password)
from flask_sqlalchemy import SQLAlchemy from sqlalchemy_utils import types import flask_login from passlib.context import CryptContext import uuid db = SQLAlchemy() crypt_context = CryptContext(schemes=["bcrypt", "pbkdf2_sha256"], default="pbkdf2_sha256") class HashedPassword: def __init__(self, hash): self.hash = hash @classmethod def from_password(cls, password): return cls(hash=crypt_context.hash(password)) def __eq__(self, test): if isinstance(test, HashedPassword): return test.hash == self.hash elif isinstance(test, str): return crypt_context.verify(test, self.hash) else: raise TypeError("Must be HashedPassword or str") class User(db.Model, flask_login.mixins.UserMixin): id = db.Column(db.Integer, primary_key=True)
def __init__(self, configfile): c = ConfigParser.ConfigParser() c.read(configfile) self.database_name = c.get('database', 'name') self.database_user = c.get('database', 'user') if c.has_option('database', 'driver'): self.database_driver = c.get('database', 'driver') else: self.database_driver = 'psycopg2' if c.has_option('database', 'password'): self.database_pw = c.get('database', 'password') else: self.database_pw = None if c.has_option('database', 'host'): self.database_host = c.get('database', 'host') else: self.database_host = None if c.has_option('database', 'port'): self.database_port = c.getint('database', 'port') else: self.database_port = None if c.has_option("database", "aws_access_key_id"): self.database_aws_access_key_id = c.get("database", "aws_access_key_id") else: self.database_aws_access_key_id = None if c.has_option("database", "aws_secret_access_key"): self.database_aws_secret_access_key = c.get( "database", "aws_secret_access_key") else: self.database_aws_secret_access_key = None if c.has_option("database", "files_bucket"): self.database_files_bucket = c.get("database", "files_bucket") else: self.database_files_bucket = None if c.has_option("database", "docs_bucket"): self.database_docs_bucket = c.get("database", "docs_bucket") else: self.database_docs_bucket = None if c.has_option("database", "releases_index_url"): self.database_releases_index_url = c.get("database", "releases_index_url") else: self.database_releases_index_url = None if c.has_option("database", "releases_index_name"): self.database_releases_index_name = c.get("database", "releases_index_name") else: self.database_releases_index_name = None self.database_files_dir = c.get('database', 'files_dir') self.database_docs_dir = c.get('database', 'docs_dir') if c.has_option('database', 'pubsubhubbub'): self.pubsubhubbub = c.get('database', 'pubsubhubbub') else: self.pubsubhubbub = None if c.has_option('webui', 'package_docs_url'): self.package_docs_url = c.get('webui', 'package_docs_url') else: self.package_docs_url = 'http://pythonhosted.org' self.adminemail = c.get('webui', 'adminemail') self.replyto = c.get('webui', 'replyto') self.url = c.get('webui', 'url') self.scheme_host = urlunsplit(urlsplit(self.url)[:2] + ('', '', '')) if c.has_option('webui', 'statuspage_id'): self.statuspage_id = c.get('webui', 'statuspage_id') else: self.statuspage_id = False self.orig_pydotorg = self.pydotorg = c.get('webui', 'pydotorg') if self.url.startswith("https:"): self.pydotorg = '/' self.simple_script = c.get('webui', 'simple_script') self.files_url = c.get('webui', 'files_url') self.rss_file = c.get('webui', 'rss_file') self.packages_rss_file = c.get('webui', 'packages_rss_file') self.debug_mode = c.get('webui', 'debug_mode') self.cheesecake_password = c.get('webui', 'cheesecake_password') self.key_dir = c.get('webui', 'key_dir') self.simple_sign_script = c.get('webui', 'simple_sign_script') self.raw_package_prefix = c.get("webui", "raw_package_prefix") if c.has_option('webui', 'sshkeys_update'): self.sshkeys_update = c.get('webui', 'sshkeys_update') else: self.sshkeys_update = None self.reset_secret = c.get('webui', 'reset_secret') self.logfile = c.get('logging', 'file') self.mail_logger = c.get('logging', 'mail_logger') self.fromaddr = c.get('logging', 'fromaddr') self.toaddrs = c.get('logging', 'toaddrs').split(',') self.queue_redis_url = c.get('database', 'queue_redis_url') self.count_redis_url = c.get('database', 'count_redis_url') if c.has_option('database', 'cache_redis_url'): self.cache_redis_url = c.get('database', 'cache_redis_url') else: self.cache_redis_url = None if c.has_option('database', 'block_redis_url'): self.block_redis_url = c.get('database', 'block_redis_url') else: self.block_redis_url = None self.sentry_dsn = c.get('sentry', 'dsn') self.passlib = CryptContext( # Unless we've manually specified a list of deprecated # algorithms assume we will deprecate all but the default. deprecated=["auto"], ) # Configure a passlib context from the config file self.passlib.load_path(configfile, update=True) # Get the fastly API key self.fastly_api_domain = c.get("fastly", "api_domain") self.fastly_api_key = c.get("fastly", "api_key") self.fastly_service_id = c.get("fastly", "service_id") # Get the smtp configuration self.smtp_hostname = c.get("smtp", "hostname") self.smtp_auth = c.getboolean("smtp", "auth") self.smtp_starttls = c.getboolean("smtp", "starttls") if self.smtp_auth: self.smtp_login = c.get("smtp", "login") self.smtp_password = c.get("smtp", "password") self.blocked_timeout = c.get("blocking", "blocked_timeout") self.blocked_attempts_user = c.get("blocking", "blocked_attempts_user") self.blocked_attempts_ip = c.get("blocking", "blocked_attempts_ip") # Get Authomatic Secret self.authomatic_secure = c.get("authomatic", "secure") self.authomatic_secret = c.get("authomatic", "secret") # Get Google OAuth2 Creds self.google_consumer_id = c.get("google", "client_id") self.google_consumer_secret = c.get("google", "client_secret")
def _get_hashing_context(app): schemes = cv("HASHING_SCHEMES", app=app) deprecated = cv("DEPRECATED_HASHING_SCHEMES", app=app) return CryptContext(schemes=schemes, deprecated=deprecated)
def init_app(self, app, db_adapter=None, # Forms add_email_form=forms.AddEmailForm, change_password_form=forms.ChangePasswordForm, change_username_form=forms.ChangeUsernameForm, forgot_password_form=forms.ForgotPasswordForm, login_form=forms.LoginForm, register_form=forms.RegisterForm, resend_confirm_email_form=forms.ResendConfirmEmailForm, reset_password_form=forms.ResetPasswordForm, invite_form=forms.InviteForm, # Validators username_validator=forms.username_validator, password_validator=forms.password_validator, # View functions change_password_view_function=views.change_password, change_username_view_function=views.change_username, confirm_email_view_function=views.confirm_email, email_action_view_function=views.email_action, forgot_password_view_function=views.forgot_password, login_view_function=views.login, logout_view_function=views.logout, manage_emails_view_function=views.manage_emails, register_view_function=views.register, resend_confirm_email_view_function = views.resend_confirm_email, reset_password_view_function = views.reset_password, unconfirmed_email_view_function = views.unconfirmed, unauthenticated_view_function = views.unauthenticated, unauthorized_view_function = views.unauthorized, user_profile_view_function = views.user_profile, invite_view_function = views.invite, # Misc login_manager=LoginManager(), password_crypt_context=None, send_email_function = emails.send_email, token_manager=tokens.TokenManager(), legacy_check_password_hash=None ): """ Initialize the UserManager object """ self.app = app if db_adapter is not None: self.db_adapter = db_adapter # Forms self.add_email_form = add_email_form self.change_password_form = change_password_form self.change_username_form = change_username_form self.forgot_password_form = forgot_password_form self.login_form = login_form self.register_form = register_form self.resend_confirm_email_form = resend_confirm_email_form self.reset_password_form = reset_password_form self.invite_form = invite_form # Validators self.username_validator = username_validator self.password_validator = password_validator # View functions self.change_password_view_function = change_password_view_function self.change_username_view_function = change_username_view_function self.confirm_email_view_function = confirm_email_view_function self.email_action_view_function = email_action_view_function self.forgot_password_view_function = forgot_password_view_function self.login_view_function = login_view_function self.logout_view_function = logout_view_function self.manage_emails_view_function = manage_emails_view_function self.register_view_function = register_view_function self.resend_confirm_email_view_function = resend_confirm_email_view_function self.reset_password_view_function = reset_password_view_function self.unconfirmed_email_view_function = unconfirmed_email_view_function self.unauthenticated_view_function = unauthenticated_view_function self.unauthorized_view_function = unauthorized_view_function self.user_profile_view_function = user_profile_view_function self.invite_view_function = invite_view_function # Misc self.login_manager = login_manager self.token_manager = token_manager self.password_crypt_context = password_crypt_context self.send_email_function = send_email_function self.legacy_check_password_hash = legacy_check_password_hash """ Initialize app.user_manager.""" # Bind Flask-USER to app app.user_manager = self # Flask seems to also support the current_app.extensions[] list if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['user'] = self # Set defaults for undefined settings settings.set_default_settings(self, app.config) # Make sure the settings are valid -- raise ConfigurationError if not settings.check_settings(self) # Initialize Translations -- Only if Flask-Babel has been installed if hasattr(app.jinja_env, 'install_gettext_callables'): app.jinja_env.install_gettext_callables( lambda x: get_translations().ugettext(x), lambda s, p, n: get_translations().ungettext(s, p, n), newstyle=True) else: app.jinja_env.add_extension('jinja2.ext.i18n') app.jinja_env.install_null_translations() # Create password_crypt_context if needed if not self.password_crypt_context: self.password_crypt_context = CryptContext( schemes=[app.config['USER_PASSWORD_HASH']]) # Setup Flask-Login self.setup_login_manager(app) # Setup TokenManager self.token_manager.setup(app.config.get('SECRET_KEY')) # Add flask_user/templates directory using a Blueprint blueprint = Blueprint('flask_user', 'flask_user', template_folder='templates') app.register_blueprint(blueprint) # Add URL routes self.add_url_routes(app) # Add context processor app.context_processor(_flask_user_context_processor) # Prepare for translations _ = translations.gettext
User utils ''' # Standard Imports # PyPi Imports from passlib.context import CryptContext from sqlalchemy.orm import Session # Local Imports from database import models from data_schemas import schemas ############################################################################### PWD_CONTEXT = CryptContext(schemes=["bcrypt"], deprecated="auto") ############################################################################### def get_user(database: Session, user_id: int): '''Get a specific user by user_id''' return database.query(models.User).filter(models.User.user_id == user_id).first() def get_user_by_email(database: Session, email: str): '''Get a specific user by email address''' return database.query(models.User).filter(models.User.email == email).first() def get_user_by_username(database: Session, username: str): '''Get a specific user by username''' return database.query(models.User).filter(models.User.username == username).first()
# Copyright (C) 2018-2020 Andrew Rechnitzer # Copyright (C) 2020 Dryden Wiebe # Copyright (C) 2020 Vala Vakilian import csv import json from .aliceBob import simple_password, make_random_user_list, make_numbered_user_list # TODO - instead of running a cryptocontext here - move stuff into authenticate.py? # Stuff for hashing and verifying passwords from passlib.hash import pbkdf2_sha256 from passlib.context import CryptContext # These parameters are used for processing and creating the user login info plomctx = CryptContext(schemes=["pbkdf2_sha256", "bcrypt"], deprecated="auto") user_hash_login_json_path = "serverConfiguration/userList.json" list_of_required_users = ["manager", "scanner", "reviewer"] list_of_expected_header = ["user", "password"] minimum_number_of_required_users = 4 cutoff_for_named_users = 20 cutoff_for_numbered_users = 50 def build_canned_users(number_of_users): """Creates a list of fake users. Arguments: number_of_users {int} -- Number of fake users to create. Returns:
def init_app(self, app, user_class, is_blacklisted=None): """ Initializes the Praetorian extension :param: app: The flask app to bind this extension to :param: user_class: The class used to interact with user data :param: is_blacklisted: A method that may optionally be used to check the token against a blacklist when access or refresh is requested Should take the jti for the token to check as a single argument. Returns True if the jti is blacklisted, False otherwise. By default, always returns False. """ PraetorianError.require_condition( app.config.get('SECRET_KEY') is not None, "There must be a SECRET_KEY app config setting set", ) self.hash_autoupdate = app.config.get( 'PRAETORIAN_HASH_AUTOUPDATE', DEFAULT_HASH_AUTOUPDATE, ) self.hash_autotest = app.config.get( 'PRAETORIAN_HASH_AUTOTEST', DEFAULT_HASH_AUTOTEST, ) self.pwd_ctx = CryptContext( schemes=app.config.get('PRAETORIAN_HASH_ALLOWED_SCHEMES', DEFAULT_HASH_ALLOWED_SCHEMES), default=app.config.get('PRAETORIAN_HASH_SCHEME', DEFAULT_HASH_SCHEME), deprecated=app.config.get('PRAETORIAN_HASH_DEPRECATED_SCHEMES', DEFAULT_HASH_DEPRECATED_SCHEMES), ) valid_schemes = self.pwd_ctx.schemes() PraetorianError.require_condition( self.hash_scheme in valid_schemes or self.hash_scheme is None, "If {} is set, it must be one of the following schemes: {}", 'PRAETORIAN_HASH_SCHEME', valid_schemes, ) self.user_class = self._validate_user_class(user_class) self.is_blacklisted = is_blacklisted or (lambda t: False) self.encode_key = app.config['SECRET_KEY'] self.allowed_algorithms = app.config.get( 'JWT_ALLOWED_ALGORITHMS', DEFAULT_JWT_ALLOWED_ALGORITHMS, ) self.encode_algorithm = app.config.get( 'JWT_ALGORITHM', DEFAULT_JWT_ALGORITHM, ) self.access_lifespan = app.config.get( 'JWT_ACCESS_LIFESPAN', DEFAULT_JWT_ACCESS_LIFESPAN, ) self.refresh_lifespan = app.config.get( 'JWT_REFRESH_LIFESPAN', DEFAULT_JWT_REFRESH_LIFESPAN, ) self.reset_lifespan = app.config.get( 'JWT_RESET_LIFESPAN', DEFAULT_JWT_RESET_LIFESPAN, ) self.header_name = app.config.get( 'JWT_HEADER_NAME', DEFAULT_JWT_HEADER_NAME, ) self.header_type = app.config.get( 'JWT_HEADER_TYPE', DEFAULT_JWT_HEADER_TYPE, ) self.header_storage = app.config.get( 'JWT_HEADER_STORAGE', DEFAULT_JWT_HEADER_STORAGE, ) self.user_class_validation_method = app.config.get( 'USER_CLASS_VALIDATION_METHOD', DEFAULT_USER_CLASS_VALIDATION_METHOD, ) self.confirmation_template = app.config.get( 'PRAETORIAN_CONFIRMATION_TEMPLATE', DEFAULT_CONFIRMATION_TEMPLATE, ) self.confirmation_uri = app.config.get('PRAETORIAN_CONFIRMATION_URI', ) self.confirmation_sender = app.config.get( 'PRAETORIAN_CONFIRMATION_SENDER', ) self.confirmation_subject = app.config.get( 'PRAETORIAN_CONFIRMATION_SUBJECT', DEFAULT_CONFIRMATION_SUBJECT, ) self.reset_template = app.config.get( 'PRAETORIAN_RESET_TEMPLATE', DEFAULT_RESET_TEMPLATE, ) self.reset_uri = app.config.get('PRAETORIAN_RESET_URI', ) self.reset_sender = app.config.get('PRAETORIAN_RESET_SENDER', ) self.reset_subject = app.config.get( 'PRAETORIAN_RESET_SUBJECT', DEFAULT_RESET_SUBJECT, ) if isinstance(self.access_lifespan, dict): self.access_lifespan = pendulum.duration(**self.access_lifespan) elif isinstance(self.access_lifespan, str): self.access_lifespan = duration_from_string(self.access_lifespan) ConfigurationError.require_condition( isinstance(self.access_lifespan, datetime.timedelta), "access lifespan was not configured", ) if isinstance(self.refresh_lifespan, dict): self.refresh_lifespan = pendulum.duration(**self.refresh_lifespan) if isinstance(self.refresh_lifespan, str): self.refresh_lifespan = duration_from_string(self.refresh_lifespan) ConfigurationError.require_condition( isinstance(self.refresh_lifespan, datetime.timedelta), "refresh lifespan was not configured", ) if not app.config.get('DISABLE_PRAETORIAN_ERROR_HANDLER'): app.register_error_handler( PraetorianError, PraetorianError.build_error_handler(), ) self.is_testing = app.config.get('TESTING', False) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['praetorian'] = self return app
import posixpath import socketserver from datetime import datetime from http import HTTPStatus from http.cookies import SimpleCookie from http.server import HTTPServer, SimpleHTTPRequestHandler from time import time from urllib.parse import unquote from uuid import uuid4 from passlib.context import CryptContext from backend import errors from backend.db import Channel, Cookie, Message, User context = CryptContext(schemes=["argon2", "bcrypt_sha256", "scrypt"], default="argon2") class Handler(SimpleHTTPRequestHandler): requires_login = ['/chat.html'] def __init__(self, *args, directory: str = None, **kwargs): if directory is None: directory = os.getcwd() self.directory = directory self._cookie = None super().__init__(*args, **kwargs) @property
import ConfigParser import errno import logging import optparse import glob import os import sys import tempfile import odoo from os.path import expandvars, expanduser, abspath, realpath from .. import release, conf, loglevels from . import appdirs from passlib.context import CryptContext crypt_context = CryptContext(schemes=['pbkdf2_sha512', 'plaintext'], deprecated=['plaintext']) class MyOption(optparse.Option, object): """ optparse Option with two additional attributes. The list of command line options (getopt.Option) is used to create the list of the configuration file options. When reading the file, and then reading the command line arguments, we don't want optparse.parse results to override the configuration file values. But if we provide default values to optparse, optparse will return them and we can't know if they were really provided by the user or not. A solution is to not use optparse's default attribute, but use a custom one (that will be copied to create the default values of the configuration file). """
from passlib.context import CryptContext from models.jwt_user import JWTUser from datetime import datetime, timedelta from utils.const import JWT_EXPIRATION_TIME_MINUTES, JWT_SECRET_KEY, JWT_ALGORITHM import jwt import time from fastapi import Depends, HTTPException from fastapi.security import OAuth2PasswordBearer from starlette.status import HTTP_401_UNAUTHORIZED pwd_context = CryptContext(schemes=['bcrypt']) oauth_schema = OAuth2PasswordBearer(tokenUrl='/token') jwt_user1 = { "username": '******', 'password': '******', 'disabled': False, 'role': 'admin' } fake_jwt_user1 = JWTUser(**jwt_user1) def get_hashed_password(password: str): return pwd_context.hash(password) def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) # Authenticate username and password to give JWT token def authenticate_user(user: JWTUser):
import logging from passlib.context import CryptContext import openerp from openerp.osv import fields, osv _logger = logging.getLogger(__name__) default_crypt_context = CryptContext( # kdf which can be verified by the context. The default encryption kdf is # the first of the list ['pbkdf2_sha512', 'md5_crypt'], # deprecated algorithms are still verified as usual, but ``needs_update`` # will indicate that the stored hash should be replaced by a more recent # algorithm. Passlib 1.6 supports an `auto` value which deprecates any # algorithm but the default, but Debian only provides 1.5 so... deprecated=['md5_crypt'], ) class res_users(osv.osv): _inherit = "res.users" def init(self, cr): _logger.info( "Hashing passwords, may be slow for databases with many users...") cr.execute("SELECT id, password FROM res_users" " WHERE password IS NOT NULL" " AND password != ''") for uid, pwd in cr.fetchall():
from passlib.context import CryptContext pwd_context = CryptContext( schemes=["pbkdf2_sha256"], default="pbkdf2_sha256", pbkdf2_sha256__default_rounds=30000, ) def encrypt_password(password): return pwd_context.hash(password) def check_encrypted_password(password, hashed): return pwd_context.verify(password, hashed)
import jwt import jwt.exceptions from passlib.context import CryptContext from sqlalchemy import desc from app.conf.settings import settings from app.constants import Status, TokenType from app.database.base import connection_context from app.database.models import Client, ClientTable, SmsMessage, SmsMessageTable from app.domain.sms.service import SendSmsService from .datamodels import CheckCodeResult, CheckTokenResult, JWTPayload, RefreshTokenResult, SendCodeResult logger = logging.getLogger(__name__) pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") class AuthService: @classmethod def verify_password(cls, plain_password: str, hashed_password: str) -> bool: is_ok: bool = pwd_context.verify(plain_password, hashed_password) return is_ok @classmethod def get_password_hash(cls, password: str) -> str: password_hash: str = pwd_context.hash(password) return password_hash @classmethod
from itertools import chain from flask import Flask, render_template, flash, redirect, url_for, session, request, logging, json from flask_mysqldb import MySQL from flask_mail import Mail, Message from wtforms import Form, StringField, TextAreaField, PasswordField, validators, SelectField, HiddenField from wtforms.fields.html5 import DateTimeLocalField from passlib.context import CryptContext from functools import wraps from wtforms import form from config import config import os cryptcontext = CryptContext(schemes=["sha256_crypt", "md5_crypt", "des_crypt"]) # Schemes for encrypting passwords app = Flask(__name__) # Config MySQL app.config['MYSQL_HOST'] = config.MYSQL_HOST app.config['MYSQL_USER'] = config.MYSQL_USER app.config['MYSQL_PASSWORD'] = config.MYSQL_PASSWORD app.config['MYSQL_DB'] = config.MYSQL_DB app.config['MYSQL_CURSORCLASS'] = config.MYSQL_CURSORCLASS app.secret_key = os.urandom(12).hex() # init MySQL mysql = MySQL(app) # init Mail # Ensure 2 Factor Authentication is off and allow less secure app access mail = Mail(app)