예제 #1
0
def _get_login_manager(app):
    lm = LoginManager()
    lm.anonymous_user = AnonymousUser
    lm.login_view = '%s.login' % cv('BLUEPRINT_NAME', app=app)
    lm.user_loader(_user_loader)
    lm.token_loader(_token_loader)

    if cv('FLASH_MESSAGES', app=app):
        lm.login_message, lm.login_message_category = cv('MSG_LOGIN', app=app)
        lm.needs_refresh_message, lm.needs_refresh_message_category = cv('MSG_REFRESH', app=app)
    else:
        lm.login_message = None
        lm.needs_refresh_message = None

    lm.init_app(app)
    return lm
예제 #2
0
파일: core.py 프로젝트: Aravs7/ubtz2
def _get_login_manager(app):
    lm = LoginManager()
    lm.anonymous_user = AnonymousUser
    lm.login_view = '%s.login' % cv('BLUEPRINT_NAME', app=app)
    lm.user_loader(_user_loader)
    lm.token_loader(_token_loader)

    if cv('FLASH_MESSAGES', app=app):
        lm.login_message, lm.login_message_category = cv('MSG_LOGIN', app=app)
        lm.needs_refresh_message, lm.needs_refresh_message_category = cv('MSG_REFRESH', app=app)
    else:
        lm.login_message = None
        lm.needs_refresh_message = None

    lm.init_app(app)
    return lm
