Ejemplo n.º 1
0
def init_login_backend():
    global authenticate, auth_ldap
    kind = app.config.get('LOGIN_BACKEND', 'ldap')
    if kind == 'ldap':
        ldap_manager = LDAP3LoginManager(app)
        authenticate = ldap_authenticate
        auth_ldap = True
    elif kind == 'demo':
        authenticate = demo_authenticate
    else:
        raise Exception(f'Unsupported login backend: {kind}')
Ejemplo n.º 2
0
    def testLdap(self):
        """
        测试ldap认证模块
        :return: 
        """
        from flask_ldap3_login import LDAP3LoginManager

        config = dict()

        # Setup LDAP Configuration Variables. Change these to your own settings.
        # All configuration directives can be found in the documentation.

        # Hostname of your LDAP Server
        config['LDAP_HOST'] = 'ad.mydomain.com'

        # Base DN of your directory
        config['LDAP_BASE_DN'] = 'dc=mydomain,dc=com'

        # Users DN to be prepended to the Base DN
        config['LDAP_USER_DN'] = 'ou=users'

        # Groups DN to be prepended to the Base DN
        config['LDAP_GROUP_DN'] = 'ou=groups'

        # The RDN attribute for your user schema on LDAP
        config['LDAP_USER_RDN_ATTR'] = 'cn'

        # The Attribute you want users to authenticate to LDAP with.
        config['LDAP_USER_LOGIN_ATTR'] = 'mail'

        # The Username to bind to LDAP with
        config['LDAP_BIND_USER_DN'] = None

        # The Password to bind to LDAP with
        config['LDAP_BIND_USER_PASSWORD'] = None

        # Setup a LDAP3 Login Manager.
        ldap_manager = LDAP3LoginManager()

        # Init the mamager with the config since we aren't using an app
        ldap_manager.init_config(config)

        # Check if the credentials are correct
        response = ldap_manager.authenticate('username', 'password')
        print(response.status)
Ejemplo n.º 3
0
def init_app(app):

    login_manager = LoginManager(app)
    login_manager.anonymous_user = models.AnonymousUser
    ldap_manager = LDAP3LoginManager(app)

    @ldap_manager.save_user
    def save_user(dn, username, data, memberships):
        user = models.User.get(username)
        return user

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

    # Set up sanity checks.
    from . import sanity
    getattr(app, 'sanity_check_modules', []).append(sanity)
Ejemplo n.º 4
0
def make_app(config=None):
    if not config:
        config = 'config.Config'
    app = Flask(__name__)
    app.config.from_object(config)
    app.config.from_envvar('KABUTO_CONFIG', silent=True)
    for key in OVERRIDES:
        read_config(app.config, key)

    api = restful.Api(app)
    login_manager = LoginManager(app)
    ldap_manager = None
    if app.config['LDAP_HOST']:
        ldap_manager = LDAP3LoginManager(app)
    db = SQLAlchemy(app)
    bcrypt = Bcrypt(app)
    if app.config['SENTRY_DSN']:
        Sentry(app)
    else:
        print("sentry not enabled !")
    return app, api, login_manager, ldap_manager, db, bcrypt
Ejemplo n.º 5
0
def create_app(port):
    app = Flask(__name__,
                static_folder='../static/',
                template_folder='../templates/')
    config = get_config()
    app.config['SQLALCHEMY_DATABASE_URI'] = config.get(
        'DATABASE_READONLY', 'remoteurl').format(port)
    app.config['SQLALCHEMY_ECHO'] = bool(
        int(config.get('DATABASE_READONLY', 'echo')))
    app.config['SECRET_KEY'] = 'testsecretkeyalsdkjf'
    db.init_app(app)
    Bootstrap(app)
    # Add the ldap config information from the .ini file.
    ldapconf = get_ldap_config()
    app.config.update(ldapconf)

    # Login Manager: set up ldap as well.
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    ldap_manager = LDAP3LoginManager(app)

    from eaodb.blueprints.user_model import create_user

    @login_manager.user_loader
    def load_user(user_id):
        return create_user(user_id)

    app.register_blueprint(auth)
    app.register_blueprint(project, url_prefix='/project')
    app.register_blueprint(obs, url_prefix='/obs')
    app.register_blueprint(ops, url_prefix='/ops')

    @app.route('/')
    def home_page():
        return redirect(url_for('ops.ops_home'), code=303)

    return app
