Setup flask-user manager.
494859
def setup_user_manager(app):
    """"""

    from flask_user import SQLAlchemyAdapter

    from rio.models import User

    init = dict(
        db_adapter=SQLAlchemyAdapter(db, User),
    )
    user_manager.init_app(app, **init)
1010675
def run(self):
        
        from zengine.models import User
        user = User(username=self.manager.args.username, superuser=self.manager.args.super)
        user.set_password(self.manager.args.password)
        user.save()
        print("New user created with ID: %s" % user.key)
751067
def manager(self):
        """"""
        from flask_script import Manager, Command

        manager = Manager(usage="Migrate database.")
        manager.add_command('create', Command(self.cmd_create))
        manager.add_command('migrate', Command(self.cmd_migrate))
        manager.add_command('rollback', Command(self.cmd_rollback))
        manager.add_command('list', Command(self.cmd_list))
        manager.add_command('merge', Command(self.cmd_merge))

        return manager
887015
def setup(self, app):
        """"""
        super().setup(app)

        if self.cfg.secret == 'InsecureSecret':
            app.logger.warning(
                'Use insecure secret key. Change SESSION_SECRET option in configuration.')

        self._user_loader = asyncio.coroutine(lambda id_: id_)  # noqa

        app.on_response_prepare.append(self.save)

        if self.cfg.auto_load:
            app.middlewares.append(self._middleware)
828218
def setup(app):
    """"""
    app.add_config_value(
        'site_url',
        default=None,
        rebuild=False
    )
    try:
        app.add_config_value(
            'html_baseurl',
            default=None,
            rebuild=False
        )
    except:
        pass

    app.connect('html-page-context', add_html_link)
    app.connect('build-finished', create_sitemap)
    app.sitemap_links = []
    app.locales = []
948485
def setup_users_page(self, ):
        
        self.users_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
        log.debug("Loading users for users page.")
        rootdata = treemodel.ListItemData(['Username', 'First', 'Last', 'Email'])
        rootitem = treemodel.TreeItem(rootdata)
        users = djadapter.users.all()
        for usr in users:
            usrdata = djitemdata.UserItemData(usr)
            treemodel.TreeItem(usrdata, rootitem)
        self.users_model = treemodel.TreeModel(rootitem)
        self.users_tablev.setModel(self.users_model)
557137
def bind(self, flask_app):
        """"""
        self.metadata.bind(flask_app, self.name, self.group)
