def login():
    """
    Function called when user logs in
    """
    if g.user:
        return redirect(url_for('index'))

    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        ldap_username = '******'+username+',ou=' + config.get('ldap', 'ou') + \
            ',' + config.get('ldap', 'base_dn')
        app.config['LDAP_USERNAME'] = ldap_username
        app.config['LDAP_PASSWORD'] = password
        ldap = LDAP(app)
        try:
            grp_members = ldap.get_group_members(
                group=config.get('ldap', 'group'))
            if ldap_username in grp_members:
                ldap.bind_user(username, password)
        except Exception:
            app.logger.warning('Login attempt failed for %s', username)
            return render_template('login.html')
        else:
            session['username'] = request.form['username']
            app.logger.info('User %s logged in', username)
            return redirect('/')

    return render_template('login.html')
Esempio n. 2
0
def init_ldap(app):
    app.config['LDAP_HOST'] = 'ad-crypto.epsi.intra'
    app.config['LDAP_BASE_DN'] = 'cn=Users,dc=epsi,dc=intra'
    app.config['LDAP_USERNAME'] = '******'
    app.config['LDAP_PASSWORD'] = '******'
    app.config['LDAP_USER_OBJECT_FILTER'] = '(sAMAccountName=%s)'
    return LDAP(app)
from flask import Flask
from flask_simpleldap import LDAP

from main.util.config import LDAPConfig

ldap = LDAP()


def create_app():
    """Creates the flask app
    """
    app = Flask(__name__)
    configure_app(app, LDAPConfig)
    register_extensions(app)
    return app


def configure_app(app, config=None):
    """configures the flask app from a config file

    :param app: Flask App
    :type app: Flask
    :param config: A config Class, defaults to None
    :type config: Class, optional
    :raises FileNotFoundError: Config class not found
    """
    if config:
        app.config.from_object(config)
    else:
        raise FileNotFoundError()
Esempio n. 4
0
if os.environ['LDAP_USERNAME'] is not None:
    app.config['LDAP_USERNAME'] = os.environ['LDAP_USERNAME']
else:
    app.config[
        'LDAP_USERNAME'] = '******'

if os.environ['LDAP_PASSWORD'] is not None:
    app.config['LDAP_PASSWORD'] = os.environ['LDAP_PASSWORD']
else:
    app.config['LDAP_PASSWORD'] = '******'

app.config[
    'LDAP_USER_OBJECT_FILTER'] = '(&(objectclass=inetOrgPerson)(uid=%s))'

ldap = LDAP(app)

# We retrieve student age file

if os.environ['student_age_file_path'] is not None:
    student_age_file_path = os.environ['student_age_file_path']
else:
    student_age_file_path = '/data/student_age.json'

student_age_file = open(student_age_file_path, "r")
student_age = json.load(student_age_file)


@app.route('/pozos/api/v1.0/get_student_ages', methods=['GET'])
@ldap.basic_auth_required
def get_student_ages():
Esempio n. 5
0
from dash import Dash
import dash_html_components as html
import os
from flask import Flask
from flask_simpleldap import LDAP

# Make Dash run on a Flask server
app = Dash(__name__, server=Flask(__name__))

# The Dash app
app.layout = html.P('Hello world!')

# Configure LDAP
app.server.config.update({
    'LDAP_BASE_DN': 'OU=users,dc=example,dc=org',
    'LDAP_USERNAME': '******',
    'LDAP_PASSWORD': os.getenv('LDAP_PASSWORD')
})

# Protect view functions with LDAP authentication
for view_func in app.server.view_functions:
    app.server.view_functions[view_func] = LDAP(
        app.server).basic_auth_required(app.server.view_functions[view_func])

# Run Flask server
if __name__ == '__main__':
    app.run_server()