Ejemplo n.º 6
0
app.config['LDAP_HOST'] = 'ldap://dirxml.prpr.mpf.mp.br'
# Base DN of your directory
app.config['LDAP_BASE_DN'] = 'o=mpf'
# Users DN to be prepended to the Base DN
app.config['LDAP_USER_DN'] = 'ou=cwb,ou=prpr'
# The RDN attribute for your user schema on LDAP
app.config['LDAP_USER_RDN_ATTR'] = 'cn'
# The Attribute you want users to authenticate to LDAP with.
app.config['LDAP_USER_LOGIN_ATTR'] = 'mail'
# The Username to bind to LDAP with
app.config['LDAP_BIND_USER_DN'] = None
# The Password to bind to LDAP with
app.config['LDAP_BIND_USER_PASSWORD'] = None

login_manager = LoginManager(app)              # Setup a Flask-Login Manager
ldap_manager = LDAP3LoginManager(app)          # Setup a LDAP3 Login Manager.

# Create a dictionary to store the users in when they authenticate, memory
users = {}

#pagina inexistente (correção)
@app.errorhandler(404)
def not_found(e):
    # return ('pagina de erro mpf')
    if current_user.is_authenticated:
        return render_template('erro.html')
    else:
        return redirect(url_for('login'))

# Declare an Object Model for the user, and make it comply with the
# flask-login UserMixin mixin.
Ejemplo n.º 7
0
from app.core import FlaskApi, ApiException
from app.utils import JSONEncoder
from .utils.mixins import Anonymous

version_ = (1, 8, 0)
__version__ = '.'.join(map(str, version_[0:2]))
__release__ = '.'.join(map(str, version_))


db = SQLAlchemy()
mail = Mail()
login_manager = LoginManager()
celery = Celery(__name__, broker=Config.BROKER_URL)
jsonschema = JsonSchema()
gpg = GPG()
ldap3_manager = LDAP3LoginManager()
migrate = Migrate()
vxstream = VxStream()
nessus = Nessus()
fireeye = FireEye()


def create_app(config_name):
    app = FlaskApi(__name__)
    app.config.from_object(config[config_name])
    if app.config['TESTING']:
        app.config.from_envvar('DO_TESTING_CONFIG', silent=True)
    else:
        app.config.from_envvar('DO_LOCAL_CONFIG', silent=True)
    app.json_encoder = JSONEncoder
    app.log = app.logger
Ejemplo n.º 8
0
    JWT_ACCESS_TOKEN_EXPIRES = int(
        os.environ.get("JWT_ACCESS_TOKEN_EXPIRES", 15))


app = Flask(__name__)
CORS(app)

app.config.from_envvar("FLASK_CONFIG_FILE")
app.config.from_object(Config)

# Initialise the JSON Web Token Manager.
jwt = JWTManager()
jwt.init_app(app)

# Initialise the ldap manager using the settings read into the flask app.
ldap_manager = LDAP3LoginManager(app)


@app.route("/")
def index():
    return "JWT token generation service authenticating against LDAP back end"


@app.route("/public_key")
def public_key():
    return app.config["JWT_PUBLIC_KEY"]


@app.route("/token", methods=["POST"])
def token():
    data = request.get_json()
Ejemplo n.º 9
0
def create_app():
    a = cms.Acano(setting.CMS_IP_ADDRESS + ":" + setting.CMS_PORT,
                  setting.CMS_USERNAME, setting.CMS_PASSWORD)

    ldapServers = a.get_ldap_servers()
    ldapSources = a.get_ldap_sources()

    print(ldapServers)
    print(ldapSources)

    app = Flask(__name__)

    # Hostname of your LDAP Server
    app.config['LDAP_HOST'] = ldapServers["ldapServers"]["ldapServer"][0][
        'address'] + ":" + ldapServers["ldapServers"]["ldapServer"][0][
            'portNumber']

    # The Username to bind to LDAP with
    app.config['LDAP_BIND_USER_DN'] = ldapServers["ldapServers"]["ldapServer"][
        0]['username']

    # The Password to bind to LDAP with
    app.config['LDAP_BIND_USER_PASSWORD'] = setting.LDAP_PASSWORD

    # Base DN of your directory
    app.config['LDAP_BASE_DN'] = ldapSources["ldapSources"]["ldapSource"][0][
        'baseDn']

    # The RDN attribute for your user schema on LDAP
    app.config['LDAP_USER_RDN_ATTR'] = 'cn'

    # The Attribute you want users to authenticate to LDAP with.
    app.config['LDAP_USER_LOGIN_ATTR'] = 'sAMAccountName'

    app.config['LDAP_USER_SEARCH_SCOPE'] = 'SUBTREE'

    app.config['SECRET_KEY'] = 'thisisthesecretkey'

    app.config['DEBUG'] = True

    users = {}

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

    ldap_manager = LDAP3LoginManager(app)

    from .models import User

    @login_manager.user_loader
    def load_user(id):
        if id in users:
            return users[id]
        return None

    @ldap_manager.save_user
    def save_user(dn, username, data, memberships):
        user = User(dn, username, data)
        users[dn] = user
        return user

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

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

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

    return app
