示例#1
0
def register(app):
    app.add_url_rule("/api/auth_token", view_func=AuthToken.as_view("auth_token"))
    app.add_url_rule("/api/logout", view_func=Logout.as_view("logout"))

    app.secret_key = app.config.get("SECRET_KEY")
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.user_loader(__user_loader)
示例#2
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(flask_config)
    app.secret_key = os.urandom(24)

    app.register_blueprint(users_app, url_prefix='/users')
    app.register_blueprint(projects_app, url_prefix='/projects')

    login_manager = LoginManager()
    login_manager.init_app(app)

    def flask_login_user_loader(user_id):
        return g.db.query(User).filter(User.id == user_id).first()
    login_manager.user_loader(flask_login_user_loader)

    return app
示例#3
0
from flask import Flask, render_template
from flask_login.login_manager import LoginManager

from models import Session, User, Post
from views import auth_app

app = Flask(__name__)
app.config.update(
    DEBUG=True,
    SECRET_KEY="topsecretkey1231231240dsdf",
)
app.register_blueprint(auth_app, url_prefix="/auth")

login_manager = LoginManager()
login_manager.init_app(app)


@login_manager.user_loader
def load_user(user_id):
    return Session.query(User).filter_by(id=user_id).one_or_none()


@app.route("/", endpoint="index")
def index():
    return render_template("index.html")


@app.teardown_request
def remove_session(*args):
    Session.remove()
示例#4
0
from board_base import db_exception, app, db
from flask_login.utils import login_user, logout_user, current_user, login_required, login_fresh
from mylogger import logger
from db.user import User
from werkzeug.security import check_password_hash
from werkzeug.utils import redirect



auth_api = Blueprint("auth_api", __name__, url_prefix='/api')



#Flask-Login 모듈
login_manager = LoginManager()  # 로그인/로그아웃 관련 세션을 관리해주는 flask-login 모듈 객체 생성
login_manager.init_app(app)     # flask객체와 연동

#인증되지 않은 사용자가 @login_required 페이지 접속을 시도할 시 redirect할 페이지 설정
login_manager.login_view = 'auth_view.login'    
login_manager.login_message = "로그인이 필요합니다."

@login_manager.user_loader      # 세션에 저장된 ID에 해당하는 user객체를 반환하는 callback 메소드, 유효하지 않은 ID일 경우 None을 반환한다.
@db_exception
def load_user(id):
        logger.info("load_user(), session:"+str(session))

        cursor = db.get_conn().cursor()
        cursor.callproc('get_user_by_id', (id,))  # argument 1개일 때도 ,하나 붙여줘야 제대로 인식함.
        r = cursor.fetchall()
        cursor.close()
示例#5
0
def init(**kwargs):
    for k, v in kwargs.items():
        setattr(Config, k, v)

    app = Flask(__name__)
    db.init_db()
    sms = AliyunSms(app)
    Config.sms = sms
    Config.app = app

    app.add_template_global(str, 'str')
    app.secret_key = Config.secret_key
    app.wsgi_app = ProxyFix(app.wsgi_app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'authentication.login'

    if app.debug:
        stream_handle = logging.StreamHandler()
        stream_handle.setFormatter(logging.Formatter(Config.logging_fmt))
        stream_handle.setLevel(logging.INFO)
        app.logger.addHandler(stream_handle)

    file_handle = logging.FileHandler(Config.logging_path)
    file_handle.setFormatter(logging.Formatter(Config.logging_fmt))
    file_handle.setLevel(logging.WARNING)

    app.logger.addHandler(file_handle)

    @login_manager.user_loader
    def load_user(user_id):
        return db.User.query.filter_by(id=int(user_id)).first()

    @app.errorhandler(404)
    @monitor
    def not_found(error):
        Dangerous.add()
        return render_template("404.html"), 404

    @app.errorhandler(400)
    @monitor
    def not_found(error):
        Dangerous.add()

        return "贪玩", 400

    @app.before_request
    def load_current_user():
        g.user = current_user

    @app.teardown_request
    def remove_db_session(exception):
        db.db_session.remove()

    @app.route('/image/<imagep>')
    def get_image(imagep):
        try:
            path = str(Config.path / "sharh-static" / "static" / "images" / imagep)
            with open(path, 'rb') as image:
                return Response(image.read(), content_type="image/{}".format("png" if ".png" in imagep else
                                                                             "jpeg" if ".jpg" in imagep else
                                                                             "gif" if ".gif" in imagep else
                                                                             ""))
        except Exception as e:
            logging.log(logging.WARNING, e)
            return Response(render_template('404.html'))

    from rx_sharh.service.view import attendance
    from rx_sharh.service.view import group
    from rx_sharh.service.view import authentication
    from rx_sharh.service.view import schedule
    from rx_sharh.service.view import profile
    from rx_sharh.service.view import index

    app.register_blueprint(attendance.mod)
    app.register_blueprint(group.mod)
    app.register_blueprint(authentication.mod)
    app.register_blueprint(schedule.mod)
    app.register_blueprint(profile.mod)
示例#6
0
from flask_login import login_required, login_user
from flask_login.login_manager import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect

from file_mapping.asserts.ip2region import Ip2Region
from file_mapping.config import URL_PREFIX
from file_mapping.utils import NoServerHeaderFlask

app = NoServerHeaderFlask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
app.config['SESSION_COOKIE_PATH'] = f'{URL_PREFIX}/admin/'

csrf = CSRFProtect()
csrf.init_app(app)
db = SQLAlchemy(app)
loginManager = LoginManager()
loginManager.init_app(app)
ip2Region = Ip2Region(f'{app.root_path}/asserts/ip2region.db')

from file_mapping.models import Log, Rule
db.create_all()
from file_mapping import admin_views, index_views
示例#7
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
from flask_login.login_manager import LoginManager
#from flask_openid import OpenID
from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT
from config import MAIL_PASSWORD, MAIL_USERNAME

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(basedir, 'tmp'))

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), 
                               'noreply@'+MAIL_SERVER, ADMINS, 
示例#8
0
from flask_login import login_user, logout_user, login_required
from flask import Flask, redirect, url_for, render_template
from flask_graphql import GraphQLView
from flask_sqlalchemy import SQLAlchemy
from flask_dance.contrib.google import make_google_blueprint, google
from oauthlib.oauth2 import TokenExpiredError
from flask_cors import CORS

flask_app = Flask(__name__)
config_module = import_module(os.environ.get('CONFIG_MODULE',
                                             'backend.config'))
ConfigObject = getattr(config_module, 'ConfigObject')
flask_app.config.from_object(ConfigObject())
flask_app.debug = True
login_manager = LoginManager()
login_manager.init_app(flask_app)

db = SQLAlchemy(flask_app)

CORS(flask_app)


def init_app(app):
    from backend.schema import schema
    from backend.models import User

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

    google_bp = make_google_blueprint(scope=[