Beispiel #1
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)
Beispiel #2
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)
Beispiel #3
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
Beispiel #4
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)
Beispiel #5
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)
Beispiel #6
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)
Beispiel #7
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)
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)
Beispiel #9
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!")