Example #1
1
def unauthorized_redirect(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.setup_app(app)
    res = lm.unauthorized()
    assert res.headers["Location"] == "/login?next=%2F"
    assert LOGIN_MESSAGE in get_flashed_messages()
Example #2
0
def setup_login_manager(app):
    """ setup_login_manager::flask.Flask->None

        Creates a login manager object and attaches an application
        object to it.

        Also sets up the login view function to redirect to, and
        the user_loader function.

    """

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'facebook.login'
    login_manager.login_message_category = 'warning'

    @login_manager.user_loader
    def load_user(user_id):
        try:
            # we need a request context for a valid db connection
            with current_app.test_request_context('/'):
                db = g.db
                user = db.session.query(User).filter(User.UUID == user_id).one()
                return user
        except NoResultFound as e:
            current_app.logger.debug(e)
            return None
Example #3
0
class LoginInSessionTestCase(unittest.TestCase):
    ''' Tests for login_user_in_session function '''

    def setUp(self):
        self.app = Flask(__name__)
        self.app.config['SECRET_KEY'] = 'deterministic'
        self.login_manager = LoginManager()
        self.login_manager.init_app(self.app)

        unittest.TestCase.setUp(self)

    def test_login_user_in_session(self):
        with self.app.test_request_context():
            session = {}
            login_user_in_session(session, notch)
            self.assertTrue('user_id' in session)
            self.assertTrue('_fresh' in session)
            self.assertTrue('_id' in session)
            self.assertTrue('remember' not in session)

    def test_login_user_in_session_remember(self):
        with self.app.test_request_context():
            session = {}
            login_user_in_session(session, notch, remember=True)
            self.assertTrue('user_id' in session)
            self.assertTrue('_fresh' in session)
            self.assertTrue('_id' in session)
            self.assertTrue(session['remember'])
Example #4
0
File: run.py Project: DianQ/MyCode
def configure_login(app):
    lm = LoginManager()
    lm.setup_app(app)

    @lm.user_loader
    def load_user(userid):
        return UserDAO.get(userid)
Example #5
0
def init_login(app):
    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        return User.objects(id=user_id).first()
Example #6
0
def create_app():
    global app
    global db
    global login_manager

    # Flask
    app = Flask(__name__)
    app.config.from_object('config.flask_config')

    # SQLAlchemy
    db = SQLAlchemy(app)

    # Login
    login_manager = LoginManager(app)
    login_manager.login_view = 'users.login'

    # Assets
    assets = Environment(app)
    less = Bundle('less/*.less',
                  filters='less',
                  output='css/gen/style.css',
                  depends='less/*.less')
    assets.register('less_all', less)

    # Debug
    app.config['DEBUG'] = (len(argv) == 2 and argv[1] == 'debug')

    @login_manager.user_loader
    def load_user(userid):
        from models import User
        return User.query.get(userid)

    register_blueprints(app)
    return app, db
Example #7
0
def create_app(config_filename=None):
    app = Flask(__name__)
    app.config.from_pyfile(config_filename or 'config.py')
    if 'CERTIFICATOR_SETTINGS' in os.environ:
        # Only try to load a config from it if set.
        app.config.from_envvar('CERTIFICATOR_SETTINGS')

    from .db import get_user_by_id, get_user
    login_manager = LoginManager()
    login_manager.user_loader(get_user_by_id)
    login_manager.init_app(app)

    browser_id = BrowserID()
    browser_id.user_loader(get_user)
    browser_id.init_app(app)

    Bootstrap(app)

    from .db import db as sqla
    sqla.init_app(app)
    sqla.app = app

    sqla.create_all()

    import stripe
    stripe.api_key = app.config['STRIPE_SECRET_KEY']

    from .views import root, quiz, dashboard, certificate
    app.register_blueprint(root)
    app.register_blueprint(quiz)
    app.register_blueprint(dashboard)
    app.register_blueprint(certificate)

    return app
Example #8
0
def create_app():
    global db

    app = Flask(__name__)

    app.config.from_object(wemedia.settings)

    db = DB(app)

    setup_blueprints(app)
    setup_logger(app)

    # 登录管理器
    login_manager = LoginManager()
    login_manager.setup_app(app)
    login_manager.login_view = 'Common.login'
    login_manager.login_message = u'请登录'

    @login_manager.user_loader
    def load_user(userid):
        from wemedia.common.models import User

        user = User.query.get(userid)

        return user

    return app
Example #9
0
class MethodViewLoginTestCase(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.login_manager = LoginManager()
        self.login_manager.init_app(self.app)
        self.login_manager._login_disabled = False

        class SecretEndpoint(MethodView):
            decorators = [
                login_required,
                fresh_login_required,
            ]

            def options(self):
                return u''

            def get(self):
                return u''

        self.app.add_url_rule('/secret',
                              view_func=SecretEndpoint.as_view('secret'))

    def test_options_call_exempt(self):
        with self.app.test_client() as c:
            result = c.open('/secret', method='OPTIONS')
            self.assertEqual(result.status_code, 200)
Example #10
0
def init_login():
    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        return db.session.query(User).get(user_id)
Example #11
0
def setup_app(app):
    """Setup login extension."""

    app.config.setdefault('CFG_OPENID_AUTHENTICATION', False)
    app.config.setdefault('CFG_OAUTH1_AUTHENTICATION', False)
    app.config.setdefault('CFG_OAUTH2_AUTHENTICATION', False)

    @app.errorhandler(401)
    def do_login_first(error=401):
        """Displays login page when user is not authorised."""
        if request.is_xhr:
            return g._("Authorization failure"), 401
        if current_user.is_guest:
            flash(g._("Please sign in to continue."), 'info')
        else:
            flash(g._("Authorization failure."), 'danger')
        from invenio.modules.accounts.views.accounts import login
        return login(referer=request.url), 401

    # Let's create login manager.
    _login_manager = LoginManager(app)
    _login_manager.login_view = app.config.get('CFG_LOGIN_VIEW',
                                               'webaccount.login')
    _login_manager.anonymous_user = UserInfo
    _login_manager.unauthorized_handler(do_login_first)

    @_login_manager.user_loader
    def _load_user(uid):
        """
        Function should not raise an exception if uid is not valid
        or User was not found in database.
        """
        return UserInfo(int(uid))

    return app
Example #12
0
def init_app():
    app = Flask(__name__, static_url_path="/static")
    env = Environment(loader=FileSystemLoader("templates/"))

    app.config.from_object("FLASKCONFIG")

    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(id):
        return User(int(id))

    app.register_blueprint(auth_blueprint, url_prefix="")
    app.register_blueprint(api_blueprint, url_prefix="/api/")

    @app.route("/t/<int:id>", methods=["GET"])
    @app.route("/register", methods=["GET"])
    @app.route("/login", methods=["GET"])
    @app.route("/create", methods=["GET"])
    @app.route("/", methods=["GET"])
    def index(id=0):
        return render_template("index.html")

    return app
Example #13
0
def create_app():
    global app
    global db
    global login_manager

    # Flask
    app = Flask(__name__,
                static_folder='static/dist/',
                static_url_path='/static')
    app.config.from_object('config.flask_config')

    # SQLAlchemy
    db = SQLAlchemy(app)

    # Login
    login_manager = LoginManager(app)
    login_manager.login_view = 'users.login'

    # Debug
    app.config['DEBUG'] = (len(argv) == 2 and argv[1] == 'debug')

    @login_manager.user_loader
    def load_user(userid):
        from models import User
        return User.query.get(userid)

    from app.models import AnonymousUser
    login_manager.anonymous_user = AnonymousUser

    register_blueprints(app)
    return app, db
Example #14
0
class CApp(flask.Flask):
    """
    Main Crossco app. Made singleton to force one instance per server.
    """
    __metaclass__ = Singleton
    def __init__(self, import_name='', static_path=None, static_url_path=None,
                 static_folder='static', template_folder='templates',
                 instance_path=None, instance_relative_config=False):
        flask.Flask.__init__(self, import_name,
                                     static_path=static_path,
                                     static_url_path=static_url_path,
                                     static_folder=static_folder,
                                     template_folder=template_folder,
                                     instance_path=instance_path,
                                     instance_relative_config=instance_relative_config
                                     )
        self.config.update(config)
        self.db = flask.ext.sqlalchemy.SQLAlchemy(self)
        self.fb = OAuth().remote_app('facebook',
                base_url='https://graph.facebook.com/',
                request_token_url=None,
                access_token_url='/oauth/access_token',
                authorize_url='https://www.facebook.com/dialog/oauth',
                consumer_key=self.config['FACEBOOK_APP_ID'],
                consumer_secret=self.config['FACEBOOK_APP_SECRET'],
                request_token_params={'scope': 'email,manage_pages'})
        self.api_manager = APIManager(self, flask_sqlalchemy_db=self.db)
        self.login_manager = LoginManager()
        self.login_manager.setup_app(self)

    def run(self, host=None, port=None, debug=None, **options):
        self.db.create_all()
        flask.Flask.run(self, host, port, debug, **options)
Example #15
0
def app_factory(config):
    # create app
    app = Flask(__name__)
    app.config.from_object(config)

    # database
    db.init_app(app)
    whoosh_index(app, Post)

    # flask-login
    login_manager = LoginManager(app)
    login_manager.user_loader(load_user)

    # flask-wtf csrf protection
    CsrfProtect(app)

    # jinja2 config
    jinja.init_app(app)

    # blueprints
    from blog import blog
    app.register_blueprint(blog)

    from api import api
    app.register_blueprint(api, url_prefix='/api')

    return app
Example #16
0
class AuthenticationModule(SystemModule):
    def __init__(self, *args, **kwargs):
        super(AuthenticationModule, self).__init__(*args, **kwargs)
        self.login_manager = LoginManager()
        self.login_manager.login_message_category = "warning"
        self.login_manager.user_loader(self.load_user)
        self.logged_in_menu = DropdownMenu()
        self.login_text = mydomain.lazy_gettext('Login...')
        self.logged_in_user_text = mydomain.lazy_gettext('User: ')

    def load_user(self, user_id):
        raise NotImplementedError

    def login(self, view):
        self.login_manager.login_view = self.name + '.' + view.__name__
        return view

    def register(self, app, *args, **kwargs):
        super(AuthenticationModule, self).register(app, *args, **kwargs)
        self.login_manager.init_app(app)

    def login_url(self):
        return login_url(self.login_manager.login_view,
                         request.url)

    def logged_in_text(self):
        return self.logged_in_user_text + ' ' + self.get_current_user_name()

    def get_current_user_name(self):
        return current_user.get_name()

    def user_menu(self, text, group='', values={}):
        def wrap(view):
            name = self.name + '.' + view.__name__
            entry = self.menu_entry_for_view(view, text, values=values)
            self.logged_in_menu.add_entry(name, entry, group)
            return view
        return wrap

    def get_anonymous_system_menu(self):
        return MenuItem(text=self.login_text,
                        url=self.login_url())
    

    def get_system_menu_item(self):
        if current_user.is_anonymous():
            return self.get_anonymous_system_menu()
        else:
            return MenuItem(text=self.logged_in_text(),
                            items=self.logged_in_menu.build_real_menu())

    def handle_forbidden_endpoint(self):
        if current_user.is_anonymous():
            return self.login_manager.unauthorized()
        else:
            return self.forbidden()

    def forbidden(self):
        return abort(403)
Example #17
0
def init_login_manager(app):
    login_manager = LoginManager()
    login_manager.login_view = "auth.login"
    login_manager.setup_app(app)

    @login_manager.user_loader
    def load_user(userid):
        return User(userid)
Example #18
0
def register_login(app):
	login_manager = LoginManager()
	login_manager.login_view = 'account.login'
	login_manager.init_app(app)

	@login_manager.user_loader
	def load_user(user_id):
		return Account.query.get(user_id)
    def __init__(self, app, user_repository):
        self.user_repository = user_repository

        login_manager = LoginManager()
        login_manager.user_loader(self.user_repository.get_by_username)
        login_manager.setup_app(app)

        self.login_manager = login_manager
Example #20
0
	def init_login(self, app):
		login_manager = LoginManager(app)
		login_manager.login_view = self.login_endpoint

		# User Loader
		@login_manager.user_loader
		def load_user(id):
			return self.get_user(id)
Example #21
0
def configure_identity(app):
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = "account.login"

    @login_manager.user_loader
    def load_user(userid):
        return User.get_by_id(int(userid))
Example #22
0
def init_login(app):
    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        from app.models import User
        return User.query.filter_by(id=user_id).first()
Example #23
0
    def init_app(self, app, datastore):
        """Initializes the Flask-Security extension for the specified
        application and datastore implentation.

        :param app: The application.
        :param datastore: An instance of a user datastore.
        """
        if app is None or datastore is None:
            return

        # TODO: change blueprint name
        blueprint = Blueprint('auth', __name__)

        configured = {}

        for key, value in default_config.items():
            configured[key] = app.config.get(key, value)

        app.config.update(configured)
        config = app.config

        # setup the login manager extension
        login_manager = LoginManager()
        login_manager.anonymous_user = AnonymousUser
        login_manager.login_view = config[LOGIN_VIEW_KEY]
        login_manager.setup_app(app)
        app.login_manager = login_manager

        Provider = get_class_from_config(AUTH_PROVIDER_KEY, config)
        Form = get_class_from_config(LOGIN_FORM_KEY, config)
        pw_hash = config[PASSWORD_HASH_KEY]

        app.pwd_context = CryptContext(schemes=[pw_hash], default=pw_hash)
        app.auth_provider = Provider(Form)
        app.principal = Principal(app)

        from flask.ext import security as s
        s.User, s.Role = datastore.get_models()

        setattr(app, config[USER_DATASTORE_KEY], datastore)

        @identity_loaded.connect_via(app)
        def on_identity_loaded(sender, identity):
            if hasattr(current_user, 'id'):
                identity.provides.add(UserNeed(current_user.id))

            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))

            identity.user = current_user

        @login_manager.user_loader
        def load_user(user_id):
            try:
                return datastore.with_id(user_id)
            except Exception, e:
                logger.error('Error getting user: %s' % e)
                return None