예제 #3
0
def login_message(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.login_message = u"Log in or the owl will eat you."
    lm.setup_app(app)
    lm.unauthorized()
    assert u"Log in or the owl will eat you." in get_flashed_messages()
예제 #4
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
예제 #5
0
 def __initLoginManager(self):
     login_manager = LoginManager()
     login_manager.anonymous_user = SupportUser.Anonymous
     login_manager.login_view = '/login'
     login_manager.login_message = ''
     login_manager.user_loader(loadUserByID)
     login_manager.init_app(self)
예제 #6
0
def login_message(app):
    lm = LoginManager()
    lm.login_view = "login"
    lm.login_message = u"Log in or the owl will eat you."
    lm.setup_app(app)
    lm.unauthorized()
    assert u"Log in or the owl will eat you." in get_flashed_messages()
예제 #7
0
def _get_login_manager(app):
    lm = LoginManager()
    lm.anonymous_user = AnonymousUser
    lm.login_view = '%s.login' % cv('BLUEPRINT_NAME', app=app)
    lm.user_loader(_user_loader)
    lm.login_message = None
    lm.needs_refresh_message = None
    lm.unauthorized_callback = lambda: abort(401)
    lm.init_app(app)
    return lm
예제 #8
0
def setup_login_manager(app):
    """
    Configure the LoginManager for the provided app.
    """
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login_user'
    login_manager.login_message = 'Resource access not authorized.'
    login_manager.login_message_category = 'error'
    login_manager.anonymous_user = AnonymousUser
    login_manager.init_app(app)
    login_manager.user_loader(load_user)
    user_logged_in.connect(on_login, app)
예제 #9
0
   def setup_login(self, app):
      login_manager = LoginManager()
      login_manager.login_view = BasicLoginView.PATH 
      login_manager.login_message = LoginViews.SUCCESSFUL_LOGIN_MSG 

      @login_manager.user_loader
      def load_user(userID):
         return user.User.get(userID)
      
      @login_manager.unauthorized_handler
      def unauthorized():
         return redirect(BasicLoginView.PATH) 
      login_manager.setup_app(app)
예제 #10
0
파일: auth.py 프로젝트: sapelson/meieraha2
def init_blueprint(setup_state):
    '''Set up Flask-Login on blueprint registration'''
    
    app = setup_state.app
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_message = u"Please, log in to access this page"
    login_manager.login_message_category = "info"

    # Create user loader function
    @login_manager.user_loader
    def load_user(user_id):
        return db.session.query(User).get(user_id)
예제 #11
0
def init_blueprint(setup_state):
    '''Set up Flask-Login on blueprint registration'''

    app = setup_state.app
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_message_category = "info"
    login_manager.login_view = 'auth.login'
    login_manager.login_message = None

    # Create user loader function
    @login_manager.user_loader
    def load_user(user_id):
        return db.session.query(User).get(user_id)
예제 #12
0
def configure_extensions(app):
    #from simplekv.memory import DictStore
    #from flask.ext.kvsession import KVSessionExtension
    #store = DictStore()
    ## this will replace the app's session handling
    #KVSessionExtension(store, app)
    mongo.init_app(app, "FUNFUNSAY")

    # cache
    cache.init_app(app)

    # babel
    #print "create babel object"
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        # if a user is logged in, use the locale from the user settings
        if current_user.is_authenticated():
            return current_user.locale
        # otherwise try to guess the language from the user accept
        # header the browser transmits.  We support de/fr/en in this
        # example.  The best match wins.
        return request.accept_languages.best_match(['zh_CN', 'en'])

    @babel.timezoneselector
    def get_timezone():
        if current_user.is_authenticated():
            return current_user.timezone
        return app.config['BABEL_DEFAULT_TIMEZONE']

    # login.
    from flask.ext.login import LoginManager
    login_manager = LoginManager()
    login_manager.session_protection = None  #@fixme!
    login_manager.login_view = 'homesite.login'
    login_manager.refresh_view = 'homesite.reauth'
    login_manager.login_message = _("Please log in to access this page.")

    @login_manager.user_loader
    def load_user(id):
        #print "####: loaduser ", id
        return User.load_user(id)

    login_manager.setup_app(app)

    from flask.ext.markdown import Markdown
    Markdown(app, safe_mode="escape")
예제 #13
0
    def _create_login_manager(self):

        login_manager = LoginManager()
        login_manager.login_view = self.config['URL_PREFIX'] + '/sign_in'
        login_manager.login_message = 'Please sign in'

        @login_manager.user_loader
        def load_user(id):
            """Return the user from his email.

      Necessary for flask.login module.
        
      """
            return User.get_from_id(id)

        return login_manager
예제 #14
0
파일: auth.py 프로젝트: colwilson/flasker
  def _create_login_manager(self):

    login_manager = LoginManager()
    login_manager.login_view = self.config['URL_PREFIX'] + '/sign_in'
    login_manager.login_message = 'Please sign in'

    @login_manager.user_loader
    def load_user(id):
      """Return the user from his email.

      Necessary for flask.login module.
        
      """
      return User.get_from_id(id)

    return login_manager
예제 #15
0
파일: ffsapp.py 프로젝트: allopen/ecnunote
def configure_extensions(app):
    #from simplekv.memory import DictStore
    #from flask.ext.kvsession import KVSessionExtension
    #store = DictStore()
    ## this will replace the app's session handling
    #KVSessionExtension(store, app)
    mongo.init_app(app, "FUNFUNSAY")

    # cache
    cache.init_app(app)

    # babel
    #print "create babel object"
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        # if a user is logged in, use the locale from the user settings
        if current_user.is_authenticated():
            return current_user.locale
        # otherwise try to guess the language from the user accept
        # header the browser transmits.  We support de/fr/en in this
        # example.  The best match wins.
        return request.accept_languages.best_match(['zh_CN', 'en'])

    @babel.timezoneselector
    def get_timezone():
        if current_user.is_authenticated():
            return current_user.timezone
        return app.config['BABEL_DEFAULT_TIMEZONE']

    # login.
    from flask.ext.login import LoginManager
    login_manager = LoginManager()    
    login_manager.session_protection = None #@fixme!
    login_manager.login_view = 'homesite.login'
    login_manager.refresh_view = 'homesite.reauth'
    login_manager.login_message = _("Please log in to access this page.")

    @login_manager.user_loader
    def load_user(id):
        #print "####: loaduser ", id
        return User.load_user(id)
    login_manager.setup_app(app)

    from flask.ext.markdown import Markdown
    Markdown(app, safe_mode="escape")
예제 #16
0
파일: __init__.py 프로젝트: Perlmint/erika
def init_login(app):
    login_manager = LoginManager()

    login_manager.login_view = "user.login"
    login_manager.logout_view = 'user.logout'
    login_manager.login_message = u"Please log in to access this page."
    login_manager.refresh_view = "user.reauth"
    login_manager.anonymous_user = Anonymous

    login_manager.setup_app(app)
    
    
    @login_manager.user_loader
    def load_user(id):
        from user.models import User
        from common import db
        return db.session.query(User).filter(User.id==id).first()
예제 #17
0
def configure_identity(app):
    ''' Configure middleware. '''

    login_manager = LoginManager()
    login_manager.login_view = 'users.login'
    login_manager.login_message = u'Please log in to access this page.'
    login_manager.refresh_view = 'users.reauth'
    login_manager.needs_refresh_message = u'To protect your account, please reauthenticate to access this page.'

    ADMIN_USER = User(app.config['ADMIN_USERNAME']) 
    @login_manager.user_loader
    def load_user(username):
        if username == ADMIN_USER.username:
            return ADMIN_USER
        else:
            return None

    login_manager.setup_app(app)
예제 #18
0
def configure_identity(app):
    ''' Configure middleware. '''

    login_manager = LoginManager()
    login_manager.login_view = 'users.login'
    login_manager.login_message = u'Please log in to access this page.'
    login_manager.refresh_view = 'users.reauth'
    login_manager.needs_refresh_message = u'To protect your account, please reauthenticate to access this page.'

    ADMIN_USER = User(app.config['ADMIN_USERNAME'])

    @login_manager.user_loader
    def load_user(username):
        if username == ADMIN_USER.username:
            return ADMIN_USER
        else:
            return None

    login_manager.setup_app(app)
예제 #19
0
파일: server.py 프로젝트: philloidin/wok
    def _init_flask(self, app):
        """
		Initialize the Flask application. Override *_create_flask_app()* to use another class.
		"""

        self.logger.info("Initializing Flask application ...")

        app.wok = self

        app.logger_name = "web"

        app.teardown_request(self._teardown_request)

        login_manager = LoginManager()
        login_manager.init_app(self.app)
        login_manager.user_loader(self._load_user)
        login_manager.login_message = "Please sign in to access this page."
        #self.login_manager.anonymous_user = ...

        app.register_blueprint(core.bp, url_prefix="/core")
예제 #20
0
	def _init_flask(self, app):
		"""
		Initialize the Flask application. Override *_create_flask_app()* to use another class.
		"""

		self.logger.info("Initializing Flask application ...")

		app.wok = self

		app.logger_name = "web"

		app.teardown_request(self._teardown_request)

		login_manager = LoginManager()
		login_manager.init_app(self.app)
		login_manager.user_loader(self._load_user)
		login_manager.login_message = "Please sign in to access this page."
		#self.login_manager.anonymous_user = ...

		app.register_blueprint(core.bp, url_prefix="/core")
예제 #21
0
파일: auth.py 프로젝트: schu/bookmarks
    def __init__(self, app):
        lm = LoginManager()

        lm.login_view = '/login'
        lm.login_message = 'Login required.'
        lm.login_message_category = 'error'
        lm.anonymous_user = AnonymousUser

        lm.setup_app(app)

        @lm.user_loader
        def user_loader(id):
            try:
                id = int(id)
                user = User.query.filter_by(id=id).first()
            except:
                return None
            return user

        app.login_manager = lm
        app.auth_handler = self.auth_handler
예제 #22
0
파일: auth.py 프로젝트: schu/bookmarks
    def __init__(self, app):
        lm = LoginManager()

        lm.login_view = '/login'
        lm.login_message = 'Login required.'
        lm.login_message_category = 'error'
        lm.anonymous_user = AnonymousUser

        lm.setup_app(app)

        @lm.user_loader
        def user_loader(id):
            try:
                id = int(id)
                user = User.query.filter_by(id=id).first()
            except:
                return None
            return user

        app.login_manager = lm
        app.auth_handler = self.auth_handler
예제 #23
0
def init(app):
    lm = LoginManager()
    lm.login_view = "auth.login"
    lm.login_message = False
    lm.user_callback = admins_service.get
    lm.setup_app(app)

    @app.before_request
    def before_request():
        # if user is logged in or no endpoint is set allow the request
        if current_user.is_authenticated():
            return

        endpoint = request.endpoint or ''

        criteria = [
            endpoint.find('auth.login') == -1,
            endpoint.find('static') == -1
        ]

        if all(criteria):
            return app.login_manager.unauthorized()
예제 #24
0
def configure_login_manager(app):
    login_manager = LoginManager()
    # 指定登陆页面的视图
    login_manager.login_view = 'index.login'
    login_manager.login_message = u'请登录系统之后进行操作'
    login_manager.login_message_category = "info"

    def init_app(_app):
        login_manager.init_app(_app)

    # 回调函数返回User实例
    @login_manager.user_loader
    def load_customer(customer_id):

        with get_session() as db_session:
            customer = db_session.query(Customer).get(customer_id)
            if customer:
                return customer
            else:
                return None

    init_app(app)
예제 #25
0
def configure_login_manager(app):
    login_manager = LoginManager()
    # 指定登陆页面的视图
    login_manager.login_view = 'index.login'
    # 会话的保护程度
    login_manager.session_protection = "basic"
    login_manager.login_message = u'请登录系统之后进行操作'
    login_manager.login_message_category = "info"

    def init_app(_app):
        login_manager.init_app(_app)

    # 回调函数返回User实例
    @login_manager.user_loader
    def load_user(user_id):

        with get_session() as db_session:
            user = db_session.query(User).get(user_id)
            if user:
                return user
            else:
                return None

    init_app(app)
예제 #26
0
    return jsonify(posts=list(platforms))


@app.route('/get_challenges')
def get_challenges():
    challenges = models.Challenge.query.all()
    return jsonify(challenges=list(challenges))


################################################################################
##########################         LOGIN         ###############################

login_manager = LoginManager()
login_manager.setup_app(app)
login_manager.login_view = "login"
login_manager.login_message = u"Please log in to access this page."
login_manager.refresh_view = "reauth"


@login_manager.user_loader
def load_user(id):
    return users.USERS.get(int(id))


@app.route('/admin_page', methods=['GET', 'POST'])
@login_required
def admin():
    form_event_add = AddEventForm()
    form_event_edit = EditEventForm()
    form_project_add = AddProjectForm()
    if request.method == 'GET':
예제 #27
0
# -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager


app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
lm=LoginManager()
lm.init_app(app)
lm.login_view = 'login_page'
lm.login_message = u"Для доступа к странице необходимо авторизоваться"
from app import views, models
예제 #28
0
def is_email(email):
    """Validate that an email is syntactially correct."""
    if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
        return False
    return True

from shortener.users.views import users_blueprint
from shortener.links.views import links_blueprint

app.register_blueprint(users_blueprint, url_prefix='/users')
app.register_blueprint(links_blueprint)


from shortener.models import User

login_manager.login_view = "users.login"
login_manager.login_message = "Please login to view that page."


@app.errorhandler(404)
def page_not_found(e):
    """Render 404 page template."""
    return render_template('404.html'), 404


@login_manager.user_loader
def load_user(user_id):
    """Load the logged in user for the LoginManager."""
    return User.query.filter(User.id == int(user_id)).first()
예제 #29
0
# coding: UTF-8
from __future__ import absolute_import

from flask import Blueprint, redirect, url_for, request, render_template, flash
from flask.ext.wtf import Form
from flask.ext.login import LoginManager, login_user, current_user, logout_user
from wtforms import PasswordField, TextField, validators

from hotsite.models import Aluno
from hotsite.base import db

bp = Blueprint('auth', __name__)

login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.login_message = 'Por favor, entre com o seu RA e senha do portal'


@login_manager.user_loader
def load_user(user_id):
    user = Aluno.query.filter_by(ra=user_id).first()
    return user


@bp.route("/login/", methods=["GET", "POST"])
def login():
    if not current_user.is_anonymous:
        return redirect(request.args.get('next') or url_for("palestras.index"))
    form = LoginForm()
    if form.validate_on_submit():
        user = form.user
예제 #30
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import basedir
import os

app = Flask(__name__)

app.config.from_object('config')

db = SQLAlchemy(app)

lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
lm.login_message = 'Login completato con successo'

# This just tells Jinja2 to expose our class as a global variable to all templates.
from .momentjs import momentjs

app.jinja_env.globals['momentjs'] = momentjs

from flask.ext.mail import Mail

mail = Mail(app)

# ********************* Debugging tools *********************************
# Send an email in case of Internal Server Errors
# Remember to set the email server on, when testing:  python -m smtpd -n -c DebuggingServer localhost:25
from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD
예제 #31
0
from flask.ext.mail import Mail
from flask.ext.migrate import Migrate, MigrateCommand
from praw.handlers import MultiprocessHandler

# handler needs to be started separately by running praw-multiprocess
# this allows the handler to adhere to rate limit of reddit API
# see r and bot below to enable in production.

handler = MultiprocessHandler()

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_app(app)
lm.login_message = None
mail = Mail(app)
Bootstrap(app)
lm.login_view = 'login'
migrate = Migrate(app, db)

if not app.debug:
    import logging
    from logging.handlers import RotatingFileHandler
    file_handler = RotatingFileHandler(app.config['LOGFILE'], maxBytes = 1024*1024)
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

bot = praw.Reddit(app.config['REDDIT_USER_AGENT'], handler=handler)
#bot.login(app.config['REDDIT_USERNAME'], app.config['REDDIT_PASSWORD'])
예제 #32
0
from flask.ext.login import LoginManager

# Start flask
app = Flask(__name__)

# Load Conig
app.config.from_object('config')

# Connect with database
db = SQLAlchemy(app)

# Initiate LoginManager
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'index'
lm.login_message = 'Please log in to access this page.'

# Import Blueprints
from .views.login import login
from .views.admin import admin
from .views.home import home
from .views.studentroom import studentroom
from .views.questionserver import questionserver

# Register Blueprints
app.register_blueprint(login)
app.register_blueprint(admin)
app.register_blueprint(home)
app.register_blueprint(studentroom)
app.register_blueprint(questionserver)
예제 #33
0
    login_required, login_user, logout_user, current_user

from flask_wtf import Form
from wtforms import StringField, PasswordField, \
    BooleanField
from wtforms.validators import DataRequired

from config import config

__version__ = "0.1.0"
__author__ = "Brijesh Bittu <*****@*****.**>"
"""User login management."""
login_manager = LoginManager()
login_manager.session_protection = "strong"
login_manager.login_message_category = "info"
login_manager.login_message = "You need to login."
login_manager.login_view = "login"
"""App setup."""
app = Flask(__name__,
            template_folder="../templates/",
            static_url_path="/static",
            static_folder="../templates/static/")
app.wsgi_app = ProxyFix(app.wsgi_app)
db = SQLAlchemy(app)
app.config.from_object(config["default"])
login_manager.init_app(app)
cache = Cache(config={"CACHE_TYPE": "simple"})
cache.init_app(app)
logger = logging.Logger(config["default"].APP_NAME)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stdout))
예제 #34
0
try:
    from conf import *
