def test_multiple_apps(self): app1 = flask.Flask(__name__) b1 = babel.Babel(app1, default_locale='de_DE') app2 = flask.Flask(__name__) b2 = babel.Babel(app2, default_locale='de_DE') with app1.test_request_context(): assert babel.gettext('Yes') == 'Ja' assert 'de_DE' in b1._default_domain.cache with app2.test_request_context(): assert 'de_DE' not in b2._default_domain.cache
def test_default_domain(self): app = flask.Flask(__name__) domain = babel.Domain(domain='test') b = babel.Babel(app, default_locale='de_DE', default_domain=domain) with app.test_request_context(): assert babel.gettext('first') == 'erste'
def test_refreshing(self): app = flask.Flask(__name__) b = babel.Babel(app) d = datetime(2010, 4, 12, 13, 46) with app.test_request_context(): assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM' app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna' babel.refresh() assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM'
def test_lazy_gettext(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') yes = lazy_gettext(u'Yes') with app.test_request_context(): assert text_type(yes) == 'Ja' app.config['BABEL_DEFAULT_LOCALE'] = 'en_US' with app.test_request_context(): assert text_type(yes) == 'Yes'
def test_basics(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') with app.test_request_context(): assert gettext(u'Hello %(name)s!', name='Peter') == 'Hallo Peter!' assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 3) == u'3 Äpfel' assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 1) == u'1 Apfel'
def test_lazy_gettext_defaultdomain(self): app = flask.Flask(__name__) domain = babel.Domain(domain='test') b = babel.Babel(app, default_locale='de_DE', default_domain=domain) first = lazy_gettext('first') with app.test_request_context(): assert text_type(first) == 'erste' app.config['BABEL_DEFAULT_LOCALE'] = 'en_US' with app.test_request_context(): assert text_type(first) == 'first'
def test_custom_formats(self): app = flask.Flask(__name__) app.config.update(BABEL_DEFAULT_LOCALE='en_US', BABEL_DEFAULT_TIMEZONE='Pacific/Johnston') b = babel.Babel(app) b.date_formats['datetime'] = 'long' b.date_formats['datetime.long'] = 'MMMM d, yyyy h:mm:ss a' d = datetime(2010, 4, 12, 13, 46) with app.test_request_context(): assert babel.format_datetime(d) == 'April 12, 2010 3:46:00 AM'
def test_basics(self): app = flask.Flask(__name__) b = babel.Babel(app) n = 1099 with app.test_request_context(): assert babel.format_number(n) == u'1,099' assert babel.format_decimal(Decimal('1010.99')) == u'1,010.99' assert babel.format_currency(n, 'USD') == '$1,099.00' assert babel.format_percent(0.19) == '19%' assert babel.format_scientific(10000) == u'1E4'
def test_basics(self): app = flask.Flask(__name__) b = babel.Babel(app) d = datetime(2010, 4, 12, 13, 46) with app.test_request_context(): assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM' assert babel.format_date(d) == 'Apr 12, 2010' assert babel.format_time(d) == '1:46:00 PM' with app.test_request_context(): app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna' assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM' assert babel.format_date(d) == 'Apr 12, 2010' assert babel.format_time(d) == '3:46:00 PM' with app.test_request_context(): app.config['BABEL_DEFAULT_LOCALE'] = 'de_DE' assert babel.format_datetime(d, 'long') == \ '12. April 2010 15:46:00 MESZ'
def test_custom_locale_selector(self): app = flask.Flask(__name__) b = babel.Babel(app) d = datetime(2010, 4, 12, 13, 46) the_timezone = 'UTC' the_locale = 'en_US' @b.localeselector def select_locale(): return the_locale @b.timezoneselector def select_timezone(): return the_timezone with app.test_request_context(): assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM' the_locale = 'de_DE' the_timezone = 'Europe/Vienna' with app.test_request_context(): assert babel.format_datetime(d) == '12.04.2010 15:46:00'
def test_template_basics(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') t = lambda x: flask.render_template_string('{{ %s }}' % x) with app.test_request_context(): assert t( "gettext('Hello %(name)s!', name='Peter')") == 'Hallo Peter!' assert t( "ngettext('%(num)s Apple', '%(num)s Apples', 3)") == u'3 Äpfel' assert t( "ngettext('%(num)s Apple', '%(num)s Apples', 1)") == u'1 Apfel' assert flask.render_template_string( ''' {% trans %}Hello {{ name }}!{% endtrans %} ''', name='Peter').strip() == 'Hallo Peter!' assert flask.render_template_string( ''' {% trans num=3 %}{{ num }} Apple {%- pluralize %}{{ num }} Apples{% endtrans %} ''', name='Peter').strip() == u'3 Äpfel'
def create_app(): app = Flask(__name__) app.config["DEBUG"] = True # SECRET_KEY generated using: secrets.token_urlsafe() app.config["SECRET_KEY"] = "pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw" app.config["LOGIN_DISABLED"] = False app.config["WTF_CSRF_ENABLED"] = False # Don't actually send any email - instead we subscribe to signals app.config["MAIL_SUPPRESS_SEND"] = True app.config["SECURITY_TWO_FACTOR_SECRET"] = { "1": "TjQ9Qa31VOrfEzuPy4VHQWPCTmRzCnFzMKLxXYiZu9B" } # Make this plaintext for most tests - reduces unit test time by 50% app.config["SECURITY_PASSWORD_HASH"] = "plaintext" # Make this hex_md5 for token tests app.config["SECURITY_HASHING_SCHEMES"] = ["hex_md5"] app.config["SECURITY_DEPRECATED_HASHING_SCHEMES"] = [] for opt in [ "changeable", "recoverable", "registerable", "trackable", "NOTpasswordless", "confirmable", "two_factor", ]: app.config["SECURITY_" + opt.upper()] = True if os.environ.get("SETTINGS"): app.config.from_envvar("SETTINGS") mail = Mail(app) app.json_encoder = JSONEncoder app.mail = mail # Setup Flask-Security user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role) security = Security(app, user_datastore) # This is NOT ideal since it basically changes entire APP (which is fine for # this test - but not fine for general use). babel = flask_babelex.Babel(app, default_domain=security.i18n_domain) @babel.localeselector def get_locale(): # For a given session - set lang based on first request. # Honor explicit url request first if "lang" not in session: locale = request.args.get("lang", None) if not locale: locale = request.accept_languages.best if not locale: locale = "en" if locale: session["lang"] = locale return session.get("lang", None).replace("-", "_") # Create a user to test with @app.before_first_request def create_user(): init_db() db_session.commit() test_acct = "*****@*****.**" if not user_datastore.get_user(test_acct): add_user(user_datastore, test_acct, "password", ["admin"]) print("Created User: {} with password {}".format( test_acct, "password")) @user_registered.connect_via(app) def on_user_registered(myapp, user, confirm_token): flash("To confirm {} - go to /confirm/{}".format( user.email, confirm_token)) @reset_password_instructions_sent.connect_via(app) def on_reset(myapp, user, token): flash("Go to /reset/{}".format(token)) @tf_security_token_sent.connect_via(app) def on_token_sent(myapp, user, token, method): flash("User {} was sent two factor token {} via {}".format( user.email, token, method)) # Views @app.route("/") @login_required def home(): return render_template_string( "{% include 'security/_messages.html' %}" "{{ _fsdomain('Welcome') }} {{email}} !", email=current_user.email, ) return app
def test_list_translations(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') translations = b.list_translations() assert len(translations) == 1 assert str(translations[0]) == 'de'
def create_app(): # Use real templates - not test templates... app = Flask(__name__, template_folder="../") app.config["DEBUG"] = True # SECRET_KEY generated using: secrets.token_urlsafe() app.config["SECRET_KEY"] = "pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw" # PASSWORD_SALT secrets.SystemRandom().getrandbits(128) app.config[ "SECURITY_PASSWORD_SALT"] = "156043940537155509276282232127182067465" app.config["LOGIN_DISABLED"] = False app.config["WTF_CSRF_ENABLED"] = False app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"] = [ { "email": { "mapper": uia_email_mapper, "case_insensitive": True } }, { "us_phone_number": { "mapper": uia_phone_mapper } }, ] # app.config["SECURITY_US_ENABLED_METHODS"] = ["password"] # app.config["SECURITY_US_ENABLED_METHODS"] = ["authenticator", "password"] # app.config["SECURITY_US_SIGNIN_REPLACES_LOGIN"] = True app.config["SECURITY_TOTP_SECRETS"] = { "1": "TjQ9Qa31VOrfEzuPy4VHQWPCTmRzCnFzMKLxXYiZu9B" } app.config["SECURITY_FRESHNESS"] = datetime.timedelta(minutes=0.5) app.config["SECURITY_FRESHNESS_GRACE_PERIOD"] = datetime.timedelta( minutes=2) # Turn on all features (except passwordless since that removes normal login) for opt in [ "changeable", "recoverable", "registerable", "trackable", "NOTpasswordless", "confirmable", "two_factor", "unified_signin", ]: app.config["SECURITY_" + opt.upper()] = True if os.environ.get("SETTINGS"): # Load settings from a file pointed to by SETTINGS app.config.from_envvar("SETTINGS") # Allow any SECURITY_ config to be set in environment. for ev in os.environ: if ev.startswith("SECURITY_"): app.config[ev] = _find_bool(os.environ.get(ev)) mail = FlashMail(app) app.mail = mail app.json_encoder = JSONEncoder # Setup Flask-Security user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role) Security(app, user_datastore) babel = None if HAVE_BABEL: babel = flask_babel.Babel(app) if HAVE_BABELEX: babel = flask_babelex.Babel(app) if babel: @babel.localeselector def get_locale(): # For a given session - set lang based on first request. # Honor explicit url request first if "lang" not in session: locale = request.args.get("lang", None) if not locale: locale = request.accept_languages.best if not locale: locale = "en" if locale: session["lang"] = locale return session.get("lang", None).replace("-", "_") # Create a user to test with @app.before_first_request def create_user(): init_db() db_session.commit() test_acct = "*****@*****.**" if not user_datastore.find_user(email=test_acct): add_user(user_datastore, test_acct, "password", ["admin"]) print("Created User: {} with password {}".format( test_acct, "password")) @user_registered.connect_via(app) def on_user_registered(myapp, user, confirm_token, **extra): flash(f"To confirm {user.email} - go to /confirm/{confirm_token}") @reset_password_instructions_sent.connect_via(app) def on_reset(myapp, user, token, **extra): flash(f"Go to /reset/{token}") @tf_security_token_sent.connect_via(app) def on_token_sent(myapp, user, token, method, **extra): flash("User {} was sent two factor token {} via {}".format( user.calc_username(), token, method)) @us_security_token_sent.connect_via(app) def on_us_token_sent(myapp, user, token, method, **extra): flash("User {} was sent sign in code {} via {}".format( user.calc_username(), token, method)) # Views @app.route("/") @login_required def home(): return render_template_string( "{% include 'security/_messages.html' %}" "{{ _fsdomain('Welcome') }} {{email}} !", email=current_user.email, ) @app.route("/basicauth") @auth_required("basic") def basic(): return render_template_string("Basic auth success") @app.route("/protected") @auth_required() def protected(): return render_template_string("Protected endpoint") return app
def create_app(): # Use real templates - not test templates... app = Flask( "view_scaffold", template_folder="../", static_folder="../flask_security/static" ) app.config["DEBUG"] = True # SECRET_KEY generated using: secrets.token_urlsafe() app.config["SECRET_KEY"] = "pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw" # PASSWORD_SALT secrets.SystemRandom().getrandbits(128) app.config["SECURITY_PASSWORD_SALT"] = "156043940537155509276282232127182067465" app.config["LOGIN_DISABLED"] = False app.config["WTF_CSRF_ENABLED"] = True app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"] = [ {"email": {"mapper": uia_email_mapper, "case_insensitive": True}}, {"us_phone_number": {"mapper": uia_phone_mapper}}, ] # app.config["SECURITY_US_ENABLED_METHODS"] = ["password"] # app.config["SECURITY_US_ENABLED_METHODS"] = ["authenticator", "password"] # app.config["SECURITY_US_SIGNIN_REPLACES_LOGIN"] = True # app.config["SECURITY_WAN_ALLOW_USER_HINTS"] = False app.config["SECURITY_TOTP_SECRETS"] = { "1": "TjQ9Qa31VOrfEzuPy4VHQWPCTmRzCnFzMKLxXYiZu9B" } app.config["SECURITY_FRESHNESS"] = datetime.timedelta(minutes=1) app.config["SECURITY_FRESHNESS_GRACE_PERIOD"] = datetime.timedelta(minutes=2) app.config["SECURITY_USERNAME_ENABLE"] = True class TestWebauthnUtil(WebauthnUtil): def generate_challenge(self, nbytes: t.Optional[int] = None) -> str: # Use a constant Challenge so we can use this app to generate gold # responses for use in unit testing. See test_webauthn. # NEVER NEVER NEVER do this in production return "smCCiy_k2CqQydSQ_kPEjV5a2d0ApfatcpQ1aXDmQPo" # Turn on all features (except passwordless since that removes normal login) for opt in [ "changeable", "recoverable", "registerable", "trackable", "NOTpasswordless", "confirmable", "two_factor", "unified_signin", "webauthn", ]: app.config["SECURITY_" + opt.upper()] = True if os.environ.get("SETTINGS"): # Load settings from a file pointed to by SETTINGS app.config.from_envvar("SETTINGS") # Allow any SECURITY_ config to be set in environment. for ev in os.environ: if ev.startswith("SECURITY_") or ev.startswith("SQLALCHEMY_"): app.config[ev] = _find_bool(os.environ.get(ev)) mail = FlashMail(app) app.mail = mail app.json_encoder = JSONEncoder # Create database models and hook up. app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db = SQLAlchemy(app) fsqla.FsModels.set_db_info(db) class Role(db.Model, fsqla.FsRoleMixin): pass class User(db.Model, fsqla.FsUserMixin): pass class WebAuthn(db.Model, fsqla.FsWebAuthnMixin): pass # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role, WebAuthn) security = Security(app, user_datastore, webauthn_util_cls=TestWebauthnUtil) try: import flask_babel babel = flask_babel.Babel(app) except ImportError: try: import flask_babelex babel = flask_babelex.Babel(app) except ImportError: babel = None if babel: @babel.localeselector def get_locale(): # For a given session - set lang based on first request. # Honor explicit url request first if "lang" not in session: locale = request.args.get("lang", None) if not locale: locale = request.accept_languages.best if not locale: locale = "en" if locale: session["lang"] = locale return session.get("lang", None).replace("-", "_") @app.before_first_request def clear_lang(): session.pop("lang", None) # Create a user to test with @app.before_first_request def create_user(): db.create_all() test_acct = "*****@*****.**" if not user_datastore.find_user(email=test_acct): add_user(user_datastore, test_acct, "password", ["admin"]) print("Created User: {} with password {}".format(test_acct, "password")) @app.after_request def allow_absolute_redirect(r): # This is JUST to test odd possible redirects that look relative but are # interpreted by browsers as absolute. # DON'T SET THIS IN YOUR APPLICATION! r.autocorrect_location_header = False return r @user_registered.connect_via(app) def on_user_registered(myapp, user, confirm_token, **extra): flash(f"To confirm {user.email} - go to /confirm/{confirm_token}") @reset_password_instructions_sent.connect_via(app) def on_reset(myapp, user, token, **extra): flash(f"Go to /reset/{token}") @tf_security_token_sent.connect_via(app) def on_token_sent(myapp, user, token, method, **extra): flash( "User {} was sent two factor token {} via {}".format( user.calc_username(), token, method ) ) @us_security_token_sent.connect_via(app) def on_us_token_sent(myapp, user, token, method, **extra): flash( "User {} was sent sign in code {} via {}".format( user.calc_username(), token, method ) ) # Views @app.route("/") @login_required def home(): return render_template_string( """ {% include 'security/_messages.html' %} {{ _fsdomain('Welcome') }} {{email}} ! {% include "security/_menu.html" %} """, email=current_user.email, security=security, ) @app.route("/basicauth") @auth_required("basic") def basic(): return render_template_string("Basic auth success") @app.route("/protected") @auth_required() def protected(): return render_template_string("Protected endpoint") return app