def register_users_from_manifest(user_datastore: SQLAlchemyUserDatastore, manifest: Dict) -> None:
    """Register the users and roles in a manifest.

    :param user_datastore: A user data store
    :param dict manifest: A manifest dictionary, which contains two keys: ``roles`` and ``users``. The ``roles``
     key corresponds to a list of dictionaries containing ``name`` and ``description`` entries. The ``users`` key
     corresponds to a list of dictionaries containing ``email``, ``password``, and ``name`` entries
     as well as a optional ``roles`` entry with a corresponding list relational to the names in the ``roles``
     entry in the manifest.
    """
    for role in manifest['roles']:
        user_datastore.find_or_create_role(**role)

    for user_manifest in manifest['users']:
        email = user_manifest['email']
        user = user_datastore.find_user(email=email)
        if user is None:
            logger.info(f'creating user: {email}')
            user = user_datastore.create_user(
                confirmed_at=datetime.datetime.now(),
                email=email,
                password=user_manifest['password'],
                name=user_manifest['name'],
            )

        for role_name in user_manifest.get('roles', []):
            if user_datastore.add_role_to_user(user, role_name):
                logger.info(f'registered {user} as {role_name}')

    user_datastore.commit()
Example #2
0
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
Example #3
0
def create_roles_users():
    log.info('Insert Role data in database')
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    admin = user_datastore.find_or_create_role(name='Admin',
                                               description='Administrator')
    user_datastore.find_or_create_role(name='api', description='API user')
    user = user_datastore.create_user(email=app.config['ADMIN_EMAIL'],
                                      password=app.config['ADMIN_PASSWORD'])
    user_datastore.add_role_to_user(user, admin)
    db.session.commit()
Example #4
0
    def testCreate(self):

        init_db()
        user_datastore = SQLAlchemyUserDatastore(db_session, User, Role)
        security = Security(app, user_datastore)

        user_datastore.find_or_create_role(name='admin',
                                           description='Administrator')
        user_datastore.find_or_create_role(name='end-user',
                                           description='End user')
        db_session.commit()
def create_admin_user(db, survey, email, password):
    user_datastore = SQLAlchemyUserDatastore(db, WebUser, WebUserRole)
    admin_role = user_datastore.find_or_create_role(name='admin')
    user = user_datastore.create_user(email=email,
                                      password=hash_password(password),
                                      survey_id=survey.id)
    user_datastore.add_role_to_user(user, admin_role)
Example #6
0
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()
Example #7
0
def create_user():
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    # db.drop_all()
    # db.create_all()
    # user_datastore.create_user(username='******', password='******')
    # db.session.commit()
    # print user_datastore.find_user(username='******')
    for permissions, (name, desc) in Permission.PERMISSION_MAP.items():
        user_datastore.find_or_create_role(name=name,
                                           description=desc,
                                           permissions=permissions)
    for username, passwd, permissions in (('xjd', '123', (Permission.LOGIN,
                                                          Permission.EDITOR)),
                                          ('xilixjd', '123',
                                           (Permission.ADMINISTER, ))):
        user = user_datastore.create_user(username=username, password=passwd)
        db.session.commit()
        for permission in permissions:
            user_datastore.add_role_to_user(
                user,
                user_datastore.find_role(
                    role=Permission.PERMISSION_MAP[permission][0]))
            db.session.commit()
Example #8
0
def make_admin(manager, email):
    """Make a pre-existing user an admin."""
    # Example: python3 -m compath make_admin [email protected]

    ds = SQLAlchemyUserDatastore(manager, User, Role)
    user = ds.find_user(email=email)

    if user is None:
        click.echo('User not found')
        sys.exit(0)

    admin = ds.find_or_create_role('admin')

    ds.add_role_to_user(user, admin)
    ds.commit()
    click.echo('User {} is now admin'.format(email))
Example #9
0
    def leave_book(self,book):
        self.book.remove(book)

class Role(RoleMixin, db.Model):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(200),index = True)
    description = db.Column(db.String(250), index = True)