except:
    pass

app = Flask(__name__, static_path = '/upvideos_static', static_url_path = '/upvideos_static')
app.config['UPLOAD_FOLDER'] = UPLOADED_FILES_DEST
app.config['URL'] = APP_URL
app.config['SECRET_KEY'] = SECRET_KEY

UPLOADED_FILES_ALLOW = ('ogg', 'ogv', 'webm', 'mp4')
videos = UploadSet('videos', UPLOADED_FILES_ALLOW)
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.login_message = 'Necess&aacute;rio efetuar o login.'
login_manager.setup_app(app)

#---------------------------------------------------------------------


@app.route("/secret")
@fresh_login_required
def secret():
    return render_template("secret.html")


class User(UserMixin):

    def __init__(self, id, senha, nome=''):
        self.usuarioid = id
예제 #35
0
# -*- coding: utf-8 -*-
import datetime

from bson import ObjectId
from flask import Blueprint, render_template, request, flash, redirect, url_for
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, UserMixin, login_user, login_required, logout_user

from database import mongo
from forms.login import LoginForm
from forms.signin import SigninForm


login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.login_message = u'Merci de vous identifier.'
bcrypt = Bcrypt()
auth = Blueprint('auth', __name__)


@auth.route("/login", methods=['GET', 'POST'])
def login():
    form = LoginForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            mongo_user = mongo.db.users.find_one({'email': form.email.data})
            if mongo_user and bcrypt.check_password_hash(mongo_user['password'], form.password.data):
                if login_user(User(mongo_user), remember=form.remember_me.data):
                    mongo_user['last_login'] = datetime.datetime.utcnow()
                    mongo.db.users.save(mongo_user)