# For gunicorn
server = app.server
Esempio n. 6
0
    def decorated_function(*args, **kwargs):
        auth = request.authorization
        ldap = None

        authentication_method = ""

        if "X-API-Key" in request.headers:
            try:
                username, password = request.headers["X-API-Key"].split(":", 1)
                authentication_method = "key"
            except:
                return Response(
                    "Access denied",
                    401,
                    {"WWW-Authenticate": 'Basic realm="PowerDNS API"'},
                )

        elif "X-LDAP-Auth" in request.headers:
            if not current_app.config["LDAP"]["enabled"]:
                return Response(
                    "LDAP not enabled for authentication",
                    406,
                    {"WWW-Authenticate": 'Basic realm="PowerDNS API"'},
                )
            else:
                try:
                    username, password = request.headers["X-LDAP-Auth"].split(":", 1)
                    authentication_method = "ldap"
                except:
                    return Response(
                        "Access denied",
                        401,
                        {"WWW-Authenticate": 'Basic realm="PowerDNS API"'},
                    )

        elif auth:
            username = auth.username
            password = auth.password
            authentication_method = "basic"

        if authentication_method == "ldap":
            current_app.config["LDAP_HOST"] = current_app.config["LDAP"]["host"]
            current_app.config["LDAP_PORT"] = current_app.config["LDAP"].get(
                "port", 389
            )
            current_app.config["LDAP_SCHEMA"] = current_app.config["LDAP"].get(
                "protocol", "ldap"
            )
            current_app.config["LDAP_USE_SSL"] = current_app.config["LDAP"].get(
                "use_ssl", False
            )
            current_app.config["LDAP_OPENLDAP"] = current_app.config["LDAP"].get(
                "openldap", False
            )
            current_app.config["LDAP_OBJECTS_DN"] = current_app.config["LDAP"].get(
                "objects_dn", "distinguishedName"
            )
            current_app.config["LDAP_BASE_DN"] = current_app.config["LDAP"]["base_dn"]
            current_app.config["LDAP_USERNAME"] = current_app.config["LDAP"]["bind_dn"]
            current_app.config["LDAP_PASSWORD"] = current_app.config["LDAP"]["password"]
            current_app.config["LDAP_USER_OBJECT_FILTER"] = current_app.config["LDAP"][
                "user_object_filter"
            ]
            current_app.config["LDAP_GROUP_MEMBER_FILTER"] = current_app.config["LDAP"][
                "group_member_filter"
            ]
            current_app.config["LDAP_GROUP_MEMBER_FILTER_FIELD"] = current_app.config[
                "LDAP"
            ]["group_member_filter_field"]

            ldap = LDAP(current_app)
        elif (
            authentication_method not in ("key", "basic")
            or username not in current_app.config["USERS"]
            or not hmac.compare_digest(
                current_app.config["USERS"][username]["key"], password
            )
        ):
            return Response(
                "Access denied", 401, {"WWW-Authenticate": 'Basic realm="PowerDNS API"'}
            )

        if ldap:
            try:
                test = ldap.bind_user(username, password)

                if test is None or password == "":
                    return Response(
                        "Access denied",
                        401,
                        {"WWW-Authenticate": 'Basic realm="PowerDNS API"'},
                    )
                else:
                    # g.user = ldap.get_object_details(username)['pdns-allow-suffix-creation']
                    # custom value
                    g.user = {"allow-suffix-creation": "example.com."}
                    g.username = username
            except KeyError:
                pass
        else:
            g.user = current_app.config["USERS"][username]
            g.username = username

        return f(*args, **kwargs)