class Book(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(200),index = True)
    author = db.Column(db.String(200),index = True)
    genre = db.Column(db.String(200),index = True)
    synopsis = db.Column(db.String(20000), index = True)
    userNumber = db.Column(db.Integer, index = True)
    user = db.relationship('User', secondary = book_user, lazy = 'select')
    date_borrowed = db.Column(db.DateTime, default = datetime.utcnow)

    def __init__(self,name,author,genre):
        self.name = name
        self.author = author
        self.genre = genre

user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore, register_form = RegisterUser)
user_datastore.find_or_create_role(name='end-user', description='End user')
user_datastore.find_or_create_role(name='admin', description='Administrator')

db.create_all()

Example #10
0
def create_app(config_object=ProductionConfig):
    app = Flask(__name__)
    # Sentry(app, dsn='https://*****:*****@sentry.io/300199')  # noqa

    # CORS(app)
    app.config.from_object(config_object)

    db.init_app(app)
    migrate.init_app(app, db)
    csrf.init_app(app)
    from Mandark.project import models

    userstore = SQLAlchemyUserDatastore(db, models.User, models.Role)
    Security(app, userstore)

    @app.before_request
    def before_request():
        g.user = current_user

    @app.errorhandler(404)
    def not_found_error(e):
        print(e)
        return render_template('404.html', title='FourOhFour')

    @app.errorhandler(500)
    def internal_error():
        return render_template('500.html', title='A server oops happened')

    try:
        with app.app_context():
            userstore.find_or_create_role(name='admin',
                                          description='Administrator')
            userstore.find_or_create_role(name='moderator',
                                          description='Moderator')
            userstore.find_or_create_role(name='projectmgr',
                                          description='Project Manager')
            userstore.find_or_create_role(name='user',
                                          description='General User')
            userstore.create_user(email='*****@*****.**',
                                  password=hash_password('admin'))
            userstore.create_user(email='*****@*****.**',
                                  password=hash_password('user'))
            userstore.create_user(email='*****@*****.**',
                                  password=hash_password('Allanice-001'))
            userstore.add_role_to_user('*****@*****.**', 'admin')
            userstore.add_role_to_user('*****@*****.**', 'user')
            userstore.add_role_to_user('*****@*****.**', 'admin')
            db.session.commit()
            print('IGETHEE')
    except OperationalError:
        if app.debug:
            print(OperationalError)
        else:
            pass
    except Exception as e:
        with app.app_context():
            print(e)
            db.session.rollback()

    from Mandark.project.views import main, admin
    app.register_blueprint(main.main)

    app_admin = Admin(app,
                      'Administration Section',
                      template_mode='bootstrap3',
                      index_view=admin.MyAdminIndexView())
    app_admin.add_view(admin.UserModelView(models.User, db.session))
    app_admin.add_view(admin.RoleModelView(models.Role, db.session))
    app_admin.add_view(admin.ProjectModelView(models.Project, db.session))
    app_admin.add_view(admin.ProjectMgrModelView(models.Projectmgr,
                                                 db.session))
    app_admin.add_view(
        admin.OrganisationModelView(models.Organisation, db.session))
    app_admin.add_view(
        admin.ChangeRequestTypeView(models.ChangeRequestType, db.session))
    app_admin.add_view(
        admin.ChangeRequestSubmitterView(models.ChangeRequestSubmitter,
                                         db.session))
    app_admin.add_link(MenuLink(name='Back to Site', url='/'))

    return app
Example #11
0
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
Example #12
0
    timezone_offset_minutes = IntegerField(default=0)


user_datastore = SQLAlchemyUserDatastore(_db, User, Role)

try:
    _db.create_all()
except OperationalError:
    pass

Migrate(app, _db)
Security(app, user_datastore, register_form=RegisterForm, login_form=LoginForm)

admin_role = 'admin'
user_datastore.find_or_create_role(name=admin_role)

try:
    user_datastore.commit()
except IntegrityError:
    user_datastore.db.session.rollback()


def login_required(func):
    if AppConfig.TESTING:
        return func

    return _login_required(func)