예제 #36
0
# coding: utf-8
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.mongoengine import MongoEngine
from flask.ext.login import LoginManager
from config import config

bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = MongoEngine()
login_manager = LoginManager()
login_manager.login_message = u'请登录喵!'
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)  # ???

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
예제 #37
0
#! usr/bin/python
#  -_-  coding:utf-8 -_-


from flask import Flask, render_template, flash, redirect, url_for, request
from flask.ext.script import Manager
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from flask.ext.login import LoginManager

db = SQLAlchemy()

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'admin.login'
login_manager.login_message = u"欢迎登陆,sugarguo制作 flask-login_DEMO!"


def create_app(config_name):
    app = Flask(__name__)#, static_url_path='/app/static')
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)    
    
    db.init_app(app)
    login_manager.init_app(app)
    
    return app
예제 #38
0
bcrypt = Bcrypt(app)
# flask login enabled
login_manager = LoginManager()
login_manager.init_app(app)

#config
app.config.from_object('config.DevConfig')

# SQLAlchemy object - povezava z bazo
db = SQLAlchemy(app)

from models import *
from project.users.views import users_blueprint
from project.home.views import home_blueprint
from project.blog.views import blog_blueprint

app.register_blueprint(users_blueprint)
app.register_blueprint(home_blueprint)
app.register_blueprint(blog_blueprint)

