Beispiel #1
0
def validate_user(user_dict, id):
    def validate_email(id):
        check(user_dict.get('email'))
        user_bymail = User.query.filter_by(
            email=user_dict.get('email')).first()
        logging.info(f'user by mail {user_bymail}')
        user_byid = User.query.filter_by(id=id).first()
        logging.info(f'user by id {user_byid}')

        if user_bymail and user_byid:
            if not user_bymail.email == user_byid.email:
                msg = "Email in uso da un altro utente"
                target_list = ['email']
                logging.error(msg)
                raise FormValidation(error=msg, target=target_list)
        else:
            return True

    if 'ruoli' in user_dict:
        if type(user_dict['ruoli']) is not list:
            msg = "Campo ruoli non valido"
            logging.error(msg)
            raise FormValidation(error=msg, target=['ruoli'])
        else:
            for ruolo in user_dict['ruoli']:
                if ruolo != "admin" and ruolo != "moderatore":
                    msg = f"Ruolo {ruolo} non valido. Ruoli validi ['moderatore', 'admin']"
                    logging.error(msg)
                    raise FormValidation(error=msg, target=['ruoli'])

    if 'email' in user_dict:
        validate_email(id)

    return True
Beispiel #2
0
def validate_user(user_dict):
    def validate_email():
        check(user_dict.get('email'))
        user_bymail = User.query.filter_by(
            email=user_dict.get('email')).first()
        print(f'user by mail {user_bymail}')
        if user_bymail:
            msg = "Email in uso da un altro utente"
            target_list = ['email']
            raise FormValidation(error=msg, target=target_list)
        else:
            return True

    # nessun campo deve essere vuoto
    if user_dict['email'] and user_dict['password'] and user_dict[
            'confirm_password']:
        validate_email()

        if user_dict['password'] == user_dict['confirm_password']:
            print("validato")
            return True
        else:
            msg = "Le password non corrispondono"
            target_list = ['password', 'confirm_password']
            print(msg)
            raise FormValidation(error=msg, target=target_list)
    else:
        msg = "Campo vuoto"
        print(msg)
        target_list = []
        for key in user_dict:
            if not user_dict[key]:
                target_list.append(key)  # lista dei campi vuoti da segnalare

        raise FormValidation(error=msg, target=target_list)
Beispiel #3
0
def validate_user(user_dict):
    def validate_email():
        check(user_dict.get('email'))
        user_bymail = User.query.filter_by(
            email=user_dict.get('email')).first()
        logging.info(f'user by mail {user_bymail}')
        if user_bymail:
            msg = "Email in uso da un altro utente"
            target_list = ['email']
            raise FormValidation(error=msg, target=target_list)
        else:
            return True

    if 'ruoli' in user_dict:
        if type(user_dict['ruoli']) is not list:
            msg = "Campo ruoli non valido"
            raise FormValidation(error=msg, target=['ruoli'])
        else:
            for ruolo in user_dict['ruoli']:
                if ruolo != "admin" and ruolo != "moderatore":
                    msg = f"Ruolo {ruolo} non valido. Ruoli validi ['moderatore', 'admin']"
                    raise FormValidation(error=msg, target=['ruoli'])

    # nessun campo deve essere vuoto
    if user_dict.get('email') and user_dict.get('password') and user_dict.get(
            'confirm_password') and ("ruoli" in user_dict):
        validate_email()

        if user_dict['password'] == user_dict['confirm_password']:
            logging.info("validato")
            return True
        else:
            msg = "Le password non corrispondono"
            target_list = ['password', 'confirm_password']
            logging.error(msg)
            raise FormValidation(error=msg, target=target_list)
    else:
        msg = "Campo vuoto"
        logging.error(msg)
        u1 = User()

        # 2 modi per filtrare i campi necessari
        # due liste + list comprehension
        not_list = ["id", "active", "confirmed_at"]
        target_list = [
            key for key in u1.as_dict()
            if not user_dict.get(key) and key not in not_list
        ]

        # due set + intersezione tra set A-B
        # not_necessary_fields = {"id", "active", "confirmed_at"} # set di campi non necessari per la validazione
        # target_list = set(target_list) # set di campi che comprende sia quelli necessari sia quelli non necessari
        # target_list = list(target_list - not_necessary_fields) # diff set ottiene come output solo campi necessari
        logging.error(target_list)
        raise FormValidation(error=msg, target=target_list)
Beispiel #4
0
def check(email):
    if re.search(regex, email):
        logging.info("Regex Valid Email")
        return True
    else:
        logging.error("Regex Invalid Email")
        raise FormValidation(error='Email non valida', target=['email'])
