예제 #1
0
def signup():
    form = UserForm()
    if request.method == 'POST':
        email = form.data['email']

        q = db.session.query(User).filter(User.email == email)
        check = q.first()
        if check is None:
            user = User()
            user.firstname = form.data['firstname']
            user.lastname = form.data['lastname']
            user.email = form.data['email']
            user.dateofbirth = form.data['dateofbirth']
            user.set_password(form.data['password'])
            db.session.add(user)
            db.session.commit()
            login_user(user)
            return redirect("/")
        else:
            form = UserForm()

            return render_template(
                'signup.html',
                form=form,
                error=True,
                message="The email was used before. Please change the email!")
    if request.method == 'GET':
        return render_template('signup.html', form=form)
예제 #2
0
def create_user():
    form = UserForm()
    if request.method == "POST":
        if form.validate_on_submit():
            new_user = User()
            form.populate_obj(new_user)
            db.session.add(new_user)
            db.session.commit()
            return redirect('/users')
    return render_template('create_user.html', form=form)
예제 #3
0
def create_user():
    form = UserForm()
    if request.method == 'POST':

        if form.validate_on_submit():
            new_user = User()
            form.populate_obj(new_user)
            new_user.set_password(
                form.password.data)  #pw should be hashed with some salt
            db.session.add(new_user)
            db.session.commit()
            return redirect('/users')

    return render_template('create_user.html', form=form)
예제 #4
0
    def test_register(self):
        # Register an user with an already used email
        payload = {
            'email': '*****@*****.**',
            'firstname': 'Admin',
            'lastname': 'Admin',
            'password': '******',
            'dateofbirth': datetime.datetime(2010, 10, 10).strftime('%d/%m/%Y')
        }
        form = UserForm(data=payload)
        self.client.post('/users/create',
                         data=form.data,
                         follow_redirects=True)
        self.assert_template_used('create_user.html')
        self.assert_message_flashed('The email address is already being used.',
                                    'error')

        # Register an user with date of birth > today
        payload = {
            'email': '*****@*****.**',
            'firstname': 'Admin',
            'lastname': 'Admin',
            'password': '******',
            'dateofbirth': datetime.datetime(2020, 10, 10).strftime('%d/%m/%Y')
        }
        form = UserForm(data=payload)
        self.client.post('/users/create',
                         data=form.data,
                         follow_redirects=True)
        self.assert_template_used('create_user.html')
        self.assert_message_flashed('Wrong date of birth.', 'error')

        # Test successful registration
        payload = {
            'email': '*****@*****.**',
            'firstname': 'Admin',
            'lastname': 'Admin',
            'password': '******',
            'dateofbirth': datetime.datetime(2010, 10, 10).strftime('%d/%m/%Y')
        }
        form = UserForm(data=payload)
        self.client.post('/users/create',
                         data=form.data,
                         follow_redirects=True)
        self.assert_template_used('users.html')
        new_user = db.session.query(User).filter(
            User.email == '*****@*****.**').first()
        self.assertIsNotNone(new_user)
예제 #5
0
def signup():
    '''
    GET
    ---
    Opens the signup page.

    Returns:
        200 -> the page has been returned

    POST
    ----
    Registers a user.

    Raises:
        IntegrityError -> there is already a user with the chosen username or e-mail address
    
    Returns:
        409 -> the exception above has been raised
        302 -> the registration was succesful and the user is redirected to its homepage
    '''
    form = UserForm()
    status = 200

    if current_user.is_authenticated:
        return redirect('/')

    if form.validate_on_submit():
        new_user = User()
        form.populate_obj(new_user)
        new_user.set_password(form.password.data)
        db.session.add(new_user)

        try:
            db.session.commit()
            login_user(new_user)
            return redirect('/')
        except IntegrityError as e:
            db.session.rollback()
            status = 409
            if 'user.username' in str(e):
                err = 'This username already exists.'
            elif 'user.email' in str(e):
                err = 'This email is already used.'

            form.email.errors.append(err)

    return render_template('signup.html', form=form), status
예제 #6
0
    def test_modify_user_role_id(self, client):
        """
        With this code is tested the services to perform the user modification
        with service and have the result on db

        Test flow
        - Create user
        - Modify user
        - check user
        - delete user to clean the database
        """
        form = UserForm()
        form.firstname.data = "Vincenzo"
        form.lastname.data = "Palazzo"
        form.password = "******"
        form.phone.data = "12345"
        form.dateofbirth = "12/12/2020"
        form.email.data = "*****@*****.**"
        user = User()
        form.populate_obj(user)
        user = UserService.create_user(user, form.password, 2)
        assert user is not None
        assert user.role_id is 2

        response = login(client, form.email.data, form.password)
        assert response.status_code == 200
        assert "logged_test" in response.data.decode("utf-8")

        formTest = UserForm(obj=user)
        user_modified = UserService.modify_user(formTest, 3)
        assert user is not None
        assert user.role_id is not 2
        UserService.delete_user(user_modified.id)
        user_modified = get_user_with_email(user_modified.email)
        assert user_modified is None