# katera funkcija se ukvarja z logiranjem uporabnikov flask-login
from models import User
login_manager.login_view = 'users.login'
login_manager.login_message = 'Za ogled te strani je obvezna prijava.'


# pridobi uporabnika iz baze in shrani v cookie flask -login obvezno
@login_manager.user_loader
def load_user(user_id):
    return User.query.filter(User.id == int(user_id)).first()
예제 #39
0
from flask.ext.mail import Mail
from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD
from flask_bootstrap import Bootstrap
from momentjs import momentjs
from flask.ext.babel import Babel
from flask.ext.babel import lazy_gettext
from flask.ext.babel import gettext

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
# lm.login_message = lazy_gettext('Please log in to access this page.')
lm.login_message = gettext('Please log in to access this page.')
oid = OpenID(app, os.path.join(basedir, 'tmp'))
mail = Mail(app)
Bootstrap(app)
babel = Babel(app)

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,
                               'microblog failure', credentials)
    mail_handler.setLevel(logging.ERROR)
예제 #40
0
파일: app.py 프로젝트: giveme168/braavos
from flask import g, request, url_for, redirect, render_template
from flask.ext.login import LoginManager, current_user

from factory import create_app
from urls import register_blueprint
from config import config_object

from flask_debugtoolbar import DebugToolbarExtension
from models.user import UserHandBook
from models.account.data import Notice, PersonNotice

