Exemplo n.º 1
0
 def temp_url_for(self, **kwargs):
     filename = kwargs.get('filename', self.filename)
     seconds = kwargs.get('seconds', None)
     if type(seconds) is float:
         seconds = int(seconds)
     if type(seconds) is not int:
         seconds = 30
     if cloud is not None:
         keyname = str(self.section) + '/' + str(self.file_number) + '/' + str(filename)
         key = cloud.get_key(keyname)
         if key.does_exist:
             if 'display_filename' in kwargs:
                 return key.generate_url(seconds, display_filename=kwargs['display_filename'])
             else:
                 return key.generate_url(seconds)
         else:
             sys.stderr.write("key " + str(keyname) + " did not exist\n")
             return('about:blank')
     r = docassemble.base.functions.server.server_redis
     while True:
         code = random_alphanumeric(32)
         keyname = 'da:tempfile:' + code
         if r.setnx(keyname, str(self.section) + '^' + str(self.file_number)):
             r.expire(keyname, seconds)
             break
     return docassemble.base.functions.get_url_root() + '/tempfile/' + code + '/' + kwargs.get('display_filename', self.filename)
Exemplo n.º 2
0
def get_user(db, role, defaults):
    while True:
        new_social = 'local$' + random_alphanumeric(32)
        existing_user = UserModel.query.filter_by(social_id=new_social).first()
        if existing_user:
            continue
        break
    the_user = UserModel.query.filter_by(nickname=defaults['nickname']).first()
    if the_user:
        return the_user
    user_auth = UserAuthModel(password=app.user_manager.hash_password(
        defaults.get('password', 'password')))
    the_user = UserModel(active=defaults.get('active', True),
                         nickname=defaults['nickname'],
                         social_id=new_social,
                         email=defaults['email'],
                         user_auth=user_auth,
                         first_name=defaults.get('first_name', ''),
                         last_name=defaults.get('last_name', ''),
                         country=defaults.get('country', ''),
                         subdivisionfirst=defaults.get('subdivisionfirst', ''),
                         subdivisionsecond=defaults.get(
                             'subdivisionsecond', ''),
                         subdivisionthird=defaults.get('subdivisionthird', ''),
                         organization=defaults.get('organization', ''),
                         confirmed_at=datetime.datetime.now())
    the_user.roles.append(role)
    db.session.add(user_auth)
    db.session.add(the_user)
    db.session.commit()
    return the_user
Exemplo n.º 3
0
 def temp_url_for(self, **kwargs):
     if kwargs.get('_attachment', False):
         suffix = 'download'
     else:
         suffix = ''
     filename = kwargs.get('filename', self.filename)
     seconds = kwargs.get('seconds', None)
     if isinstance(seconds, float):
         seconds = int(seconds)
     if not isinstance(seconds, int):
         seconds = 30
     if cloud is not None and daconfig.get('use cloud urls', False):
         keyname = str(self.section) + '/' + str(self.file_number) + '/' + path_to_key(filename)
         key = cloud.get_key(keyname)
         inline = not bool(kwargs.get('_attachment', False))
         if key.does_exist:
             return key.generate_url(seconds, display_filename=kwargs.get('display_filename', None), inline=inline, content_type=kwargs.get('content_type', None))
         sys.stderr.write("key " + str(keyname) + " did not exist\n")
         return 'about:blank'
     r = docassemble.base.functions.server.server_redis
     while True:
         code = random_alphanumeric(32)
         keyname = 'da:tempfile:' + code
         if r.setnx(keyname, str(self.section) + '^' + str(self.file_number)):
             r.expire(keyname, seconds)
             break
     use_external = kwargs.get('_external', bool('jsembed' in docassemble.base.functions.this_thread.misc))
     url = url_for('rootindex', _external=use_external).rstrip('/')
     url += '/tempfile' + suffix + '/' + code + '/' + path_to_key(kwargs.get('display_filename', filename))
     return url