def admin_required(func):
def create_app():
    myapp = Flask(__name__)
    myapp.config['DEBUG'] = True
    myapp.config['SECRET_KEY'] = 'super-secret'
    myapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
    # As of Flask-SQLAlchemy 2.4.0 it is easy to pass in options directly to the
    # underlying engine. This option makes sure that DB connections from the
    # pool are still valid. Important for entire application since
    # many DBaaS options automatically close idle connections.
    myapp.config["SQLALCHEMY_ENGINE_OPTIONS"] = {
        "pool_pre_ping": True,
    }
    myapp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    myapp.config['SECURITY_PASSWORD_SALT'] = 'onetwothreefourfive'

    myapp.config['SECURITY_REGISTERABLE'] = True
    myapp.config['SECURITY_CONFIRMABLE'] = False
    myapp.config['SECURITY_RECOVERABLE'] = True
    myapp.config['SECURITY_TRACKABLE'] = True
    myapp.config['SECURITY_CHANGEABLE'] = True

    myapp.config['MAIL_SERVER']='localhost'
    myapp.config['MAIL_PORT']=8025

    db.init_app(myapp)
    mail.init_app(myapp)
    db_admin.init_app(myapp)

    from app.models import User, Role
    from app.forms import ExtendedRegisterForm
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(myapp, datastore=user_datastore,
         register_form=ExtendedRegisterForm, confirm_register_form=ExtendedRegisterForm)

    from app.main import bp as main_bp
    myapp.register_blueprint(main_bp)

    from app.db_admin import bp as db_admin_bp
    myapp.register_blueprint(db_admin_bp)

# This is junk. This should be in the security blueprint, but the "myapp" variable is not
#   available there, so I had to register it here.
# I thought I could put connect_via(bp), but that didn't work
# Here are some hints for fixing this
# https://stackoverflow.com/questions/16163139/catch-signals-in-flask-blueprint
# https://stackoverflow.com/questions/57866541/how-to-get-user-registered-signal-in-flask-user
# https://stackoverflow.com/questions/17146724/setting-a-default-role-in-flask-security?rq=1

    @user_registered.connect_via(myapp)
    def user_registered_sighandler(app, user, confirm_token):
        default_role = user_datastore.find_role("user")
        user_datastore.add_role_to_user(user, default_role)
        db.session.commit()

    # debug only for testing.
    app_context = myapp.app_context()
    app_context.push()
    db.create_all()
        # Create the Roles "admin" and "end-user" -- unless they already exist
    user_datastore.find_or_create_role(name='admin', description='Administrator')
    user_datastore.find_or_create_role(name='user', description='End user')
    
    user_datastore.create_user(email='*****@*****.**', password='******')
    user_datastore.create_user(email='*****@*****.**', password='******')
    
    db.session.commit()

    # Give one User has the "end-user" role, while the other has the "admin" role. (This will have no effect if the
    # Users already have these Roles.) Again, commit any database changes.
    user_datastore.add_role_to_user('*****@*****.**', 'user')
    user_datastore.add_role_to_user('*****@*****.**', 'admin')
    db.session.commit()

    return myapp
Example #14
0
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
CSRFProtect(app)

# set up the database model if not already set up
from app import models
db.create_all()
db.session.commit()

# setup the User/Role tables with flask-security, create base users/groups if neccessary
userstore = SQLAlchemyUserDatastore(db, models.User, models.Role)
sec = Security(app, userstore)
try:
    with app.app_context():
        userstore.find_or_create_role(name='admin', description='Administrator')
        userstore.find_or_create_role(name='user', description='General user')
        userstore.create_user(email=FIRST_USER_NAME,
                            password=utils.encrypt_password(FIRST_USER_PASS))
        userstore.add_role_to_user(FIRST_USER_NAME, 'admin')
        db.session.commit()
except: db.session.rollback()

# get the view controllers for the app
from app.views import main, admin, common

# set up main as a blueprint, add as many blueprints as necessary
app.register_blueprint(main.main)

# configure the admin interface, populate it with pages and links
app_admin = Admin(app, 'Flask Skeleton Admin', template_mode='bootstrap3', index_view=admin.AdminIndexView())
Example #15
0
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
CsrfProtect(app)

# set up the database model if not already set up
from app import models
db.create_all()
db.session.commit()