app = create_app(config_object)
# toolbar = DebugToolbarExtension(app)

login_manager = LoginManager()
login_manager.login_message = None
login_manager.init_app(app)
login_manager.login_view = "user.login"


def page_recipe(pages, adjacent_pages=3):
    paginator = pages.paginator
    page_numbers = [n for n in range(
        pages.number - adjacent_pages, pages.number + adjacent_pages + 1) if n > 0 and n <= paginator.num_pages]

    return page_numbers

app.jinja_env.filters['page_recipe'] = page_recipe


@app.route('/email')
예제 #41
0
# _*_ coding:utf-8 _*_

from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.redis import FlaskRedis
from flask.ext.bootstrap import Bootstrap
from flask.ext.login import LoginManager

__all__ = ['db', 'redis']

db = SQLAlchemy()
redis = FlaskRedis()
bootstrap = Bootstrap()
loging_manager = LoginManager()
loging_manager.session_protection = 'strong'
loging_manager.login_view = 'admin.login'
loging_manager.login_message = u'请登入帐号再进行下一步操作!'
예제 #42
0
from flask.ext.login import LoginManager
from factories import Jinja2
from config import config
from flask.ext.cache import Cache
from flask.ext.cors import CORS
from app._flask import make_response, extends_db

bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
jinja2 = Jinja2()
login_manager = LoginManager()
login_manager.session_protection = None
login_manager.login_view = 'main.login'
login_manager.login_message = "请登录后再访问该页面"
cache = Cache()

def create_app(config_name):
    Flask.make_response = make_response
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    extends_db(db)
    jinja2.init_app(app)
    login_manager.init_app(app)
    
예제 #43
0
파일: login.py 프로젝트: radonlab/papery
# -*- coding: utf-8 -*-
"""
Copyright (C) 2015, Radmon.
Use of this source code is governed by the MIT license that can be
found in the LICENSE file.
"""

from flask.ext.login import LoginManager
from ..auth.models import User

login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.login_message = 'Please log in first.'


@login_manager.user_loader
def load_user(user_id):
    user = User.query.get(int(user_id))
    return user


def init_app(app):
    login_manager.init_app(app)
예제 #44
0
from flask.ext.openid import OpenID
from config import basedir
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from config import ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
mail = Mail(app)
babel = Babel(app)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
login_manager.login_message = lazy_gettext('Please log in to access this page.')
oid = OpenID(app, os.path.join(basedir, 'tmp'))

from app import views, models

app.jinja_env.globals['momentjs'] = Momentjs

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, 'microblog failure', credentials)
예제 #45
0
import logging
from logging.handlers import TimedRotatingFileHandler
from logging import getLogger

UPLOAD_FOLDER = '/static/imagenes'


app = Flask(__name__)
api = Api(app)

login_manager = LoginManager()

login_manager.init_app(app)
login_manager.login_view = "login"
login_manager.login_message = "Necesitas estar logueado para acceder a esa pagina"