Exemplo n.º 4
0
 def temp_url_for(self, **kwargs):
     filename = kwargs.get('filename', self.filename)
     seconds = kwargs.get('seconds', None)
     if type(seconds) is float:
         seconds = int(seconds)
     if type(seconds) is not int:
         seconds = 30
     if cloud is not None and daconfig.get('use cloud urls', False):
         keyname = str(self.section) + '/' + str(self.file_number) + '/' + path_to_key(filename)
         key = cloud.get_key(keyname)
         if key.does_exist:
             return key.generate_url(seconds, display_filename=kwargs.get('display_filename', None), inline=kwargs.get('inline', None), content_type=kwargs.get('content_type', None))
         else:
             sys.stderr.write("key " + str(keyname) + " did not exist\n")
             return('about:blank')
     r = docassemble.base.functions.server.server_redis
     while True:
         code = random_alphanumeric(32)
         keyname = 'da:tempfile:' + code
         if r.setnx(keyname, str(self.section) + '^' + str(self.file_number)):
             r.expire(keyname, seconds)
             break
     use_external = kwargs.get('_external', True if 'jsembed' in docassemble.base.functions.this_thread.misc else False)
     from flask import url_for
     url = url_for('rootindex', _external=use_external).rstrip('/')
     url += '/tempfile/' + code + '/' + path_to_key(kwargs.get('display_filename', filename))
     return(url)
Exemplo n.º 5
0
 def temp_url_for(self, **kwargs):
     filename = kwargs.get('filename', self.filename)
     seconds = kwargs.get('seconds', None)
     if type(seconds) is float:
         seconds = int(seconds)
     if type(seconds) is not int:
         seconds = 30
     if cloud is not None:
         keyname = str(self.section) + '/' + str(self.file_number) + '/' + str(filename)
         key = cloud.get_key(keyname)
         if key.does_exist:
             if 'display_filename' in kwargs:
                 return key.generate_url(seconds, display_filename=kwargs['display_filename'])
             else:
                 return key.generate_url(seconds)
         else:
             sys.stderr.write("key " + str(keyname) + " did not exist\n")
             return('about:blank')
     r = docassemble.base.functions.server.server_redis
     while True:
         code = random_alphanumeric(32)
         keyname = 'da:tempfile:' + code
         if r.setnx(keyname, str(self.section) + '^' + str(self.file_number)):
             r.expire(keyname, seconds)
             break
     return docassemble.base.functions.get_url_root() + '/tempfile/' + code + '/' + kwargs.get('display_filename', self.filename)
Exemplo n.º 6
0
def unattached_uid():
    while True:
        newname = random_alphanumeric(32)
        existing_key = UserDict.query.filter_by(key=newname).first()
        if existing_key:
            continue
        return newname
Exemplo n.º 7
0
def get_user(db, role, defaults):
    while True:
        new_social = 'local$' + random_alphanumeric(32)
        existing_user = UserModel.query.filter_by(social_id=new_social).first()
        if existing_user:
            continue
        break
    the_user = UserModel.query.filter_by(nickname=defaults['nickname']).first()
    if the_user:
        return the_user
    user_auth = UserAuthModel(password=app.user_manager.hash_password(defaults.get('password', 'password')))
    the_user = UserModel(
        active=defaults.get('active', True),
        nickname=defaults['nickname'],
        social_id=new_social,
        email=defaults['email'],
        user_auth=user_auth,
        first_name = defaults.get('first_name', ''),
        last_name = defaults.get('last_name', ''),
        country = defaults.get('country', ''),
        subdivisionfirst = defaults.get('subdivisionfirst', ''),
        subdivisionsecond = defaults.get('subdivisionsecond', ''),
        subdivisionthird = defaults.get('subdivisionthird', ''),
        organization = defaults.get('organization', ''),
        confirmed_at = datetime.datetime.now()
    )
    the_user.roles.append(role)
    db.session.add(user_auth)
    db.session.add(the_user)
    db.session.commit()
    return the_user