Beispiel #5
0
 def validate_email():
     check(user_dict.get('email'))
     user_bymail = User.query.filter_by(
         email=user_dict.get('email')).first()
     logging.info(f'user by mail {user_bymail}')
     if user_bymail:
         msg = "Email in uso da un altro utente"
         target_list = ['email']
         raise FormValidation(error=msg, target=target_list)
     else:
         return True
Beispiel #6
0
 def validate_email():
     check(student_dict.get('email'))
     student_bymail = Student.query.filter_by(
         email=student_dict.get('email')).first()
     print(f'student by mail {student_bymail}')
     student_byid = Student.query.filter_by(
         id=student_dict.get('id')).first()
     print(f'student by id {student_byid}')
     if student_bymail and student_byid:
         if not student_bymail.email == student_byid.email:
             msg = "Email in uso da un altro studente"
             target_list = ['email']
             raise FormValidation(error=msg, target=target_list)
     elif student_dict['action'] == 'submit':
         if student_bymail:
             msg = "Email in uso da un altro studente"
             target_list = ['email']
             raise FormValidation(error=msg, target=target_list)
     else:
         return True
Beispiel #7
0
def validate(student_dict):
    def validate_email():
        check(student_dict.get('email'))
        student_bymail = Student.query.filter_by(
            email=student_dict.get('email')).first()
        print(f'student by mail {student_bymail}')
        student_byid = Student.query.filter_by(
            id=student_dict.get('id')).first()
        print(f'student by id {student_byid}')
        if student_bymail and student_byid:
            if not student_bymail.email == student_byid.email:
                msg = "Email in uso da un altro studente"
                target_list = ['email']
                raise FormValidation(error=msg, target=target_list)
        elif student_dict['action'] == 'submit':
            if student_bymail:
                msg = "Email in uso da un altro studente"
                target_list = ['email']
                raise FormValidation(error=msg, target=target_list)
        else:
            return True

    # nessun campo deve essere vuoto
    if student_dict['name'] and student_dict['lastname'] and student_dict[
            'age'] and student_dict['email']:
        validate_email()
        if 18 > int(student_dict['age']) or int(student_dict['age']) > 100:
            msg = "Eta' non valida"
            raise FormValidation(error=msg, target=['age'])
        else:
            print("validato")
            return True
    else:
        msg = "Campo vuoto"
        print(msg)
        target_list = []
        for key in student_dict:
            if not student_dict[key]:
                target_list.append(key)  # lista dei campi vuoti da segnalare

        raise FormValidation(error=msg, target=target_list)
Beispiel #8
0
    def validate_email():
        check(student_dict.get('email'))
        student_bymail = Student.query.filter_by(
            email=student_dict.get('email')).first()
        logging.info(f'student by mail {student_bymail}')

        if student_bymail:
            msg = "Email in uso da un altro studente"
            target_list = ['email']
            logging.error(msg)
            raise FormValidation(error=msg, target=target_list)
        else:
            return True
Beispiel #9
0
def validate(student_dict, id):
    def validate_email(id):
        check(student_dict.get('email'))
        student_bymail = Student.query.filter_by(
            email=student_dict.get('email')).first()
        logging.info(f'student by mail {student_bymail}')
        student_byid = Student.query.filter_by(id=id).first()
        logging.info(f'student by id {student_byid}')

        if student_bymail and student_byid:
            if not student_bymail.email == student_byid.email:
                msg = "Email in uso da un altro studente"
                target_list = ['email']
                logging.error(msg)
                raise FormValidation(error=msg, target=target_list)
        else:
            return True

    # e' possibile non modificare ogni campo

    if 'name' in student_dict and type(student_dict['name']) is not str:
        msg = "Nome' non valido"
        raise FormValidation(error=msg, target=['name'])

    elif 'lastname' in student_dict and type(
            student_dict['lastname']) is not str:
        msg = "Lastname' non valido"
        raise FormValidation(error=msg, target=['lastname'])

    elif ('age' in student_dict and type(student_dict['age']) is not int) or\
            ('age' in student_dict and (18 > int(student_dict['age']) or int(student_dict['age']) > 100)):
        msg = "Age non valida"
        raise FormValidation(error=msg, target=['age'])

    elif 'email' in student_dict:
        validate_email(id)

    else:
        return True
Beispiel #10
0
def validate(student_dict):
    def validate_email():
        check(student_dict.get('email'))
        student_bymail = Student.query.filter_by(
            email=student_dict.get('email')).first()
        logging.info(f'student by mail {student_bymail}')

        if student_bymail:
            msg = "Email in uso da un altro studente"
            target_list = ['email']
            logging.error(msg)
            raise FormValidation(error=msg, target=target_list)
        else:
            return True

    # nessun campo deve essere vuoto
    if student_dict.get('name') and student_dict.get(
            'lastname') and student_dict.get('age') and student_dict.get(
                'email'):
        validate_email()
        if 18 > int(student_dict['age']) or int(student_dict['age']) > 100:
            msg = "Eta' non valida"
            raise FormValidation(error=msg, target=['age'])
        else:
            logging.info("validato")
            return True
    else:
        msg = "Campo vuoto"
        logging.error(msg)
        target_list = []
        s1 = Student()
        for key in s1.as_dict():
            if not student_dict.get(key):
                target_list.append(key)  # lista dei campi vuoti da segnalare

        raise FormValidation(error=msg, target=target_list)
