def create_init_user(user_datastore: SQLAlchemyUserDatastore) -> None: """ TODO in doc: 在这里创建初始的角色和管理用户。 """ user_datastore.find_or_create_role(name='root', description='系统管理员') user_datastore.find_or_create_role(name='admin', description='管理员') user_datastore.find_or_create_role(name='user', description='用户') if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user( email='*****@*****.**', password=security_utils.encrypt_password('default_password')) # TODO in doc: # 如果还需要更多的初始用户,在这里创建 db.session.commit() # 在给用户分配角色前,必须commit这个User对象 user_datastore.add_role_to_user('*****@*****.**', 'root') # TODO in doc: # 在这里分配其他角色给初始用户 db.session.commit()
def create_app(config=Config): app = Flask(__name__, template_folder='../templates', static_folder='../static') app.config.from_object(config) config.init_app(app) mail.init_app(app) db.init_app(app) admin.init_app(app) pagedown.init_app(app) migrate.init_app(app, db) user_datastore = SQLAlchemyUserDatastore(db, User, Role) Security(app, datastore=user_datastore, login_form=ExtendedLoginForm) with app.test_request_context(): db.create_all() user_datastore.find_or_create_role(name='admin', description='Administrator') if not user_datastore.get_user(app.config['ADMIN_EMAIL']): user_datastore.create_user(email=app.config['ADMIN_EMAIL'], password=app.config['ADMIN_PASSWORD']) db.session.commit() user_datastore.add_role_to_user(app.config['ADMIN_EMAIL'], 'admin') db.session.commit() return app
def create_user(email: str, password: str): datastore = SQLAlchemyUserDatastore(db, User, Role) if not datastore.get_user(email): datastore.create_user(email=email, password=hash_password(password)) db.session.commit() return jsonify( User.query.filter(User.email == email).first().to_dict()) return jsonify(User.query.filter(User.email == email).first().to_dict())
def add_user(): user = User.query.order_by(User.id.desc()).first() user_datastore = SQLAlchemyUserDatastore(db, User, Role) if request.method == 'POST': if 'email' in request.form: email = request.form.get('email') if 'password' in request.form: password = request.form.get('password') if 'name' in request.form: name = request.form.get('name') if 'firstname' in request.form: firstname = request.form.get('firstname') if 'phone' in request.form: phone = request.form.get('phone') if 'signing' in request.files: filename = str(user.id + 1) + '.jpg' signing = request.files.get('signing') path = f"APPLICATION/{admin.app['MODULES_FOLDER']}/{'admin'}/{'signing'}" pathlib.Path(path).mkdir(parents=True, exist_ok=True) try: signing.save(os.path.join(path, filename)) except PermissionError: admin.log.error( "Permission Error to create / save file to uploads folder") exists = db.session.query( db.exists().where(User.email == email)).scalar() if exists: flash("Utilisateur existe déja", "error") return redirect(url_for('admin.index')) encrypted_password = utils.hash_password(password) if not user_datastore.get_user(email): user_datastore.create_user(email=email, password=encrypted_password, last_name=name, first_name=firstname, phone=phone, signing=filename) try: db.session.commit() except OperationalError: admin.logger.error("Operational Error permission access database") user_datastore.add_role_to_user(email, 'user') # set Role to the new User try: db.session.commit() except OperationalError: admin.logger.error("Operational Error permission access database") flash("Utilisateur créer", "success") return redirect(url_for('admin.index'))
def setup(app): """ Setup Flask Security :param app: The Flask Application Object :return: None """ user_datastore = SQLAlchemyUserDatastore(db, User, Role) security.init_app(app, user_datastore) if app.config["DEBUG"]: if not user_datastore.get_user('*****@*****.**'): user_datastore.create_user(email='*****@*****.**', password=hash_password('signmeup')) db.session.commit()
def test_uuid(app, request, tmpdir, realdburl): """ Test that UUID extension of postgresql works as a primary id for users """ import uuid from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Boolean, Column, DateTime, Integer, ForeignKey, String from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import relationship, backref from flask_security import SQLAlchemyUserDatastore from conftest import _setup_realdb, _teardown_realdb # UUID type only supported by postgres - not sqlite. if not realdburl or "postgres" not in realdburl: skip("This test only works on postgres") db_url, db_info = _setup_realdb(realdburl) app.config["SQLALCHEMY_DATABASE_URI"] = db_url db = SQLAlchemy(app) class RolesUsers(db.Model): __tablename__ = "roles_users" id = Column(Integer(), primary_key=True) user_id = Column("user_id", UUID(as_uuid=True), ForeignKey("user.id")) role_id = Column("role_id", UUID(as_uuid=True), ForeignKey("role.id")) class User(db.Model, UserMixin): __tablename__ = "user" id = Column( UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, index=True ) email = Column(String(255), unique=True) first_name = Column(String(255), index=True) last_name = Column(String(255), index=True) username = Column(String(255), unique=True) password = Column(String(255)) active = Column(Boolean()) created_at = Column(DateTime, default=datetime.datetime.utcnow) confirmed_at = Column(DateTime()) roles = relationship( "Role", secondary="roles_users", backref=backref("users", lazy="dynamic") ) class Role(db.Model, RoleMixin): __tablename__ = "role" id = Column( UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, index=True ) name = Column(String(80), unique=True) description = Column(String(255)) # __hash__ is required to avoid the exception # TypeError: unhashable type: 'Role' when saving a User def __hash__(self): return hash(self.name) with app.app_context(): db.create_all() def tear_down(): db.drop_all() _teardown_realdb(db_info) request.addfinalizer(tear_down) ds = SQLAlchemyUserDatastore(db, User, Role) app.security = Security(app, datastore=ds) with app.app_context(): user = ds.get_user("*****@*****.**") assert not user
def init_db(app): """ # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() Initializes database and creates the tables """ from app.models import db, Role, AdminLogin, Project from flask_security import Security, SQLAlchemyUserDatastore from flask_migrate import Migrate db.init_app(app) app.app_context().push() # Initialize the SQLAlchemy data store and Flask-Security user_datastore = SQLAlchemyUserDatastore(db, AdminLogin, Role) security_bp = Security(app, user_datastore) # Initialize Flask-Migrate migrate = Migrate(app, db) # db.drop_all() # drops tables, won't drop functions or anything else # db.create_all() """ only run configure_mappers() and create_all() once, because create_all() will throw an error that the tsvector functions already exist. With tables, create_all() can recognize they already exist and then not create them again, but with functions it struggles and will try to create the functions that already exist in the database. """ # db.configure_mappers() # need this to enable TsVector triggers # db.create_all() # # insert dummy data # from app.dummy_data import insert_dummy_data # insert_dummy_data(db) # Create a default superuser that has all permissions user_datastore.find_or_create_role(name="superuser_admins", table_name='admins', can_read=True, can_edit=True, can_create=True, can_delete=True) user_datastore.find_or_create_role(name="superuser_roles", table_name='roles', can_read=True, can_edit=True, can_create=True, can_delete=True) user_datastore.find_or_create_role(name="superuser_advisorapplicants", table_name='advisorapplicants', can_read=True, can_edit=True, can_create=True, can_delete=True) user_datastore.find_or_create_role(name="superuser_advisors", table_name='advisors', can_read=True, can_edit=True, can_create=True, can_delete=True) user_datastore.find_or_create_role(name="superuser_projects", table_name='projects', can_read=True, can_edit=True, can_create=True, can_delete=True) user_datastore.find_or_create_role(name="superuser_specialties", table_name='specialties', can_read=True, can_edit=True, can_create=True, can_delete=True) user_datastore.find_or_create_role(name="superuser_subspecialties", table_name='subspecialties', can_read=True, can_edit=True, can_create=True, can_delete=True) user_datastore.find_or_create_role(name="superuser_bigfirms", table_name='bigfirms', can_read=True, can_edit=True, can_create=True, can_delete=True) user_datastore.find_or_create_role(name="superuser_occupations", table_name='occupations', can_read=True, can_edit=True, can_create=True, can_delete=True) user_datastore.find_or_create_role(name="superuser_occupationtypes", table_name='occupationtypes', can_read=True, can_edit=True, can_create=True, can_delete=True) user_datastore.find_or_create_role(name="can_edit_advisorapplicants") user_datastore.find_or_create_role(name="can_create_advisors", ) if not user_datastore.get_user(app.config['SUPERUSER_ADMIN_EMAIL']): user_datastore.create_user(email=app.config['SUPERUSER_ADMIN_EMAIL'], password=app.config['SUPERUSER_ADMIN_PASSWORD'], active=True, analytics_access=True, database_access=True) db.session.commit() user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "superuser_admins") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "superuser_roles") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "superuser_advisorapplicants") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "superuser_advisors") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "superuser_projects") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "superuser_specialties") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "superuser_subspecialties") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "superuser_bigfirms") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "superuser_occupations") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "superuser_occupationtypes") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "can_edit_advisorapplicants") user_datastore.add_role_to_user(app.config['SUPERUSER_ADMIN_EMAIL'], "can_create_advisors") db.session.commit() db.session.close() return security_bp
from app import Collection, Item, User, Role, app from sqlalchemy import create_engine from flask_security import SQLAlchemyUserDatastore import csv from glob import glob from os.path import basename from config import ADMIN_PASSWORD engine = create_engine('sqlite:///app.sqlite', echo=True) db = flask_sqlalchemy.SQLAlchemy(app) db.create_all() user_datastore = SQLAlchemyUserDatastore(db, User, Role) #Create user with app.app_context(): admin = user_datastore.get_user('admin') if not admin: admin = user_datastore.create_user(email='admin', password=ADMIN_PASSWORD) db.session.commit() #Loop collections for collection in glob('../scripts/output/*.tsv'): with open(f'../scripts/{collection}') as f: collection_name = basename(collection).split('.')[0].replace( '_', ' ').title() if db.session.query(Collection).filter_by( user=admin, name=collection_name).first(): print(f"{collection_name} exists") continue # exists already print(collection_name) #If new collection, add it to the database c = Collection(name=collection_name, user_id=admin.id, public=True)
def get_user(self, identifier): return _wrap_user(SQLAlchemyUserDatastore.get_user(self, identifier))