예제 #7
0
def create_user():
    if current_user is not None and hasattr(current_user, 'id'):
        return make_response(
            render_template(
                'error.html',
                message="You are already logged! Redirecting to home page",
                redirect_url="/"), 403)

    form = UserForm()

    if request.method == 'POST':

        if form.validate_on_submit():

            new_user = User()
            form.populate_obj(new_user)
            new_user.role = request.form['role']
            check_already_register = db.session.query(User).filter(
                User.email == new_user.email).first()

            if (check_already_register is not None):
                # already registered
                return render_template('create_user.html', form=form), 403

            new_user.set_password(
                form.password.data)  #pw should be hashed with some salt

            if new_user.role != 'customer' and new_user.role != 'owner':
                return make_response(
                    render_template(
                        'error.html',
                        message=
                        "You can sign in only as customer or owner! Redirecting to home page",
                        redirect_url="/"), 403)

            db.session.add(new_user)
            db.session.commit()
            return redirect('/')
        else:
            # invalid form
            return make_response(
                render_template('create_user.html', form=form), 400)

    return render_template('create_user.html', form=form)
예제 #8
0
def _create_generic_user(role_id: int = 3, name_on_page: str = "customer"):
    """
    This method contains the logic to create a new user with a different role
    :param role_id: role id on database this mean that is possible
    :param name_on_page: name to customize the page inside the template
    :return: response template
    """
    form = UserForm()
    if request.method == "POST":
        if form.validate_on_submit():
            q_user_email = UserService.user_is_present(email=form.email.data)
            q_user_phone = UserService.user_is_present(phone=form.phone.data)
            current_app.logger.error(
                "user with email is null? ".format(q_user_email is None)
            )
            current_app.logger.error(
                "user with phone is null? ".format(q_user_phone is None)
            )
            if (q_user_email is not None) or (q_user_phone is not None):
                return render_template(
                    "create_user.html",
                    form=form,
                    message="Email {} and/or number {} already registered".format(
                        form.email.data, form.phone.data
                    ),
                    type=name_on_page,
                )
            user = User()
            form.populate_obj(user)
            user = UserService.create_user(user, form.password.data, role_id)
            if user is not None and user.authenticate(form.password.data):
                login_user(user)
            DispatcherMessage.send_message(
                REGISTRATION_EMAIL,
                [user.email, user.lastname, "112344"],
            )
            new_role = UserService.get_user_role(role_id)
            if new_role is not None:
                session["ROLE"] = new_role.value
            return redirect("/")
    return render_template("create_user.html", form=form, type=name_on_page)
예제 #9
0
    def test_delete_user_with_email(self):
        """
        This test cases test if the user service are able to
        remove correctly the user inside the DB
        Test flow
        - Create a new user with the service
        - delete a new user with service with user pass
        - check on db if this user is gone
        """

        form = UserForm()
        form.firstname.data = "Vincenzo"
        form.lastname.data = "Palazzo"
        form.password = "******"
        form.phone.data = "12345"
        form.dateofbirth = "12/12/2020"
        form.email.data = "*****@*****.**"
        user = User()
        form.populate_obj(user)
        user = UserService.create_user(user, form.password, 2)
        assert user is not None
        assert user.role_id is 2
        UserService.delete_user(email=user.email)
        user = db.session.query(User).filter_by(email=user.email).first()
        assert user is None
예제 #10
0
def user_data():
    message = None
    if request.method == "POST":
        form = UserEditForm()
        if form.validate_on_submit():
            UserService.modify_user(form)
            return render_template("user_data.html", form=form)
        print(form.errors.items())
        return render_template("user_data.html", form=form, error="Error in the data")
    else:
        q = User.query.filter_by(id=current_user.id).first()
        if q is not None:
            form = UserForm(obj=q)
            return render_template("user_data.html", form=form)
예제 #11
0
def _create_user():
    form = UserForm()
    if request.method == 'POST':

        if form.validate_on_submit():
            # check if the email already exists
            email = form.data['email']
            user = db.session.query(User).filter(User.email == email).first()
            if user is None:
                # check if date of birth < today
                dateofbirth = form.data['dateofbirth']
                if dateofbirth < date.today():
                    new_user = User()
                    form.populate_obj(new_user)
                    new_user.set_password(form.password.data)  # pw should be hashed with some salt
                    db.session.add(new_user)
                    db.session.commit()
                    return redirect('/users')
                else:
                    flash("Wrong date of birth.", 'error')
            else:
                flash("The email address is already being used.", 'error')
    return render_template('create_user.html', form=form, home_url=HOME_URL)