Example #24
0
def configure_login_manager(app):
    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(userid):
        return User.query.get(userid)

    login_manager.login_view = "frontend.signin"
Example #25
0
def init_login():
    login_manager = LoginManager()
    login_manager.init_app(app)

    login_manager.login_view = 'login'
    # Create user loader function
    @login_manager.user_loader
    def load_user(user_id):
        return db.session.query(User).get(user_id)
Example #26
0
 def test_no_user_loader_raises(self):
     login_manager = LoginManager(self.app, add_context_processor=True)
     with self.app.test_request_context():
         session['user_id'] = '2'
         with self.assertRaises(Exception) as cm:
             login_manager.reload_user()
         expected_exception_message = 'No user_loader has been installed'
         self.assertTrue(
             str(cm.exception).startswith(expected_exception_message))
Example #27
0
def setup_login(app):
    from models import User
    login_manager = LoginManager()
    login_manager.login_view = 'Common.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(userid):
        return User.query.get(userid)
Example #28
0
def init_login(app):
    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(userid):
        return User()

    return login_manager
def init_login():
    login_manager = LoginManager()
    login_manager.login_view = "/login/"
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        from lightningwolf_smp.models import User
        return db.session.query(User).get(user_id)
Example #30
0
def configure_extensions(app):
    from flask.ext.login import LoginManager
    login_manager = LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(userid):
        from webapp.api import User
        return User(userid)