Exemplo n.º 8
0
def user_add():
    setup_translation()
    user_role = db.session.execute(
        select(Role).filter_by(name='user')).scalar_one()
    add_form = UserAddForm(request.form, role_id=[str(user_role.id)])
    add_form.role_id.choices = [(r.id, r.name) for r in db.session.execute(
        select(Role.id, Role.name).where(Role.name != 'cron').order_by('name'))
                                ]
    add_form.role_id.default = user_role.id
    if str(add_form.role_id.data) == 'None':
        add_form.role_id.data = user_role.id
    if request.method == 'POST' and add_form.validate():
        user, user_email = app.user_manager.find_user_by_email(
            add_form.email.data)
        if user:
            flash(word("A user with that e-mail has already registered"),
                  "error")
            return redirect(url_for('user_add'))
        user_auth = UserAuthModel(
            password=app.user_manager.hash_password(add_form.password.data))
        while True:
            new_social = 'local$' + random_alphanumeric(32)
            existing_user = db.session.execute(
                select(UserModel).filter_by(social_id=new_social)).scalar()
            if existing_user:
                continue
            break
        the_user = UserModel(active=True,
                             nickname=re.sub(r'@.*', '', add_form.email.data),
                             social_id=new_social,
                             email=add_form.email.data,
                             user_auth=user_auth,
                             first_name=add_form.first_name.data,
                             last_name=add_form.last_name.data,
                             confirmed_at=datetime.datetime.now())
        num_roles = 0
        for role in db.session.execute(select(Role).order_by('id')).scalars():
            if role.id in add_form.role_id.data:
                the_user.roles.append(role)
                num_roles += 1
        if num_roles == 0:
            the_user.roles.append(user_role)
        db.session.add(user_auth)
        db.session.add(the_user)
        db.session.commit()
        #docassemble.webapp.daredis.clear_user_cache()
        flash(word("The new user has been created"), "success")
        return redirect(url_for('user_list'))
    response = make_response(
        render_template('users/add_user_page.html',
                        version_warning=None,
                        bodyclass='daadminbody',
                        page_title=word('Add User'),
                        tab_title=word('Add User'),
                        form=add_form), 200)
    response.headers[
        'Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
    return response
Exemplo n.º 9
0
 def _get_random_unique_id(self):
     r = DARedis()
     tries = 10
     while tries > 0:
         key = random_alphanumeric(32)
         if r.setnx('da:' + self.appname + ':status:uniqueid:' + key, 'None'):
             r.expire('da:' + self.appname + ':status:uniqueid:' + key, 300)
             return key
         tries -= 1
     raise Exception("DAOAuth: unable to set a random unique id")
Exemplo n.º 10
0
 def validate(self):
     #import redis
     from docassemble.webapp.daredis import r
     #import docassemble.base.util
     from flask import request, abort
     #r = redis.StrictRedis(host=docassemble.base.util.redis_server, db=0)
     key = 'da:failedlogin:ip:' + str(request.remote_addr)
     failed_attempts = r.get(key)
     if failed_attempts is not None and int(
             failed_attempts) > daconfig['attempt limit']:
         abort(404)
     if daconfig['ldap login'].get('enable', False):
         ldap_server = daconfig['ldap login'].get('server',
                                                  'localhost').strip()
         username = self.email.data
         password = self.password.data
         connect = ldap.open(ldap_server)
         try:
             connect.simple_bind_s(username, password)
             connect.unbind_s()
             from flask import current_app
             user_manager = current_app.user_manager
             user, user_email = user_manager.find_user_by_email(
                 self.email.data)
             if not user:
                 from docassemble.base.generate_key import random_alphanumeric
                 from docassemble.webapp.db_object import db
                 from docassemble.webapp.users.models import UserModel, Role
                 while True:
                     new_social = 'ldap$' + random_alphanumeric(32)
                     existing_user = UserModel.query.filter_by(
                         social_id=new_social).first()
                     if existing_user:
                         continue
                     break
                 user = UserModel(social_id=new_social,
                                  email=self.email.data,
                                  nickname='',
                                  active=True)
                 user_role = Role.query.filter_by(name='user').first()
                 user.roles.append(user_role)
                 db.session.add(user)
                 db.session.commit()
             result = True
         except ldap.LDAPError:
             connect.unbind_s()
             result = super(MySignInForm, self).validate()
     else:
         result = super(MySignInForm, self).validate()
     if result is False:
         r.incr(key)
         r.expire(key, daconfig['ban period'])
     elif failed_attempts is not None:
         r.delete(key)
     return result
Exemplo n.º 11
0
def user_add():
    user_role = Role.query.filter_by(name='user').first()
    add_form = UserAddForm(request.form, role_id=[text_type(user_role.id)])
    add_form.role_id.choices = [(r.id, r.name)
                                for r in db.session.query(Role).filter(
                                    Role.name != 'cron').order_by('name')]
    add_form.role_id.default = user_role.id
    if text_type(add_form.role_id.data) == 'None':
        add_form.role_id.data = user_role.id
    if request.method == 'POST' and add_form.validate():
        user, user_email = app.user_manager.find_user_by_email(
            add_form.email.data)
        if user:
            flash(word("A user with that e-mail has already registered"),
                  "error")
            return redirect(url_for('user_add'))
        user_auth = UserAuthModel(
            password=app.user_manager.hash_password(add_form.password.data))
        while True:
            new_social = 'local$' + random_alphanumeric(32)
            existing_user = UserModel.query.filter_by(
                social_id=new_social).first()
            if existing_user:
                continue
            break
        the_user = UserModel(active=True,
                             nickname=re.sub(r'@.*', '', add_form.email.data),
                             social_id=new_social,
                             email=add_form.email.data,
                             user_auth=user_auth,
                             first_name=add_form.first_name.data,
                             last_name=add_form.last_name.data,
                             confirmed_at=datetime.datetime.now())
        num_roles = 0
        for role in Role.query.order_by('id'):
            if role.id in add_form.role_id.data:
                the_user.roles.append(role)
                num_roles += 1
        if num_roles == 0:
            the_user.roles.append(user_role)
        db.session.add(user_auth)
        db.session.add(the_user)
        db.session.commit()
        #docassemble.webapp.daredis.clear_user_cache()
        flash(word("The new user has been created"), "success")
        return redirect(url_for('user_list'))
    return render_template('users/add_user_page.html',
                           version_warning=None,
                           bodyclass='daadminbody',
                           page_title=word('Add User'),
                           tab_title=word('Add User'),
                           form=add_form)
def save_input_data(title: str = "",
                    input_dict: Dict[str, Any] = None,
                    tags: List[str] = None) -> None:
    """
    This function is used by survey type interviews to save input data for data reporting purposes.

    The input_dict should a dictionary where each key is a string and each value is a value from a Docassemble interview
    question. Typically that is a string, float, int, or a DADict.
    """
    type_dict = dict()
    field_dict = dict()
    for k, v in input_dict.items():
        field_dict[k] = v
        if isinstance(v, int):
            type_dict[k] = "int"
        elif isinstance(v, float):
            type_dict[k] = "float"
        elif isinstance(v, DADict):  # This covers checkboxes and multiselect
            type_dict[k] = "checkboxes"
        else:
            type_dict[k] = "text"

    data_to_save = dict()
    data_to_save["title"] = title

    # TODO(qs): We should be able to infer type in the InterviewStats package too, eventually. But
    # leaving as-is for now
    data_to_save["field_type_list"] = type_dict  # This may not be needed

    for k, v in type_dict.items():
        # If a field is of checkboxes type, flatten its elements dict
        # so that each key/value pair is saved in its own column.
        if v in ["checkboxes", "multiselect"]:
            for subkey, subvalue in field_dict[k].elements.items():
                data_to_save[k + "_" + subkey] = subvalue
        else:
            data_to_save[k] = field_dict[k]

    # Save one record per session to JsonStorage datatable.
    filename = get_current_info().get("yaml_filename", None)
    random_uid = random_alphanumeric(32)
    new_entry = JsonStorage(
        filename=filename,
        key=random_uid,
        data=data_to_save,
        tags=tags,
        persistent=False,
    )
    JsonDb.add(new_entry)
    JsonDb.commit()
Exemplo n.º 13
0
def user_add():
    user_role = Role.query.filter_by(name='user').first()
    add_form = UserAddForm(request.form, role_id=[text_type(user_role.id)])
    add_form.role_id.choices = [(r.id, r.name) for r in db.session.query(Role).filter(Role.name != 'cron').order_by('name')]
    add_form.role_id.default = user_role.id
    if text_type(add_form.role_id.data) == 'None':
        add_form.role_id.data = user_role.id
    if request.method == 'POST' and add_form.validate():
        user, user_email = app.user_manager.find_user_by_email(add_form.email.data)
        if user:
            flash(word("A user with that e-mail has already registered"), "error")
            return redirect(url_for('user_add'))
        user_auth = UserAuthModel(password=app.user_manager.hash_password(add_form.password.data))
        while True:
            new_social = 'local$' + random_alphanumeric(32)
            existing_user = UserModel.query.filter_by(social_id=new_social).first()
            if existing_user:
                continue
            break
        the_user = UserModel(
            active=True,
            nickname=re.sub(r'@.*', '', add_form.email.data),
            social_id=new_social,
            email=add_form.email.data,
            user_auth=user_auth,
            first_name = add_form.first_name.data,
            last_name = add_form.last_name.data,
            confirmed_at = datetime.datetime.now()
        )
        num_roles = 0
        for role in Role.query.order_by('id'):
            if role.id in add_form.role_id.data:
                the_user.roles.append(role)
                num_roles +=1
        if num_roles == 0:
            the_user.roles.append(user_role)
        db.session.add(user_auth)
        db.session.add(the_user)
        db.session.commit()
        #docassemble.webapp.daredis.clear_user_cache()
        flash(word("The new user has been created"), "success")
        return redirect(url_for('user_list'))
    return render_template('users/add_user_page.html', version_warning=None, bodyclass='adminbody', page_title=word('Add User'), tab_title=word('Add User'), form=add_form)
Exemplo n.º 14
0
def get_user(the_db, role, defaults, result=None):
    if result is None:
        result = {}
    the_user = the_db.session.execute(
        select(UserModel).filter_by(nickname=defaults['nickname'])).scalar()
    if the_user:
        return the_user
    while True:
        new_social = 'local$' + random_alphanumeric(32)
        existing_user = the_db.session.execute(
            select(UserModel).filter_by(social_id=new_social)).scalar()
        if existing_user:
            continue
        break
    user_auth = UserAuthModel(password=app.user_manager.hash_password(
        defaults.get('password', 'password')))
    the_user = UserModel(active=defaults.get('active', True),
                         nickname=defaults['nickname'],
                         social_id=new_social,
                         email=defaults['email'],
                         user_auth=user_auth,
                         first_name=defaults.get('first_name', ''),
                         last_name=defaults.get('last_name', ''),
                         country=defaults.get('country', ''),
                         subdivisionfirst=defaults.get('subdivisionfirst', ''),
                         subdivisionsecond=defaults.get(
                             'subdivisionsecond', ''),
                         subdivisionthird=defaults.get('subdivisionthird', ''),
                         organization=defaults.get('organization', ''),
                         confirmed_at=datetime.datetime.now())
    the_user.roles.append(role)
    the_db.session.add(user_auth)
    the_db.session.add(the_user)
    the_db.session.commit()
    result['changed'] = True
    return the_user
Exemplo n.º 15
0
 def validate(self):
     key = 'da:failedlogin:ip:' + str(get_requester_ip(request))
     failed_attempts = r.get(key)
     if failed_attempts is not None and int(
             failed_attempts) > daconfig['attempt limit']:
         abort(404)
     if daconfig['ldap login'].get('enable', False):
         ldap_server = daconfig['ldap login'].get('server',
                                                  'localhost').strip()
         username = self.email.data
         password = self.password.data
         connect = ldap.initialize('ldap://' + ldap_server)
         connect.set_option(ldap.OPT_REFERRALS, 0)
         try:
             connect.simple_bind_s(username, password)
             if connect.whoami_s() is not None:
                 connect.unbind_s()
                 user_manager = current_app.user_manager
                 user, user_email = user_manager.find_user_by_email(
                     self.email.data)
                 if not user:
                     while True:
                         new_social = 'ldap$' + random_alphanumeric(32)
                         existing_user = db.session.execute(
                             select(UserModel).filter_by(
                                 social_id=new_social)).scalar()
                         if existing_user:
                             continue
                         break
                     user = UserModel(social_id=new_social,
                                      email=self.email.data,
                                      nickname='',
                                      active=True)
                     user_role = db.session.execute(
                         select(Role).filter_by(name='user')).scalar_one()
                     user.roles.append(user_role)
                     db.session.add(user)
                     db.session.commit()
                 result = True
             else:
                 connect.unbind_s()
                 result = super().validate()
         except (ldap.LDAPError, ldap.INVALID_CREDENTIALS):
             connect.unbind_s()
             result = super().validate()
     else:
         user_manager = current_app.user_manager
         user, user_email = user_manager.find_user_by_email(self.email.data)
         if user is None:
             if daconfig.get('confirm registration', False):
                 self.email.errors = []
                 self.email.errors.append(
                     word("Incorrect Email and/or Password"))
                 self.password.errors = []
                 self.password.errors.append(
                     word("Incorrect Email and/or Password"))
             else:
                 self.email.errors = list(self.email.errors)
                 self.email.errors.append(word("Account did not exist."))
             return False
         if user and (user.password is None or
                      (user.social_id is not None
                       and not user.social_id.startswith('local$'))):
             self.email.errors = list(self.email.errors)
             if user.social_id.startswith('google$'):
                 self.email.errors.append(
                     word("You need to log in with Google."))
             elif user.social_id.startswith('azure$'):
                 self.email.errors.append(
                     word("You need to log in with Azure."))
             elif user.social_id.startswith('auth0$'):
                 self.email.errors.append(
                     word("You need to log in with Auth0."))
             elif user.social_id.startswith('twitter$'):
                 self.email.errors.append(
                     word("You need to log in with Twitter."))
             elif user.social_id.startswith('facebook$'):
                 self.email.errors.append(
                     word("You need to log in with Facebook."))
             else:
                 self.email.errors.append(
                     word("You cannot log in this way."))
             return False
         #sys.stderr.write("Trying super validate\n")
         result = super().validate()
         #sys.stderr.write("Super validate response was " + repr(result) + "\n")
     if result is False:
         r.incr(key)
         r.expire(key, daconfig['ban period'])
     elif failed_attempts is not None:
         r.delete(key)
     return result
Exemplo n.º 16
0
 def validate(self):
     from docassemble.webapp.daredis import r
     from flask import request, abort
     key = 'da:failedlogin:ip:' + str(request.remote_addr)
     failed_attempts = r.get(key)
     if failed_attempts is not None and int(
             failed_attempts) > daconfig['attempt limit']:
         abort(404)
     if daconfig['ldap login'].get('enable', False):
         ldap_server = daconfig['ldap login'].get('server',
                                                  'localhost').strip()
         username = self.email.data
         password = self.password.data
         connect = ldap.open(ldap_server)
         try:
             connect.simple_bind_s(username, password)
             connect.unbind_s()
             from flask import current_app
             user_manager = current_app.user_manager
             user, user_email = user_manager.find_user_by_email(
                 self.email.data)
             if not user:
                 from docassemble.base.generate_key import random_alphanumeric
                 from docassemble.webapp.db_object import db
                 from docassemble.webapp.users.models import UserModel, Role
                 while True:
                     new_social = 'ldap$' + random_alphanumeric(32)
                     existing_user = UserModel.query.filter_by(
                         social_id=new_social).first()
                     if existing_user:
                         continue
                     break
                 user = UserModel(social_id=new_social,
                                  email=self.email.data,
                                  nickname='',
                                  active=True)
                 user_role = Role.query.filter_by(name='user').first()
                 user.roles.append(user_role)
                 db.session.add(user)
                 db.session.commit()
             result = True
         except ldap.LDAPError:
             connect.unbind_s()
             result = super(MySignInForm, self).validate()
     else:
         from flask import current_app
         user_manager = current_app.user_manager
         user, user_email = user_manager.find_user_by_email(self.email.data)
         if user is None:
             return False
         if user and (user.password is None or
                      (user.social_id is not None
                       and not user.social_id.startswith('local$'))):
             self.email.errors = list(self.email.errors)
             if user.social_id.startswith('google$'):
                 self.email.errors.append(
                     word("You need to log in with Google."))
             elif user.social_id.startswith('azure$'):
                 self.email.errors.append(
                     word("You need to log in with Azure."))
             elif user.social_id.startswith('auth0$'):
                 self.email.errors.append(
                     word("You need to log in with Auth0."))
             elif user.social_id.startswith('twitter$'):
                 self.email.errors.append(
                     word("You need to log in with Twitter."))
             elif user.social_id.startswith('facebook$'):
                 self.email.errors.append(
                     word("You need to log in with Facebook."))
             else:
                 self.email.errors.append(
                     word("You cannot log in this way."))
             return False
         #sys.stderr.write("Trying super validate\n")
         result = super(MySignInForm, self).validate()
         #sys.stderr.write("Super validate response was " + repr(result) + "\n")
     if result is False:
         r.incr(key)
         r.expire(key, daconfig['ban period'])
     elif failed_attempts is not None:
         r.delete(key)
     return result
Exemplo n.º 17
0
 def validate(self):
     from docassemble.webapp.daredis import r
     from flask import request, abort
     key = 'da:failedlogin:ip:' + str(request.remote_addr)
     failed_attempts = r.get(key)
     if failed_attempts is not None and int(failed_attempts) > daconfig['attempt limit']:
         abort(404)
     if daconfig['ldap login'].get('enable', False):
         ldap_server = daconfig['ldap login'].get('server', 'localhost').strip()
         username = self.email.data
         password = self.password.data
         connect = ldap.open(ldap_server)
         try:
             connect.simple_bind_s(username, password)
             connect.unbind_s()
             from flask import current_app
             user_manager = current_app.user_manager
             user, user_email = user_manager.find_user_by_email(self.email.data)
             if not user:
                 from docassemble.base.generate_key import random_alphanumeric
                 from docassemble.webapp.db_object import db
                 from docassemble.webapp.users.models import UserModel, Role
                 while True:
                     new_social = 'ldap$' + random_alphanumeric(32)
                     existing_user = UserModel.query.filter_by(social_id=new_social).first()
                     if existing_user:
                         continue
                     break
                 user = UserModel(social_id=new_social, email=self.email.data, nickname='', active=True)
                 user_role = Role.query.filter_by(name='user').first()
                 user.roles.append(user_role)
                 db.session.add(user)
                 db.session.commit()
             result = True
         except ldap.LDAPError:
             connect.unbind_s()
             result = super(MySignInForm, self).validate()
     else:
         from flask import current_app
         user_manager = current_app.user_manager
         user, user_email = user_manager.find_user_by_email(self.email.data)
         if user is None:
             return False
         if user and (user.password is None or (user.social_id is not None and not user.social_id.startswith('local$'))):
             self.email.errors = list(self.email.errors)
             if user.social_id.startswith('google$'):
                 self.email.errors.append(word("You need to log in with Google."))
             elif user.social_id.startswith('azure$'):
                 self.email.errors.append(word("You need to log in with Azure."))
             elif user.social_id.startswith('auth0$'):
                 self.email.errors.append(word("You need to log in with Auth0."))
             elif user.social_id.startswith('twitter$'):
                 self.email.errors.append(word("You need to log in with Twitter."))
             elif user.social_id.startswith('facebook$'):
                 self.email.errors.append(word("You need to log in with Facebook."))
             else:
                 self.email.errors.append(word("You cannot log in this way."))
             return False
         #sys.stderr.write("Trying super validate\n")
         result = super(MySignInForm, self).validate()
         #sys.stderr.write("Super validate response was " + repr(result) + "\n")
     if result is False:
         r.incr(key)
         r.expire(key, daconfig['ban period'])
     elif failed_attempts is not None:
         r.delete(key)
     return result