Beispiel #11
0
    def validate_email(id):
        check(user_dict.get('email'))
        user_bymail = User.query.filter_by(
            email=user_dict.get('email')).first()
        logging.info(f'user by mail {user_bymail}')
        user_byid = User.query.filter_by(id=id).first()
        logging.info(f'user by id {user_byid}')

        if user_bymail and user_byid:
            if not user_bymail.email == user_byid.email:
                msg = "Email in uso da un altro utente"
                target_list = ['email']
                logging.error(msg)
                raise FormValidation(error=msg, target=target_list)
        else:
            return True
Beispiel #12
0
def admin():
    if request.method == "POST":
        print("post request")
        user_dict = request.get_json()
        action = user_dict['action']
        print(user_dict)
        print(action)

        if user_dict['action'] == 'edit':
            print("dentro edit")
            try:
                email = user_dict["email"]
                if email and check(user_dict.get('email')):
                    print("email passed regex")
                else:
                    raise FormValidation(error="Mail non valida",
                                         target=['email'])

                user_bymail = User.query.filter_by(
                    email=user_dict.get('email')).first()
                user_byid = User.query.filter_by(
                    id=user_dict.get('id')).first()
                print(f'user by mail {user_bymail}')
                print(f'user by id {user_byid}')
                if user_bymail and user_byid:
                    if not (user_bymail.email == user_byid.email):
                        msg = "Email in uso da un altro utente"
                        target_list = ['email']
                        raise FormValidation(error=msg, target=target_list)

            except FormValidation as err:
                return jsonify(error=err.error, target=err.target)
            else:
                user = User.query.filter_by(id=user_dict.get('id')).first()

                user.email = email

                role_admin = Role.query.filter_by(name='admin').first()
                role_mod = Role.query.filter_by(name='moderatore').first()

                if not role_admin:  # il record admin esiste gia' nella tabella dei ruoli?
                    role_admin = Role(name='admin', description='admin')

                if user_dict["admin"]:  # inviata richiesta di diventare admin?
                    if 'admin' not in user.roles:  # l'utente e' gia' admin?
                        user.roles.append(role_admin)
                else:
                    if 'admin' in user.roles:  # l'utente non e' gia' admin?
                        user.roles.remove(role_admin)

                if not role_mod:  # il record moderatore esiste gia' nella tabella dei ruoli?
                    role_mod = Role(name='moderatore',
                                    description='moderatore')

                if user_dict[
                        "moderatore"]:  # inviata richiesta di diventare moderatore?
                    if 'moderatore' not in user.roles:  # l'utente non e' gia' moderatore?
                        user.roles.append(role_mod)
                else:
                    if 'moderatore' in user.roles:  # l'utente non e' gia' moderatore?
                        user.roles.remove(role_mod)

                db.session.commit()
                flash(f'User {user.email} edited', 'success')
                return jsonify({"redirect": "/home"})

        if user_dict['action'] == 'delete':
            print("dentro delete")
            user = User.query.filter_by(email=user_dict["email"]).first()
            db.session.delete(user)
            db.session.commit()
            flash(f'User {user.email} Removed!', 'success')
            return jsonify({"redirect": '/home'})

        if user_dict['action'] == 'submit':
            print("dentro submit")
            try:
                validate_user(user_dict)
            except FormValidation as err:
                return jsonify(error=err.error, target=err.target)
            else:
                role_admin = Role.query.filter_by(name='admin').first()
                role_mod = Role.query.filter_by(name='moderatore').first()

                hashed_psw = bcrypt.generate_password_hash(
                    user_dict["password"]).decode('utf-8')
                user = User(email=user_dict["email"], password=hashed_psw)

                if user_dict["admin"]:
                    if not role_admin:
                        role_admin = Role(name='admin', description='admin')

                    user.roles.append(role_admin)

                if user_dict["moderatore"]:
                    if not role_mod:
                        role_mod = Role(name='moderatore',
                                        description='moderatore')

                    user.roles.append(role_mod)

                db.session.add(user)
                db.session.commit()
                flash(f'User {user.email} added', 'success')
                return jsonify({"redirect": "/home"})

    if request.method == "GET":
        print("GET method requested")
        id = request.args.get('id')
        return render_template('register.html', title='Register', user_id=id)