# Path: doorman/users/forms.py
# class LoginForm(Form):
# 
#     username = StringField('Username', validators=[DataRequired()])
#     password = PasswordField('Password', validators=[DataRequired()])
#     remember = BooleanField('Remember me', validators=[Optional()])
# 
#     def __init__(self, *args, **kwargs):
#         """Create instance."""
#         super(LoginForm, self).__init__(*args, **kwargs)
#         self.user = None
# 
#     def validate(self):
#         initial_validation = super(LoginForm, self).validate()
#         if not initial_validation:
#             return False
# 
#         error_message = u'Invalid username or password.'
# 
#         if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman':
#             self.user = User.query.filter_by(username=self.username.data).first()
# 
#             if not self.user:
#                 from doorman.extensions import bcrypt
#                 # avoid timing leaks
#                 bcrypt.generate_password_hash(self.password.data)
#                 self.username.errors.append(error_message)
#                 return False
# 
#             if not self.user.check_password(self.password.data):
#                 self.username.errors.append(error_message)
#                 return False
# 
#             return True
# 
#         elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap':
#             result = ldap_manager.authenticate(
#                 self.username.data,
#                 self.password.data
#             )
# 
#             if result.status == AuthenticationResponseStatus.fail:
#                 self.username.errors.append(error_message)
#                 return False
# 
#             self.user = ldap_manager._save_user(
#                 result.user_dn,
#                 result.user_id,
#                 result.user_info,
#                 result.user_groups
#             )
#             return True
# 
#         elif current_app.config['DOORMAN_AUTH_METHOD'] is None:
#             return True
# 
#         return False
# 
#     @property
#     def auth_method(self):
#         return current_app.config['DOORMAN_AUTH_METHOD']
# 
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
#     class ContextTask(TaskBase):
#     def __init__(self, app=None):
#     def init_app(self, app):
#     def handle_status(self, data, **kwargs):
#     def handle_result(self, data, **kwargs):
#     def __init__(self, app=None):
#     def init_app(self, app):
#     def load_alerters(self):
#     def should_reload_rules(self):
#     def load_rules(self):
#     def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
#         def __call__(self, *args, **kwargs):
# 
# Path: doorman/models.py
# class User(UserMixin, SurrogatePK, Model):
# 
#     username = Column(db.String(80), unique=True, nullable=False)
#     email = Column(db.String)
# 
#     password = Column(db.String, nullable=True)
#     created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
# 
#     # oauth related stuff
#     social_id = Column(db.String)
#     first_name = Column(db.String)
#     last_name = Column(db.String)
# 
#     def __init__(self, username, password=None, email=None, social_id=None,
#                  first_name=None, last_name=None):
#         self.username = username
#         self.email = email
#         if password:
#             self.set_password(password)
#         else:
#             self.password = None
# 
#         self.social_id = social_id
#         self.first_name = first_name
#         self.last_name = last_name
# 
#     def set_password(self, password):
#         self.update(password=bcrypt.generate_password_hash(password))
#         return
# 
#     def check_password(self, value):
#         if not self.password:
#             # still do the computation
#             return bcrypt.generate_password_hash(value) and False
#         return bcrypt.check_password_hash(self.password, value)
# 
# Path: doorman/utils.py
# def flash_errors(form):
#     '''http://flask.pocoo.org/snippets/12/'''
#     for field, errors in form.errors.items():
#         for error in errors:
#             message = u"Error in the {0} field - {1}".format(
#                 getattr(form, field).label.text, error
#             )
#             flash(message, 'danger')


    from urlparse import urlparse, urljoin
    from urllib.parse import urlparse, urljoin
from flask import (
    Blueprint, abort, current_app, flash, redirect, render_template,
    request, session, url_for
)
from flask_login import current_user, login_user, logout_user, COOKIE_NAME
from oauthlib.oauth2 import OAuth2Error
from .forms import LoginForm
from doorman.extensions import csrf, ldap_manager, login_manager
from doorman.models import User
from doorman.utils import flash_errors
        from doorman.users.mixins import NoAuthUserMixin
# -*- coding: utf-8 -*-
try:
except ImportError:





blueprint = Blueprint('users', __name__)


@login_manager.user_loader
def load_user(user_id):
    if current_app.config['DOORMAN_AUTH_METHOD'] is None:
        return NoAuthUserMixin()
    return User.get_by_id(int(user_id))


@ldap_manager.save_user
def save_user(dn, username, userdata, memberships):
    user = User.query.filter_by(username=username).first()
    kwargs = {}
    kwargs['username'] = username

    if 'givenName' in userdata:
        kwargs['first_name'] = userdata['givenName'][0]

    if 'sn' in userdata:
        kwargs['last_name'] = userdata['sn'][0]