Ejemplo n.º 10
0
from flask import Flask
from flask_ldap3_login import LDAP3LoginManager
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_executor import Executor
from config import Config
from ConsulClient import ConsulClient
from flask_apscheduler import APScheduler
users = {}

login = LoginManager()
login.login_view = 'auth.login'
login.login_message = 'Please log in with your LDAP account to access this page'
ldap = LDAP3LoginManager()
bootstrap = Bootstrap()
consul_client = ConsulClient()
executor = Executor()
scheduler = APScheduler()


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

    login.init_app(app)
    ldap.init_app(app)
    bootstrap.init_app(app)
    consul_client.init_app(app)
    executor.init_app(app)

    from app.models import models
Ejemplo n.º 11
0
def verify_password(username_or_token, password):
    # 首先验证token
    # print('verify_password')
    # ldap = current_app.config.get('LDAP')
    ldap_manager = LDAP3LoginManager()
    ldap_manager.init_config(current_app.config.get('LDAP'))

    # response = ldap_manager.authenticate(username_or_token, password)
    # print(response.status)

    ldap = False
    if password == '':
        print username_or_token
        if session.get(username_or_token):
            print('token:', session.get(username_or_token))
            # return True
        else:
            print('unable get session')
            # return False

        data, token_flag = Users.verify_auth_token(username_or_token)
        # data, token_flag = parse_token(username_or_token)
        if token_flag == 1:  # 认证成功
            print('verify success')

            g.username = data['username']
            print(g.username)

        elif token_flag == 2:  # token 超时
            # pass
            return False

        elif token_flag == 3:  # token 解析失败
            return False
    else:
        user = Users.query.filter_by(username=username_or_token).first()
        # g.user_name = username_or_token
        # print(user)
        # print('g.user')
        if user:
            if not user.verify_password(password):
                # print('passwrd error')
                return False
            else:
                # print('password v')
                g.username = username_or_token
                # return True
        elif ldap:
            ldap_manager = LDAP3LoginManager()
            ldap_manager.init_config(current_app.config.get('LDAP'))

            response = ldap_manager.authenticate(username_or_token, password)
            print(response)

        else:
            return False
        login_user(user)
    # user = User.verify_auth_token(username_or_token)
    # if not user:
    #     # 然后再验证用户名和密码
    #     user = User.query.filter_by(username=username_or_token).first()
    #     if not user or not user.verify_password(password):
    #         return False
    # g.user = user
    return True
Ejemplo n.º 12
0
from apifairy import APIFairy
from flask_marshmallow import Marshmallow
from flask import Flask, redirect
from werkzeug.middleware.proxy_fix import ProxyFix
import pathlib
import os
import datetime
import sys

__version__ = '0.2.0'

logs = LogSetup()
db = SQLAlchemy()
migrate = Migrate()
login_mgr = LoginManager()
ldap_mgr = LDAP3LoginManager()
principal = Principal()
cache = Cache()
flask_statics = FlaskStaticDigest()
apifairy = APIFairy()
ma = Marshmallow()
csrf = CSRFProtect()
# celery = Celery(__name__)
# Breadcrumbs is a subclass of flask_menu.Menu
menu = Menu()


def create_app(config='newswriter.config.Config'):
    """Inicializar la aplicación"""
    if getattr(sys, 'frozen', False):
        # para pyinstaller