Exemplo n.º 1
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.º 2
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.º 3
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
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)
Exemplo n.º 5
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.º 6
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.º 7
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