# setup the User/Role tables with flask-security, create base users/groups if neccessary
userstore = SQLAlchemyUserDatastore(db, models.User, models.Role)
sec = Security(app, userstore)
try:
    with app.app_context():
        userstore.find_or_create_role(name='admin', description='Administrator')
        userstore.find_or_create_role(name='user', description='General user')
        userstore.create_user(email=FIRST_USER_NAME,
                            password=utils.encrypt_password(FIRST_USER_PASS))
        userstore.add_role_to_user('admin', 'admin')
        db.session.commit()
except: db.session.rollback()

# get the view controllers for the app
from app.views import main, admin, common

# set up main as a blueprint, add as many blueprints as necessary
app.register_blueprint(main.main)

# configure the admin interface, populate it with pages and links
app_admin = Admin(app, 'Flask Skeleton Admin', template_mode='bootstrap3', index_view=admin.AdminIndexView())
Example #16
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(os.environ['APP_SETTINGS'])
    db.init_app(app)
    db.app = app

    # hook up mail
    mail = Mail(app)

    try:
        # initialize data store and setup roles, security
        # this will fail if the db does not exist ...
        user_datastore = SQLAlchemyUserDatastore(db, User, Role)
        user_datastore.find_or_create_role(name='admin',
                                           description='Administrator')
        user_datastore.find_or_create_role(name='client', description='Client')
        user_datastore.commit()
        security = Security(app, user_datastore)
    except:
        pass

    with app.app_context():
        # Create admin
        if admin.app is None:
            admin.init_app(app)

        app.config['FLASK_ADMIN_SWATCH'] = 'cosmo'

        admin.add_view(UserAdmin(User, db.session))
        admin.add_view(RoleAdmin(Role, db.session))
        admin.add_view(BaseAdmin(Company, db.session))
        admin.add_view(BaseAdmin(UserRequest, db.session))
        admin.add_view(BaseAdmin(Project, db.session))
        admin.add_view(BaseAdmin(ServiceAgreement, db.session))

        # Initialize the plugin manager
        plugin_manager = PluginManager(app)
        plugins = get_enabled_plugins()

        if test_config is None:
            # load the instance config, if it exists, when not testing
            app.config.from_pyfile('config.py', silent=True)
        else:
            # load the test config if passed in
            app.config.from_mapping(test_config)

        # ensure the instance folder exists
        try:
            os.makedirs(app.instance_path)
        except OSError:
            pass

        app.register_blueprint(user_bp)
        app.register_blueprint(company_bp)
        app.register_blueprint(request_bp)
        app.register_blueprint(project_bp)

        # internal version
        @app.route('/version')
        def version():
            return app_version

        # index
        @app.route("/")
        def index():
            return render_template("index.html")

        @app.route("/plugins")
        @login_required
        def plugins():
            return render_template("plugins.html",
                                   plugins=get_enabled_plugins())

        @app.route("/disable/<plugin>")
        def disable(plugin):
            plugin = get_plugin(plugin)
            plugin_manager.disable_plugins([plugin])
            return redirect(url_for("index"))

        @app.route("/enable/<plugin>")
        def enable(plugin):
            plugin = get_plugin(plugin)
            plugin_manager.enable_plugins([plugin])
            return redirect(url_for("index"))

    return app
Example #17
0
def before_first_request():
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    user_datastore.find_or_create_role(name='admin',
                                       description='Administrator')
    user_datastore.find_or_create_role(name='end-user', description='End user')
    db.session.commit()
Example #18
0
    timezone_offset_minutes = IntegerField(default=0)


user_datastore = SQLAlchemyUserDatastore(_db, User, Role)

try:
    _db.create_all()
except OperationalError:
    pass

Migrate(app, _db)
Security(app, user_datastore, register_form=RegisterForm, login_form=LoginForm)

admin_role = 'admin'
user_datastore.find_or_create_role(name=admin_role)

try:
    user_datastore.commit()
except IntegrityError:
    user_datastore.db.session.rollback()


def login_required(func):
    if AppConfig.TESTING:
        return func

    return _login_required(func)


def admin_required(func):