@login_manager.user_loader
def load_user(user_id):
	return adapter.get_user_by_id(user_id)

@app.errorhandler(400)
def page_not_found(e):
    return render_template('login.html'),400

app.config.from_object('config')
 
app.config['SECURITY_POST_LOGIN'] = '******'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

app.config['MAIL_SERVER']='smtp.gmail.com'
예제 #46
0
# encoding=utf-8
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.bootstrap import Bootstrap

db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'main.login'
# use encoding=utf-8
login_manager.login_message = u'请先登录!'
login_manager.login_message_category = "info"
bs = Bootstrap()


def create_app(config_object):
    app = Flask(__name__)
    app.config.from_object(config_object)

    db.init_app(app)
    login_manager.init_app(app)
    bs.init_app(app)
    #avoid circular import.
    from app.views import main

    app.register_blueprint(main)

    return app

예제 #47
0
파일: __init__.py 프로젝트: opatut/mini
app = Flask(__name__)
app.config.from_pyfile('../config.py', silent=True)

db = SQLAlchemy(app)

cache = Cache(app, config=dict(CACHE_TYPE='simple'))

mail = Mail(app)

Markdown(app, safe_mode="escape")

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "core.login"
login_manager.login_message = u"Please log in to show this page."
login_manager.login_message_category = "warning"
login_manager.anonymous_user = AnonymousUser

access = AccessControl(current_user)

from mini.filters import *
from mini.forms import *
from mini.models import *
from mini.views import *

@app.errorhandler(404)
@app.errorhandler(403)
@app.errorhandler(500)
@app.errorhandler(501)
def error(error):
예제 #48
0
from sched.models import Appointment, Base, User

app = Flask(__name__)
app.config.from_object(config)

# Use Flask-SQLAlchemy for its engine and session configuration. Load the
# extension, giving it the app object, and override its default Model class
# with the pure SQLAlchemy declarative Base class.
db = SQLAlchemy(app)
db.Model = Base

# Use Flask-Login to track the current user in Flask's session.
login_manager = LoginManager()
login_manager.setup_app(app)
login_manager.login_view = 'login'
login_manager.login_message = 'Please log in to see your appointments.'


@login_manager.user_loader
def load_user(user_id):
    """Hook for Flask-Login to load a User instance from a user ID."""
    return db.session.query(User).get(user_id)


# Load custom Jinja filters from the `filters` module.
filters.init_app(app)

# Setup logging for production.
if not app.debug:
    app.logger.setHandler(logging.StreamHandler())  # Log to stderr.
    app.logger.setLevel(logging.INFO)
예제 #49
0
from flask import Flask
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__, instance_relative_config=True)

app.config.from_object('config')
app.config.from_pyfile('config.py')

db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
toolbar = DebugToolbarExtension(app)

from models import Employee

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view =  'login'
login_manager.login_message = 'Your session has expired, login again.'
login_manager.login_message_category = 'info'

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

from . import views
예제 #50
0
import config
from flask.ext.login import LoginManager
from flask.ext.moment import Moment
from flask.ext.mail import Mail

SECRET_KEY = 'hard to guess'

app = Flask(__name__)
app.config.from_object(config)
bootstrap = Bootstrap(app)
moment = Moment(app)
mail = Mail(app)
login_manager = LoginManager(app)
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'
login_manager.login_message = u'请先登录'
db = SQLAlchemy(app)
from model import Permission


@app.context_processor
def inject_permissions():
    return dict(Permission=Permission)


from views import *

if __name__ == '__main__':
    app.run(debug=True)

# from flask import Flask
예제 #51
0
#coding=utf-8
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
import sys,os
sys.path.append('..')
import config

app=Flask(__name__)
app.config.from_object('config')
app.config['avatar_dir']=os.path.join(config.basedir,'app','static','avatar')
db=SQLAlchemy(app)

lm=LoginManager()
lm.init_app(app)
lm.login_view='login'
lm.login_message=u'请先登录'

from app import views,models
예제 #52
0
파일: login.py 프로젝트: kurohai/colord
from flask.ext.login import LoginManager
from flask.ext.login import login_user
from flask.ext.login import login_required
from flask.ext.login import logout_user
from flask.ext.login import AnonymousUserMixin
from flaskapp import flasktemplate


class Anonymous(AnonymousUserMixin):
    def __init__(self):
        self.username = '******'
        self.name = 'Guest'