Esempio n. 7
0
    def login(self):
        """
        user login
        /passport/

        :return:
        """
        form = LoginForm(request.form, csrf=False)
        if form.validate_on_submit():

            if current_app.config['LDAP']:
                ldap = LDAP(current_app)
                if form.password.data == '':
                    userbind = None
                else:
                    userbind = ldap.bind_user(form.email.data,
                                              form.password.data)
            else:
                ldap = current_app.config['LDAP']
                userbind = None

            if form.email.data in current_app.config['LDAP_PRIVILEGE']:
                ldap = False

            if ldap:
                if userbind:
                    user = UserModel.query.filter_by(
                        email=form.email.data).first()
                    if user is not None:
                        login_user(user)
                        user.fresh_session()
                        return self.render_json(data=current_user.to_json())
                    else:
                        # ldap验证成功,取信息入库
                        ldap_user = ldap.get_object_details(form.email.data)
                        user_info = {
                            'username': ldap_user['displayName'][0].decode(),
                            'password':
                            generate_password_hash(form.password.data),
                            'email': form.email.data,
                            'role': '',
                            'last_space': 1,
                            'created_at': datetime.now(),
                            'updated_at': datetime.now(),
                        }
                        user = UserModel().add(user_info)

                        member_info = {
                            'user_id': user.id,
                            'source_id': 1,
                            'source_type': 'group',
                            'access_level': 'DEVELOPER',
                            'status': MemberModel.status_available
                        }
                        m = MemberModel(**member_info)
                        db.session.add(m)
                        db.session.commit()

                        login_user(user)
                        user.fresh_session()
                        return self.render_json(data=current_user.to_json())
                else:
                    return self.render_json(code=Code.error_pwd,
                                            data=form.errors)
            else:
                user = UserModel.query.filter_by(email=form.email.data).first()
                if user is not None and user.verify_password(
                        form.password.data):
                    login_user(user)
                    user.fresh_session()
                    return self.render_json(data=current_user.to_json())

        return self.render_json(code=Code.error_pwd, data=form.errors)
Esempio n. 8
0
from flask import g, session
from flask_simpleldap import LDAP

from models.users import User


ldap_client = LDAP()


def register_hooks(app):
    @app.before_request
    def before_request():
        g.user = None
        if 'username' in session:
            session['logged_in'] = True
            # This is where you'd query your database to get the user info.
            user = User.query.filter_by(
                username=session['username']).first().username
            g.user = user
            # Create a global with the LDAP groups the user is a member of.
            g.ldap_groups = ldap_client.get_user_groups(
                user=session['username'])


def refine_data(obj, data_tag):
    out = obj[data_tag][0].decode('utf8')
    return out
Esempio n. 9
0
from PIL import Image, ImageFont, ImageOps, ImageDraw
import base64
import logging
from logging.handlers import RotatingFileHandler

application = Flask(__name__)
application.secret_key = 'pexdev key'
application.debug = True
application.config['LDAP_LOGIN_VIEW'] = 'login'
application.config.from_object('config')
log_filename = application.config['LOG_FILENAME']
mgr_address = application.config['MGR_ADDRESS']
mgr_user = application.config['MGR_USER']
mgr_password = application.config['MGR_PASSWORD']

ldap = LDAP(application)


@application.errorhandler(404)
def page_not_found(error):
    return 'This route does not exist {}'.format(request.url), 404


# def register_hooks(application):
@application.before_request
def before_request():
    if 'logged_in' not in session and '/static/' not in request.path and request.endpoint != 'logout':
        g.user = None
        if 'user_id' in session:
            # This is where you'd query your database to get the user info.
            g.user = {}
Esempio n. 10
0
 def init_app(app):
     app.config.setdefault('LDAP_USER_PREFIX', "")
     app.config.setdefault('LDAP_USER_MAIL', "*****@*****.**")
     LDAP.init_app(app)
Esempio n. 11
0
# Flask Initialization
app = Flask(__name__)

# Include config from config.py
app.config.from_object('config')
group = app.config['GROUP_NAME']

from models import db
db.init_app(app)

from models import *
from specification import *
from utils import set_boolean_value, make_component_info, _monkey_patch_openldap_string_flask_simpleldap_1_2_0_issue_44, owner_or_group_required

ldap = _monkey_patch_openldap_string_flask_simpleldap_1_2_0_issue_44(LDAP(app))


@app.before_request
def before_request():
    g.user = None
    if 'user_id' in session:
        g.user = ldap.get_object_details(user=session['user_id'])
        groups = ldap.get_user_groups(user=session['user_id'])
        if groups:
            g.ldap_groups = groups
        else:
            g.ldap_groups = list()


@app.route('/')