def __init__(self, app, install=True, prefix=None, name='GoogleAuth'): self.app = app self.app.config.setdefault('GOOGLE_DOMAIN', None) self.oid = OpenID(self.app) self.url_prefix = prefix self.name = name self.blueprint = self._get_blueprint(self.name) self.domain = self.app.config.get('GOOGLE_DOMAIN') self._login = self.oid.loginhandler(self.__login) self._create_or_login = self.oid.after_login(self.__create_or_login) if install: self.install()
class GoogleAuth(object): """Google Federated Authentication manager. If ``install==True`` (default), it is automatically installed into the given Flask application. """ def __init__(self, app, install=True, prefix=None, name='GoogleAuth'): self.app = app self.app.config.setdefault('GOOGLE_DOMAIN', None) self.oid = OpenID(self.app) self.url_prefix = prefix self.name = name self.blueprint = self._get_blueprint(self.name) self.domain = self.app.config.get('GOOGLE_DOMAIN') self._login = self.oid.loginhandler(self.__login) self._create_or_login = self.oid.after_login(self.__create_or_login) if install: self.install() def _check_auth(self): """Returns True if authentication is valid.""" return ('openid' in session) if self.domain else True def __login(self): return self.oid.try_login('https://www.google.com/accounts/o8/site-xrds?hd=%s' % self.domain) def _before_request(self): g.user = None def __create_or_login(self, resp): """This is called when login with OpenID succeeded and it's not necessary to figure out if this is the users's first login or not. This function has to redirect otherwise the user will be presented with a terrible URL which we certainly don't want. """ session['openid'] = resp.identity_url return redirect(self.oid.get_next_url()) def _logout(self): session.pop('openid', None) return redirect(self.oid.get_next_url()) def _get_blueprint(self, name): return Blueprint( name, __name__, static_folder=os.path.join(current_dir, 'static'), template_folder=os.path.join(current_dir, 'templates'), ) def _configure_routes(self): self.blueprint.route('/login/', methods=['GET', 'POST'])(self._login) self.blueprint.route('/logout/', methods=['GET', 'POST'])(self._logout) def _register_blueprint(self, **kwargs): self.app.register_blueprint( self.blueprint, url_prefix=self.url_prefix, **kwargs ) def install(self): """Installs the Blueprint into the app.""" self.app.before_request(self._before_request) self._configure_routes() self._register_blueprint() def required(self, f): """Request decorator. Forces authentication.""" @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not self._check_auth(): return redirect(url_for('%s.__login' % self.blueprint.name, next=request.url)) return f(*args, **kwargs) return decorated
from flask import g, redirect, request, session, flash, url_for, render_template from flask_openid import OpenID from flask_oauth import OAuth from penguicontrax import constants from . import lookup_current_user, User from .. import app, db from ..constants import constants import urllib, hashlib oid = OpenID(app, constants.OPENID_STORE, safe_roots=[]) oauth = OAuth() twitter = oauth.remote_app('twitter', base_url='https://api.twitter.com/1/', request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authorize', consumer_key=constants.TWITTER_KEY, consumer_secret=constants.TWITTER_SECRET_KEY ) facebook = 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=constants.FACEBOOK_APP_ID, consumer_secret=constants.FACEBOOK_SECRET, request_token_params={'scope': 'email'} ) def gravatar_image_update(user): default_small = constants.PUBLIC_URL + 'static/penguinhead_small.png'
app.config.from_pyfile('settings.cfg') app.debug = app.config['DEBUG'] boto_logger = logging.getLogger('boto') handler = RotatingFileHandler(app.config['LOG_DIR'] + '/' + __name__ + '.log', maxBytes=10000, backupCount=1) if app.config['DEBUG'] == 'True': handler.setLevel(logging.DEBUG) boto_logger.setLevel(logging.DEBUG) else: # Force TLS and HSTS only in production sslify = SSLify(app, permanent=True) handler.setLevel(logging.INFO) app.logger.addHandler(handler) db = SQLAlchemy(app) oid = OpenID(app) app.logger.info( 'App started with debug mode: {0}\nApp running with Flask: {1}'.format( app.config['DEBUG'], app.config['USE_FLASK'])) class Role(db.Model): id = db.Column(db.Integer, primary_key=True) role = db.relationship('User', backref='user') name = db.Column(db.String(40)) @staticmethod def get_or_create(role_name): rv = Role.query.filter_by(name=role_name).first() if rv is None:
from flask_openid import OpenID LOGIN_URL = "https://login.ubuntu.com" app = FlaskBase( __name__, "anbox-cloud.io", template_folder="../templates", static_folder="../static", template_404="404.html", template_500="500.html", ) app.secret_key = os.environ["SECRET_KEY"] open_id = OpenID(stateless=True, safe_roots=[]) def login_required(func): """ Decorator that checks if a user is logged in, and redirects to login page if not. """ @functools.wraps(func) def is_user_logged_in(*args, **kwargs): if "openid" not in flask.session: return flask.redirect("/login?next=" + flask.request.path) return func(*args, **kwargs)
from flask_openid import OpenID from flask_migrate import Migrate from cfg.configuration import load_config from models import db def create_app(): """Factory to create the Flask application with cfg and db.""" app = Flask(__name__) load_config(app.config) db.init_app(app) return app app = create_app() oid = OpenID(app, store_factory=lambda: None) migrate = Migrate(app, db) ########## # Routes # ########## @app.route('/docs/<path:path>') def access_docs(path): return send_from_directory('docs', path) from routes.user import build_api_user from routes.auth import build_api_auth from routes.game import build_api_game build_api_auth(app, oid)
#encoding: utf-8 from flask_bcrypt import Bcrypt from flask_login import LoginManager from flask_openid import OpenID from flask_mail import Mail from flask_cache import Cache from flask_restful import Api bcrypt = Bcrypt() openid = OpenID() mail = Mail() cache = Cache() restful_api = Api() # Create the Flask-Login's instance login_manager = LoginManager() login_manager.login_view = "main.login" login_manager.session_protection = "strong" login_manager.login_message = "Please login to access this page." login_manager.login_message_category = "info" @login_manager.user_loader def load_user(user_id): """Load the user's info."""
from os.path import dirname, join from flask import Flask, g, redirect, session, json from flask_sqlalchemy import SQLAlchemy from flask_openid import OpenID import urllib, urllib2 import re app = Flask(__name__) app.config.update(SQLALCHEMY_DATABASE_URI='sqlite:///flask-openid.db', SECRET_KEY='STEAM API KEY', DEBUG=True, PORT=5000) oid = OpenID(app, join(dirname(__file__), 'openid_store')) db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) steam_id = db.Column(db.String(40)) nickname = db.Column(db.String(80)) @staticmethod def get_or_create(steam_id): rv = User.query.filter_by(steam_id=steam_id).first() if rv is None: rv = User() rv.steam_id = steam_id dbs.session.add(rv) return rv
from requests.exceptions import RequestException from urllib.parse import urlparse, parse_qs from random import randint app = flask.Flask(__name__) app.secret_key = os.environ['SECRET_KEY'] # Setup session to retry requests 5 times uncached_session = requests.Session() retries = Retry(total=5, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504]) uncached_session.mount('https://api.snapcraft.io', HTTPAdapter(max_retries=retries)) oid = OpenID(app, safe_roots=[], extension_responses=[MacaroonResponse]) # The cache expires after 5 seconds cached_session = requests_cache.CachedSession(expire_after=5) # Requests should timeout after 2 seconds in total request_timeout = 2 # Request only stable snaps snap_details_url = ("https://api.snapcraft.io/api/v1/snaps/details/{snap_name}" "?channel=stable") details_query_headers = { 'X-Ubuntu-Series': '16', 'X-Ubuntu-Architecture': 'amd64', }
from flask_login import LoginManager # takes care of the inputs and user handling # create an application object from config import basedir, MAIL_PASSWORD, MAIL_USERNAME, MAIL_PORT, MAIL_SERVER, ADMINS app = Flask(__name__) app.config.from_object('config') # why is this coming from 'config' object? # SQLAlchemy is Python SQL toolkit and Object Relational Mapper db = SQLAlchemy(app) # the views are the handlers that response to requests from web browser or other clients lm = LoginManager() lm.init_app(app) lm.login_view = 'login' # this is the view that logs the user in oid = OpenID(app, os.path.join(basedir, "tmp")) # enabling email to be sent when there is an error if not app.debug: import logging from logging.handlers import SMTPHandler credentials = None if MAIL_USERNAME or MAIL_PASSWORD: credentials = (MAIL_USERNAME, MAIL_PASSWORD) mail_handler = SMTPHandler((MAIL_SERVER, MAIL_PORT), 'no-reply@' + MAIL_SERVER, ADMINS, "app failure", credentials) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) # enable logging to a file if not app.debug:
import json import os.path import re from datetime import datetime from urllib.parse import urlencode from urllib.request import urlopen import requests from flask import Flask, render_template, redirect, session, g from flask_openid import OpenID from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_envvar('STEAMLENS_SETTINGS') oid = OpenID(app, os.path.join(os.path.dirname(__file__), app.config['OPENID_STIRE'])) db = SQLAlchemy(app) ####################### # Recommender Service # ####################### @app.context_processor def inject_current_time(): return {'current_time': datetime.utcnow()} @app.route('/') def index(): return redirect('/pop')
app = flask.Flask(__name__) if "COPRS_ENVIRON_PRODUCTION" in os.environ: app.config.from_object("coprs.config.ProductionConfig") elif "COPRS_ENVIRON_UNITTEST" in os.environ: app.config.from_object("coprs.config.UnitTestConfig") else: app.config.from_object("coprs.config.DevelopmentConfig") if os.environ.get("COPR_CONFIG"): app.config.from_envvar("COPR_CONFIG") else: app.config.from_pyfile("/etc/copr/copr.conf", silent=True) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True oid = OpenID(app, app.config["OPENID_STORE"], safe_roots=[], extension_responses=[TeamsResponse]) db = SQLAlchemy(app) @contextmanager def db_session_scope(): """Provide a transactional scope around a series of operations.""" session = db.session try: yield session session.commit() except Exception as err: session.rollback() raise
from flask_openid import OpenID import anitya.lib import anitya.mail_logging __version__ = '0.11.0' # Create the application. APP = flask.Flask(__name__) APP.config.from_object('anitya.default_config') if 'ANITYA_WEB_CONFIG' in os.environ: # pragma: no cover APP.config.from_envvar('ANITYA_WEB_CONFIG') # Set up OpenID APP.oid = OpenID(APP) # Set up the logging logging_config = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '[%(name)s %(levelname)s] %(message)s', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple', 'stream': 'ext://sys.stdout',
""" Config can be either of DevelopmentConfig ProductionConfig TestingConfig """ app.config.from_object('core.config.DevelopmentConfig') """ Internationalization support """ babel = Babel(app) """ OpenID instance """ openid_store = "logs" oid = OpenID(app, openid_store) """ Helper modules for app """ from core import context_processors, loggers """ Create cookie to track activities if user is not logged in Value in this cookie will be used as temporary userid in words, descriptions, views, likes and dislikes """ @app.before_request def create_temp_userid_cookie(): session.permanent = True app.permanent_session_lifetime = timedelta(days=31) if 'openid' not in session:
from flask import Flask, redirect, request, jsonify # session? from flask_openid import OpenID from flask_cors import cross_origin from Battlerite import teams, players, matches, telemetry from Database.MongoDB import mongodb from Database.ORM import champion, tournament, test from Steam.Steam import getSInfo app = Flask(__name__) openID = OpenID(app) app.config.update( SECRET_KEY= 'static', # os.urandom(24), <-- can be used to use random keys(not api) DEBUG=True, TESTING=True) db = mongodb.initialise_database(app) #app.steamUser = None @app.route("/steam", methods=["GET"]) @openID.loginhandler def login(): return openID.try_login('http://steamcommunity.com/openid') @openID.after_login def after_login(response): #return "plz - {}".format(getSInfo(response)) return redirect(openID.get_next_url() + '?{}'.format(getSInfo(response)['steamid']))
from flask import Flask, render_template, request, g, session, flash, redirect, url_for, abort, jsonify from flask_openid import OpenID from openid.extensions import pape from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base app = Flask(__name__) app.config.update(DATABASE_URI='sqlite:///database.db', SECRET_KEY='dev key', DEBUG='true') oid = OpenID(app, safe_roots=[], extension_responses=[pape.Response]) # setup sqlalchemy engine = create_engine(app.config['DATABASE_URI']) db_session = scoped_session( sessionmaker(autocommit=False, autoflush=True, bind=engine)) Base = declarative_base() Base.query = db_session.query_property() def init_db(): Base.metadata.create_all(bind=engine) class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True)
def before_request(): g.user = current_user g.oid = OpenID(app, os.path.join(basedir, 'tmp'))
import os from flask_login import LoginManager from flask_openid import OpenID from config import dirCurrent ''' Application Configuration ''' app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager() lm.init_app(app) oid = OpenID(app, os.path.join(dirCurrent, 'tmp')) #placed here to prevent circular imports from models import * ''' Controller - Handling the routes. ''' @lm.user_loader def load_user(id): return User.query.get(int(id))
LOGIN_URL = "https://login.ubuntu.com" ANBOXCLOUD_API_BASE = "https://demo-api.anbox-cloud.io" session = requests.Session() app = FlaskBase( __name__, "anbox-cloud.io", template_folder="../templates", static_folder="../static", template_404="404.html", template_500="500.html", ) app.secret_key = os.environ["SECRET_KEY"] open_id = OpenID(stateless=True, safe_roots=[], extension_responses=[MacaroonResponse]) # Discourse docs session = talisker.requests.get_session() discourse_docs = Docs( parser=DocParser( api=DiscourseAPI(base_url="https://discourse.ubuntu.com/", session=session), index_topic_id=17029, url_prefix="/docs", ), document_template="docs/document.html", url_prefix="/docs", )
'no-reply@' + MAIL_SERVER, ADMINS, 'microblog failure', credentials) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not app.debug: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler('tmp/microblog.log', 'a', 1 * 1024 * 1024, 10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) app.logger.setLevel(logging.INFO) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.info('microblog startup') #Login lm = LoginManager() lm.init_app(app) lm.login_view = 'login' oid = OpenID(app, os.path.join(basedir, 'tmp')) #path donde guardaremos los archivos #conexion BDD db = SQLAlchemy(app) from app import views, models #importamos las vistas, lo hacemos al final para evitar referencias circulares
from app.form import LoginForm, EditForm, PostForm from flask_login import LoginManager, login_required, login_user, logout_user, current_user from datetime import datetime from pprint import pprint from app import app from app.models import User, Post from app.config import Config from flask_login import LoginManager from flask_openid import OpenID from app.models import db import os lm = LoginManager() lm.init_app(app) lm.login_view = 'login' oid = OpenID(app, os.path.join(os.path.abspath(os.path.dirname(__file__)), 'tmp')) @app.before_request def before_request(): g.user = current_user if g.user.is_authenticated: g.user.last_seen = datetime.utcnow() db.session.add(g.user) db.session.commit() #openID装饰器 @lm.user_loader def load_user(id): return User.query.get(int(id))
def __init__(self, appbuilder): super(BaseSecurityManager, self).__init__(appbuilder) app = self.appbuilder.get_app # Base Security Config app.config.setdefault('AUTH_ROLE_ADMIN', 'Admin') app.config.setdefault('AUTH_ROLE_PUBLIC', 'Public') app.config.setdefault('AUTH_TYPE', AUTH_DB) # Self Registration app.config.setdefault('AUTH_USER_REGISTRATION', False) app.config.setdefault('AUTH_USER_REGISTRATION_ROLE', self.auth_role_public) # LDAP Config if self.auth_type == AUTH_LDAP: if 'AUTH_LDAP_SERVER' not in app.config: raise Exception( "No AUTH_LDAP_SERVER defined on config with AUTH_LDAP authentication type." ) app.config.setdefault('AUTH_LDAP_SEARCH', '') app.config.setdefault('AUTH_LDAP_SEARCH_FILTER', '') app.config.setdefault('AUTH_LDAP_BIND_USER', '') app.config.setdefault('AUTH_LDAP_APPEND_DOMAIN', '') app.config.setdefault('AUTH_LDAP_USERNAME_FORMAT', '') app.config.setdefault('AUTH_LDAP_BIND_PASSWORD', '') # TLS options app.config.setdefault('AUTH_LDAP_USE_TLS', False) app.config.setdefault('AUTH_LDAP_ALLOW_SELF_SIGNED', False) app.config.setdefault('AUTH_LDAP_TLS_DEMAND', False) app.config.setdefault('AUTH_LDAP_TLS_CACERTDIR', '') app.config.setdefault('AUTH_LDAP_TLS_CACERTFILE', '') app.config.setdefault('AUTH_LDAP_TLS_CERTFILE', '') app.config.setdefault('AUTH_LDAP_TLS_KEYFILE', '') # Mapping options app.config.setdefault('AUTH_LDAP_UID_FIELD', 'uid') app.config.setdefault('AUTH_LDAP_FIRSTNAME_FIELD', 'givenName') app.config.setdefault('AUTH_LDAP_LASTNAME_FIELD', 'sn') app.config.setdefault('AUTH_LDAP_EMAIL_FIELD', 'mail') if self.auth_type == AUTH_OID: self.oid = OpenID(app) if self.auth_type == AUTH_OAUTH: from flask_oauthlib.client import OAuth self.oauth = OAuth() self.oauth_remotes = dict() for _provider in self.oauth_providers: provider_name = _provider['name'] log.debug("OAuth providers init {0}".format(provider_name)) obj_provider = self.oauth.remote_app(provider_name, **_provider['remote_app']) obj_provider._tokengetter = self.oauth_tokengetter if not self.oauth_user_info: self.oauth_user_info = self.get_oauth_user_info # Whitelist only users with matching emails if 'whitelist' in _provider: self.oauth_whitelists[provider_name] = _provider[ 'whitelist'] self.oauth_remotes[provider_name] = obj_provider self.lm = LoginManager(app) self.lm.login_view = 'login' self.lm.user_loader(self.load_user)
class GoogleAuth(object): """Google Federated Authentication manager. If ``install==True`` (default), it is automatically installed into the given Flask application. """ def __init__(self, app, install=True, prefix=None, name='GoogleAuth'): self.app = app self.app.config.setdefault('GOOGLE_DOMAIN', None) self.oid = OpenID(self.app) self.url_prefix = prefix self.name = name self.blueprint = self._get_blueprint(self.name) self.domain = self.app.config.get('GOOGLE_DOMAIN') self._login = self.oid.loginhandler(self.__login) self._create_or_login = self.oid.after_login(self.__create_or_login) if install: self.install() def _check_auth(self): """Returns True if authentication is valid.""" return ('openid' in session) if self.domain else True def __login(self): return self.oid.try_login( 'https://www.google.com/accounts/o8/site-xrds?hd=%s' % self.domain) def _before_request(self): g.user = None def __create_or_login(self, resp): """This is called when login with OpenID succeeded and it's not necessary to figure out if this is the users's first login or not. This function has to redirect otherwise the user will be presented with a terrible URL which we certainly don't want. """ session['openid'] = resp.identity_url return redirect(self.oid.get_next_url()) def _logout(self): session.pop('openid', None) return redirect(self.oid.get_next_url()) def _get_blueprint(self, name): return Blueprint( name, __name__, static_folder=os.path.join(current_dir, 'static'), template_folder=os.path.join(current_dir, 'templates'), ) def _configure_routes(self): self.blueprint.route('/login/', methods=['GET', 'POST'])(self._login) self.blueprint.route('/logout/', methods=['GET', 'POST'])(self._logout) def _register_blueprint(self, **kwargs): self.app.register_blueprint(self.blueprint, url_prefix=self.url_prefix, **kwargs) def install(self): """Installs the Blueprint into the app.""" self.app.before_request(self._before_request) self._configure_routes() self._register_blueprint() def required(self, f): """Request decorator. Forces authentication.""" @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not self._check_auth(): return redirect( url_for('%s.__login' % self.blueprint.name, next=request.url)) return f(*args, **kwargs) return decorated
from config import base_dir from flask import Flask from flask_login import LoginManager from flask_openid import OpenID from flask_sqlalchemy import SQLAlchemy from os import path app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager() lm.init_app(app) lm.login_view='login' oid = OpenID(app,path.join(base_dir,'tmp')) from app import views from app import models
'{0}:{1}'.format(app.config["MEMCACHED_HOST"], app.config["MEMCACHED_PORT"]) ], key_prefix=app.config["MEMCACHED_KEY_PREFIX"]) elif app.config["CACHE_TYPE"].lower() == "simple": flask_cache = SimpleCache() else: flask_cache = NullCache() if app.config["PROXY_SETUP"]: app.wsgi_app = ProxyFix(app.wsgi_app) if app.config["OPENID_ENABLED"]: from flask_openid import OpenID from openid_teams import teams oid = OpenID(app, safe_roots=[], extension_responses=[teams.TeamsResponse]) from webfaf.login import login # pylint: disable=cyclic-import app.register_blueprint(login) from webfaf.user import user # pylint: disable=cyclic-import app.register_blueprint(user) from webfaf.reports import reports # pylint: disable=wrong-import-position, cyclic-import app.register_blueprint(reports, url_prefix="/reports") from webfaf.problems import problems # pylint: disable=wrong-import-position, cyclic-import app.register_blueprint(problems, url_prefix="/problems") from webfaf.stats import stats # pylint: disable=wrong-import-position, cyclic-import app.register_blueprint(stats, url_prefix="/stats") from webfaf.summary import summary # pylint: disable=wrong-import-position, cyclic-import app.register_blueprint(summary, url_prefix="/summary")
import datanommer.models # Create the application. app = flask.Flask(__name__) log = app.logger app.url_map.converters['not_reserved'] = fmn.web.converters.NotReserved # set up FAS app.config.from_object('fmn.web.default_config') if 'FMN_WEB_CONFIG' in os.environ: # pragma: no cover app.config.from_envvar('FMN_WEB_CONFIG') # Set up OpenID in stateless mode oid = OpenID(app, safe_roots=[], store_factory=lambda: None, url_root_as_trust_root=True) # Inject a simple jinja2 test -- it is surprising jinja2 does not have this. app.jinja_env.tests['equalto'] = lambda x, y: x == y # Also, allow 'continue' and 'break' statements in jinja loops app.jinja_env.add_extension('jinja2.ext.loopcontrols') db_url = config.app_conf['fmn.sqlalchemy.uri'] fedmsg.meta.make_processors(**config.app_conf) # Long, long ago # http://threebean.org/blog/datanommer-and-fedmsg-activity/ before_fedmsg = datetime.datetime(2012, 10, 8)
from flask import flash, redirect, url_for, session from flask_bcrypt import Bcrypt from flask_openid import OpenID from flask_oauth import OAuth from flask_login import LoginManager, login_required from flask_principal import Principal, Permission, RoleNeed from flask_restful import Api from flask_celery import Celery admin_permission = Permission(RoleNeed('admin')) poster_permission = Permission(RoleNeed('poster')) default_permission = Permission(RoleNeed('default')) from celery.backends.redis import RedisBackend oid = OpenID() login_manager = LoginManager() login_manager.login_view = "main.login" login_manager.session_protection = "strong" login_manager.login_message = "Please login to access this page" login_manager.login_message_category = "info" bcrypt = Bcrypt() rest_api = Api() principals = Principal() celery = Celery() @login_manager.user_loader def load_user(userid): from .models import User return User.query.get(userid)
from flask import render_template, session, redirect, flash, url_for, request, g from flask_wtf import FlaskForm from wtforms import BooleanField, StringField, SubmitField from wtforms.validators import DataRequired from flask_login import login_user, logout_user, current_user from app import bp, db, lm, oid from app.models import User, ROLE_USER from flask_openid import OpenID oid = OpenID(bp, os.path.join(BASEDIR, 'tmp')) class LoginForm(FlaskForm): openid = StringField('openid', validators=[DataRequired()]) submit = SubmitField('Submit') remember_me = BooleanField('Remember_me', default=False) # 从数据库加载用户 @lm.user_loader def load_user(uid): return User.query.get(int(uid)) # Flask-Login设定的全局变量current_user复制给g变量 @bp.before_request def before_request(): g.user = current_user # 装饰器:oid.loginhandler 告诉Flask-OpenID这是登录视图函数
if sys.getdefaultencoding() != defaultencoding: reload(sys) sys.setdefaultencoding(defaultencoding) logging.basicConfig(filename='cmdb.log', level=logging.ERROR) logging.info('Started') app = Flask(__name__) logging.info('App established') #读取config配置 app.config.from_object('config') # 初始化Flask-Bootstap扩展 bootstrap = Bootstrap() mail = Mail() moment = Moment() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'cmdb.login' oid = OpenID(app, os.path.join(basedir, 'tmp')) app.config.from_object(config['default']) config['default'].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db = SQLAlchemy(app) db.init_app(app) login_manager.init_app(app) from app import views, models
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_openid import OpenID from config import basedir app = Flask(__name__) #instruct flask to read & use config file app.config.from_object('config') db = SQLAlchemy(app) #the db lm = LoginManager() lm.init_app(app) lm.login_view = 'login' oid = OpenID(app, '/path/to/store', safe_roots=[]) #oid = OpenID(app, os.path.join(basedir, 'tmp')) from app import views, models
from flask import render_template, flash, redirect, session, url_for, request, g from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_openid import OpenID import config from hashlib import md5 import os app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager() lm.init_app(app) lm.login_view = 'login' oid = OpenID(app, os.path.join(config.basedir, 'tmp')) followers = db.Table( "followers", db.Column("follower_id", db.Integer, db.ForeignKey("user.id")), db.Column("followed_id", db.Integer, db.ForeignKey("user.id"))) class User(db.Model): global followers id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) posts = db.relationship('Post', backref='author', lazy='dynamic') about_me = db.Column(db.String(140)) last_seen = db.Column(db.DateTime) followed = db.relationship("User",
import eventlet eventlet.monkey_patch() from flask_socketio import SocketIO from flask import Flask, g, session, request, flash, render_template, redirect, abort, url_for from flask_openid import OpenID from config import off from db import create_db, create_user, update_score, users_top, find_user, all_db, user_status app = Flask(__name__) app.config.from_object('config') socketio = SocketIO(app, async_mode='eventlet') oid = OpenID(app, 'tmp') def login_required(func): def before_request(*args, **kwargs): if g.user is None: return redirect('login') return func(*args, **kwargs) before_request.__name__ = func.__name__ return before_request @app.route('/top') @login_required def top(): default_start, default_amount = 0, 100