login_manager = LoginManager()
login_manager.init_app(flasktemplate)
login_manager.login_view = '{app}.login'.format(app=appnamed)
login_manager.login_message = 'Please log in.'
login_manager.anonymous_user = Anonymous


@login_manager.user_loader
def load_user(user_id):
    """Hook for Flask-Login to load a User instance from a user ID."""
    return session.query(User).get(user_id)


login_manager.anonymous_user = Anonymous
예제 #53
0
from flask.ext.login import LoginManager
from .models import User

login_manager = LoginManager()


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


login_manager.login_view = 'user.login'
login_manager.login_message = 'Login untuk mengakses link ini'
if app.config.get('BASIC_AUTH_USERNAME'):
    app.config['BASIC_AUTH_FORCE'] = True
    basic_auth = BasicAuth(app)

# Sentry exception reporting
if 'SENTRY_DSN' in os.environ:
    sentry = Sentry(app, dsn=os.environ['SENTRY_DSN'])

app.logger.debug("\nConfiguration\n%s\n" % app.config)

# import and register auth blueprint
from .auth.views import auth
app.register_blueprint(auth)
login_manager.login_view = 'auth.login'
login_manager.login_message = ''

from .relationship.views import relationship
app.register_blueprint(relationship)

def health(self):
    try:
        with self.engine.connect() as c:
            c.execute('select 1=1').fetchall()
            return True, 'DB'
    except:
        return False, 'DB'

@app.context_processor
def asset_path_context_processor():
    return {
예제 #55
0
파일: __init__.py 프로젝트: v2up/queyue
from flask.ext.mail import Mail
from flask.ext.login import LoginManager    #登录管理
from flask.ext.moment import Moment

from config import config	#不同的配置,不同的运行模式

import os

bootstrap = Bootstrap()
db = SQLAlchemy()
migrate = Migrate()
mail = Mail()
login_manager = LoginManager()
login_manager.session_protection = 'strong' #登录保护等级
login_manager.login_view = 'auth.login'
login_manager.login_message = '登录后方可访问'
login_manager.login_message_category = "alert-warning"
moment = Moment()

def create_app(config_name):
    '''工厂函数'''
    app = Flask(__name__)	#当前目录为根目录
    app.config.from_object(config[config_name])	#读取配置对象
    config[config_name].init_app(app)	#自己实现的staticmethod

    # 文件上传配置
    app.config['UPLOADS_DEFAULT_DEST'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads/')    #F:\queyue\qy\uploads
    app.config['UPLOADS_DEFAULT_URL'] = 'http://127.0.0.1:5000/uploads/'

    bootstrap.init_app(app)
    db.init_app(app)
예제 #56
0
파일: core.py 프로젝트: rkyymmt/pybossa
    log_level = app.config.get('LOG_LEVEL', logging.WARN)
    if log_file_path:
        file_handler = RotatingFileHandler(log_file_path)
        file_handler.setFormatter(Formatter(
            '%(name)s:%(levelname)s:[%(asctime)s] %(message)s '
            '[in %(pathname)s:%(lineno)d]'
            ))
        file_handler.setLevel(log_level)
        app.logger.addHandler(file_handler)
        logger = logging.getLogger('pybossa')
        logger.setLevel(log_level)
        logger.addHandler(file_handler)

login_manager = LoginManager()
login_manager.login_view = 'account.signin'
login_manager.login_message = u"Please sign in to access this page."
app = create_app()


#toolbar = DebugToolbarExtension(app)
db = SQLAlchemy(app)
mail = Mail(app)
signer = URLSafeTimedSerializer(app.config['ITSDANGEORUSKEY'])
if app.config.get('SENTRY_DSN'):
    sentr = Sentry(app)

babel = Babel(app)


@babel.localeselector
def get_locale():
예제 #57
0
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, AnonymousUser
from flask.ext.oauth import OAuth
from allangles.middleware import MethodRewriteMiddleware

app = Flask(__name__)
app.config.from_object('allangles.configuration')
app.wsgi_app = MethodRewriteMiddleware(app.wsgi_app)

oauth = OAuth()
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.anonymous_user = AnonymousUser
login_manager.login_view = 'login'
login_manager.login_message = u'Please log in to access this page'
@login_manager.user_loader
def load_user(id):
    from allangles.models import User
    return User.query.filter_by(id=id).first()
login_manager.setup_app(app)

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=os.environ.get('FB_API_KEY'),
    consumer_secret=os.environ.get('FB_SECRET'),
    request_token_params={'scope': 'email'}
)