1275848
def create_app():
    

    # Setup Flask app and app.config
    app = Flask(__name__)
    app.config.from_object(__name__ + '.ConfigClass')

    # Initialize Flask extensions
    db = None
    mail = Mail(app)  # Initialize Flask-Mail

    # Define the User data model. Make sure to add flask_user UserMixin !!!
    class UsernameIndex(GlobalSecondaryIndex):
        class Meta:
            read_capacity_units = 1
            write_capacity_units = 1
            projection = AllProjection()

        username = UnicodeAttribute(hash_key=True)

    class EmailIndex(GlobalSecondaryIndex):
        class Meta:
            read_capacity_units = 1
            write_capacity_units = 1
            projection = AllProjection()

        email = UnicodeAttribute(hash_key=True)

    class User(Model, UserMixin):
        class Meta:
            table_name = 'users'

        id = UnicodeAttribute(hash_key=True, default=lambda: str(uuid.uuid1()))
        active = BooleanAttribute()

        # User authentication information
        username = UnicodeAttribute(null=True)
        password = UnicodeAttribute(null=True)

        username_index = UsernameIndex()

        # User email information
        email = UnicodeAttribute(null=True)
        email_confirmed_at = UTCDateTimeAttribute(null=True)

        email_index = EmailIndex()

        # User information
        first_name = UnicodeAttribute(null=True)
        last_name = UnicodeAttribute(null=True)


    # Setup Flask-User
    user_manager = UserManager(app, db, User)

    # Create all database tables
    print('create_schema()')
    user_manager.db_manager.create_all_tables()
    print('created_schema()')

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% block content %}
                <h2>Home page</h2>
                <p>This page can be accessed by anyone.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('members_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    # The Members page is only accessible to authenticated users
    @app.route('/members')
    @login_required  # Use of @login_required decorator
    def members_page():
        return render_template_string("""
            {% block content %}
                <h2>Members page</h2>
                <p>This page can only be accessed by authenticated users.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('members_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    return app
782968
def create_login_manager(self, app) -> LoginManager:
        
        lm = LoginManager(app)
        lm.login_view = "login"
        lm.user_loader(self.load_user)
        return lm
228456
public static void setUpUsers() {
        LOG.info("SETTING UP THE USERS TO BE USED ");
        adminUser = userProps.getProperty("adminUsername");
        adminUserPassword = userProps.getProperty("adminPassword");
        LOG.info("COMPLETED USER SETUP ");
    }
863223
def update_user(self, user, name=None, password=None, host=None):
        
        return self._user_manager.update(user, name=name, password=password,
                host=host)
398562
protected function setup()
    {
        // Check if a valid access token exists.
        if (!$this->accessToken || $this->accessToken->expired()) {
            // Refresh is successful unless explicitly set to false.
            $refreshSuccess = true;

            // Check if a valid refresh token exists.
            if ($this->refreshToken && $this->refreshToken->getToken()) {
                // Attempt to use the refresh token.
                try {
                    $this->refresh();
                } catch (RequestException $e) {
                    // Check if the exception is due to an HTTP 403.
                    if ($e->getCode() == 403) {
                        $response = $e->getResponse();
                        $json = json_decode($response->getBody());
                        $body = $json->{'nl.divide.iq'};

                        // Check if the error is indeed a "TokenExpired" error,
                        // as expected.
                        if ($body->answer == 'TokenExpired') {
                            // Token is expired; refreshing unsuccessful.
                            $refreshSuccess = false;
                        } else {
                            // Unexpected error. Pass it up the stack. This
                            // might be a "TokenEmpty" error, but that would
                            // still be unexpected, because the token value was
                            // checked beforehand.
                            throw $e;
                        }
                    } else {
                        // Unexpected error. Pass it up the stack.
                        throw $e;
                    }
                }
            } else {
                // There is no refresh token to use; refreshing unsuccessful.
                $refreshSuccess = false;
            }

            // If refreshing failed, login from scratch and then authenticate.
            if (!$refreshSuccess) {
                $this->login()->authenticate();
            }
        }

        // Request the settings if needed.
        if (!$this->settings) {
            $response = $this->client->get('settings', [
                'headers' => ['Authentication' => $this->accessToken->getToken()],
            ]);

            $json = json_decode($response->getBody());
            $body = $json->{'nl.divide.iq'};
            $services = [];
            foreach ($body->services as $service) {
                $services[] = $service->code;
            }

            // Create new settings object.
            $this->settings = new Settings($services, $body->settings_updated);
        }
    }
817344
def user(username, password, all):
    """"""
    if current_app.config['AUTH_PROVIDER'] != 'basic':
        raise click.UsageError('Not required for {} admin users'.format(current_app.config['AUTH_PROVIDER']))
    if username and username not in current_app.config['ADMIN_USERS']:
        raise click.UsageError('User {} not an admin'.format(username))
    if not username and not all:
        raise click.UsageError('Missing option "--username".')

    def create_user(admin):
        email = admin if '@' in admin else None
        user = User(
            name='Admin user',
            login=admin,
            password=generate_password_hash(password),
            roles=['admin'],
            text='Created by alertad script',
            email=email,
            email_verified=bool(email)
        )
        try:
            db.get_db()  # init db on global app context
            user = user.create()
        except Exception as e:
            click.echo('ERROR: {}'.format(e))
        else:
            click.echo('{} {}'.format(user.id, user.name))

    if all:
        for admin in current_app.config['ADMIN_USERS']:
            create_user(admin)
    else:
        create_user(username)
866587
def setup(self, app):
        """"""
        super(Plugin, self).setup(app)

        if 'jinja2' not in app.plugins:
            raise PluginException('The plugin requires Muffin-Jinja2 plugin installed.')

        self.cfg.prefix = self.cfg.prefix.rstrip('/') + '/'
        self.cfg.exclude.append(self.cfg.prefix)

        # Setup debugtoolbar templates
        app.ps.jinja2.cfg.template_folders.append(op.join(PLUGIN_ROOT, 'templates'))

        self.cfg.panels += list(self.cfg.additional_panels)
        panels_ = []
        for panel in self.cfg.panels:
            if isinstance(panel, str):
                mod, _, panel = panel.partition(':')
                mod = importlib.import_module(mod)
                panel = eval(panel or 'DebugPanel', mod.__dict__)
            panels_.append(panel)
        self.cfg.panels = panels_

        # Setup debugtoolbar static files
        app.router.register_route(StaticRoute(
            'debugtoolbar.static',
            self.cfg.prefix + 'static/',
            op.join(PLUGIN_ROOT, 'static')))

        app.register(self.cfg.prefix + 'sse', name='debugtoolbar.sse')(self.sse)
        app.register(
            self.cfg.prefix + 'exception', name='debugtoolbar.exception')(self.exception)
        app.register(
            self.cfg.prefix + 'execute', name='debugtoolbar.execute')(self.execute)
        app.register(
            self.cfg.prefix + 'source', name='debugtoolbar.source')(self.source)
        app.register(
            self.cfg.prefix.rstrip('/'),
            self.cfg.prefix,
            self.cfg.prefix + '{request_id}', name='debugtoolbar.request')(self.view)

        app['debugtoolbar'] = {}
        app['debugtoolbar']['pdbt_token'] = uuid.uuid4().hex
        self.history = app['debugtoolbar']['history'] = utils.History(50)
        self.exceptions = app['debugtoolbar']['exceptions'] = utils.History(50)
        self.frames = app['debugtoolbar']['frames'] = utils.History(100)
84273
def grant_user_access(self, db_names, strict=True):
        
        return self.manager.grant_user_access(self, db_names, strict=strict)
753113
def setup(self, environ):
        ''''''
        json_handler = Root().putSubHandler('calc', Calculator())
        middleware = wsgi.Router('/', post=json_handler,
                                 accept_content_types=JSON_CONTENT_TYPES)
        response = [wsgi.GZipMiddleware(200)]
        return wsgi.WsgiHandler(middleware=[wsgi.wait_for_body_middleware,
                                            middleware],
                                response_middleware=response)
1337158
def cli(env, identifier):
    """"""

    mgr = SoftLayer.UserManager(env.client)
    user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
    object_mask = "mask[id, permissions, isMasterUserFlag, roles]"

    user = mgr.get_user(user_id, object_mask)
    all_permissions = mgr.get_all_permissions()
    user_permissions = perms_to_dict(user['permissions'])

    if user['isMasterUserFlag']:
        click.secho('This account is the Master User and has all permissions enabled', fg='green')

    env.fout(roles_table(user))
    env.fout(permission_table(user_permissions, all_permissions))