예제 #12
0
def create_user():
    # A connected user cannot create other users
    if hasattr(current_user, 'is_authenticated') and current_user.is_authenticated is True:
        return abort(403)

    form = UserForm()
    if request.method == 'POST':

        if form.validate_on_submit():
            new_user = User()
            form.populate_obj(new_user)
            c = db.session.query(User).filter(new_user.email == User.email)
            if c.first() is None:
                new_user.set_password(form.password.data)  # pw should be hashed with some salt
                db.session.add(new_user)
                db.session.commit()
                return redirect(url_for('auth.login'))
            else:
                flash('Already existing user', category='error')
                return make_response(render_template('create_user.html', form=form), 409)
        else:
            abort(400)

    return render_template('create_user.html', form=form)
예제 #13
0
def create_user_on_db(ran: int = randrange(100000)):
    form = UserForm()
    # form.data["email"] = "alibaba" + str(ran) + "@alibaba.com"
    # form.data["password"] = "******"
    form.firstname.data = "User_{}".format(ran)
    form.lastname.data = "user_{}".format(ran)
    form.password = "******".format(ran)
    form.phone.data = "1234562344{}".format(ran)
    form.dateofbirth = "12/12/2000"
    form.email.data = "alibaba" + str(ran) + "@alibaba.com"
    user = User()
    form.populate_obj(user)
    return UserService.create_user(user, form.password)
예제 #14
0
def create_user():
    if not current_user.is_anonymous:
        return redirect("/", code=302)
    form = UserForm()
    if form.validate_on_submit():
        new_user = User()
        form.populate_obj(new_user)
        new_user.set_password(form.password.data)
        db.session.add(new_user)
        try:
            db.session.commit()
            return login()
        except IntegrityError:
            db.session.rollback()
            form.message = "Seems like this email is already used"

    return render_template('create_user.html', form=form, notlogged=True)
예제 #15
0
    def test_create_user(self):
        """
        test create user
        :return:
        """
        form = UserForm()
        form.firstname.data = "Vincenzo"
        form.lastname.data = "Palazzo"
        form.password = "******"
        form.phone.data = "12345"
        form.dateofbirth = "12/12/2020"
        form.email.data = "*****@*****.**"
        user = User()
        form.populate_obj(user)
        user = UserService.create_user(user, form.password)
        assert user is not None
        assert user.role_id is 3

        db.session.query(User).filter_by(id=user.id).delete()
        db.session.commit()
예제 #16
0
def create_operator():
    """ Create an operator account and login
    
    Error status codes:
        400 -- The request is not valid, the form is filled out incorrectly, a user with the same identifiers already exists or a generic error has occurred
        500 -- A db error
    Success codes:
        200 -- The form is sent
        302 -- The creation was carried out
    """
    form = UserForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            json = DotMap()
            form.populate_obj(json)
            json = json.toDict()

            if json['ssn'] == '':
                json['ssn'] = None

            if json['password'] != json['password_repeat']:
                flash('Passwords do not match', 'warning')
                return make_response(
                    render_template('form.html', form=form, title="Sign in!"),
                    200)

            user = {
                'firstname': json['firstname'],
                'lastname': json['lastname'],
                'email': json['email'],
                'password': generate_password_hash(form.password.data),
                'phone': json['telephone'],
                'rest_id': None,
                'is_operator': True,
                'ssn': json['ssn'],
                'is_admin': False,
                'dateofbirth': json['dateofbirth'].strftime("%Y-%m-%d'"),
                'is_health_authority': False,
                'is_positive': False
            }

            resp, status_code = get_getaway().create_user(userdata=user)
            if resp is None or status_code is None:
                flash("Sorry, an error occured. Please, try again.", "error")
                return make_response(
                    render_template('form.html', form=form, title="Sign in!"),
                    500)
            if status_code == 200 or status_code == 201:
                usr = User(resp.id, True, user['is_admin'],
                           user['is_health_authority'], user['password'],
                           user['rest_id'], user['is_positive'])
                login_user(usr)
                flash('User registerd succesfully', 'success')
                return redirect("/")
            else:
                flash('ERROR' + str(status_code) + str(resp), 'success')
                return make_response(
                    render_template("error.html", error=status_code),
                    status_code)

    return render_template('form.html', form=form, title="Sign in!")