# Path: doorman/users/forms.py
# class LoginForm(Form):
# 
#     username = StringField('Username', validators=[DataRequired()])
#     password = PasswordField('Password', validators=[DataRequired()])
#     remember = BooleanField('Remember me', validators=[Optional()])
# 
#     def __init__(self, *args, **kwargs):
#         """Create instance."""
#         super(LoginForm, self).__init__(*args, **kwargs)
#         self.user = None
# 
#     def validate(self):
#         initial_validation = super(LoginForm, self).validate()
#         if not initial_validation:
#             return False
# 
#         error_message = u'Invalid username or password.'
# 
#         if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman':
#             self.user = User.query.filter_by(username=self.username.data).first()
# 
#             if not self.user:
#                 from doorman.extensions import bcrypt
#                 # avoid timing leaks
#                 bcrypt.generate_password_hash(self.password.data)
#                 self.username.errors.append(error_message)
#                 return False
# 
#             if not self.user.check_password(self.password.data):
#                 self.username.errors.append(error_message)
#                 return False
# 
#             return True
# 
#         elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap':
#             result = ldap_manager.authenticate(
#                 self.username.data,
#                 self.password.data
#             )
# 
#             if result.status == AuthenticationResponseStatus.fail:
#                 self.username.errors.append(error_message)
#                 return False
# 
#             self.user = ldap_manager._save_user(
#                 result.user_dn,
#                 result.user_id,
#                 result.user_info,
#                 result.user_groups
#             )
#             return True
# 
#         elif current_app.config['DOORMAN_AUTH_METHOD'] is None:
#             return True
# 
#         return False
# 
#     @property
#     def auth_method(self):
#         return current_app.config['DOORMAN_AUTH_METHOD']
# 
# Path: doorman/extensions.py
# class LogTee(object):
# class RuleManager(object):
#     class ContextTask(TaskBase):
#     def __init__(self, app=None):
#     def init_app(self, app):
#     def handle_status(self, data, **kwargs):
#     def handle_result(self, data, **kwargs):
#     def __init__(self, app=None):
#     def init_app(self, app):
#     def load_alerters(self):
#     def should_reload_rules(self):
#     def load_rules(self):
#     def handle_log_entry(self, entry, node):
# def make_celery(app, celery):
#         def __call__(self, *args, **kwargs):
# 
# Path: doorman/models.py
# class User(UserMixin, SurrogatePK, Model):
# 
#     username = Column(db.String(80), unique=True, nullable=False)
#     email = Column(db.String)
# 
#     password = Column(db.String, nullable=True)
#     created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
# 
#     # oauth related stuff
#     social_id = Column(db.String)
#     first_name = Column(db.String)
#     last_name = Column(db.String)
# 
#     def __init__(self, username, password=None, email=None, social_id=None,
#                  first_name=None, last_name=None):
#         self.username = username
#         self.email = email
#         if password:
#             self.set_password(password)
#         else:
#             self.password = None
# 
#         self.social_id = social_id
#         self.first_name = first_name
#         self.last_name = last_name
# 
#     def set_password(self, password):
#         self.update(password=bcrypt.generate_password_hash(password))
#         return
# 
#     def check_password(self, value):
#         if not self.password:
#             # still do the computation
#             return bcrypt.generate_password_hash(value) and False
#         return bcrypt.check_password_hash(self.password, value)
# 
# Path: doorman/utils.py
# def flash_errors(form):
#     '''http://flask.pocoo.org/snippets/12/'''
#     for field, errors in form.errors.items():
#         for error in errors:
#             message = u"Error in the {0} field - {1}".format(
#                 getattr(form, field).label.text, error
#             )
#             flash(message, 'danger')


# Path: doorman/users/views.py
    from urlparse import urlparse, urljoin
    from urllib.parse import urlparse, urljoin
from flask import (
    Blueprint, abort, current_app, flash, redirect, render_template,
    request, session, url_for
)
from flask_login import current_user, login_user, logout_user, COOKIE_NAME
from oauthlib.oauth2 import OAuth2Error
from .forms import LoginForm
from doorman.extensions import csrf, ldap_manager, login_manager
from doorman.models import User
from doorman.utils import flash_errors
        from doorman.users.mixins import NoAuthUserMixin

# -*- coding: utf-8 -*-
try:
except ImportError:





blueprint = Blueprint('users', __name__)


@login_manager.user_loader
def load_user(user_id):
    if current_app.config['DOORMAN_AUTH_METHOD'] is None:
        return NoAuthUserMixin()
    return User.get_by_id(int(user_id))


@ldap_manager.save_user
def save_user(dn, username, userdata, memberships):
    user = User.query.filter_by(username=username).first()
    kwargs = {}
    kwargs['username'] = username

    if 'givenName' in userdata:
        kwargs['first_name'] = userdata['givenName'][0]

    if 'sn' in userdata:
        kwargs['last_name'] = userdata['sn'][0]


    return user.update(**kwargs) if user else User.create(**kwargs)