def setUp(self):
     self.server = app.test_client()
     database.clear()
     self.user1 = database.create_user({'name': 'new user 1'})
     self.user2 = database.create_user({'name': 'new user 2'})
     self.headers_user1 = {'Authorization' : 'token %s' % self.user1['token']}
     self.headers_user2 = {'Authorization': 'token %s' % self.user2['token']}
示例#2
0
def users():
	if not g.user['is_admin']:
		return redirect(url_for('admin'))

	if request.method == 'POST':
		create_user(request.form['username'], request.form['password'], request.form.get('admin', False))
		return redirect(url_for('users'))

	users = query_db("select * from users", [])

	return render_template('admin/users.html', users=users)
示例#3
0
def users():
    if not g.user['is_admin']:
        return redirect(url_for('admin'))

    if request.method == 'POST':
        create_user(request.form['username'], request.form['password'],
                    request.form.get('admin', False))
        return redirect(url_for('users'))

    users = query_db("select * from users", [])

    return render_template('admin/users.html', users=users)
示例#4
0
def submit_register():
    if database.email_exists(request.form.get("email")):
        flash("E-mail " + request.form.get("email") + " ya registrado",
              "error")
        return render_template("register.html")

    if database.user_exists(request.form.get("username")):
        flash(
            "Nombre de usuario " + request.form.get("username") +
            " ya registrado", "error")
        return render_template("register.html")

    ret = database.create_user(request.form.get("email"),
                               request.form.get("username"),
                               request.form.get("password"),
                               request.form.get("fullname"),
                               request.form.get("lastname"),
                               request.form.get("gender"),
                               request.form.get("direction"),
                               request.form.get("bank-account"))

    if not ret:
        flash("Error interno en el registro de los datos", "error")
        return render_template("register.html")

    flash("Usuario registrado correctamente", "success")
    return redirect(url_for("login"))
示例#5
0
def create_user():
    """Creates a new user"""
    try:
        r = request.json
        if (db.create_user(r["username"], r["password"]) == -1):
            result = {'success': False, 'message': 'Account is taken'}
        else:
            result = {'success': True}
    except Exception as e:
        print(e)
        result = {'success': False, 'message': str(e)}
    return jsonify(result)
示例#6
0
def get_users():
    # Creating an output dictionary
    out = {"ok": True, "body": ""}
    body_list = []
    if "GET" in request.method:
        # get_all_users() returns all records from the user table
        form = NameForm()
        raw_data = get_all_users()
        for item in raw_data:
            temp_dict = {
                "first_name": item[0],
                "last_name": item[1],
                "hobbies": item[2]
            }
            body_list.append(temp_dict)
        if not body_list:
            body_list.append(
                {}
            )  # This is done so that when we reference the 0th index on lines 47-50 the code doesn't break
        out["body"] = body_list
        return render_template(
            "about_me.html",
            first_name=out["body"][0].get(
                "first_name"
            ),  # This is just for the sake of being an example, you should never do this in a real app.
            last_name=out["body"][0].get(
                "last_name"
            ),  # Ideally in a real app you would not hardcode the index like we've done here.
            hobbies=out["body"][0].get("hobbies"),
            form=form)
    if "POST" in request.method:
        first_name = request.form.get("first_name")
        last_name = request.form.get("last_name")
        hobbies = request.form.get("hobbies")
        create_user((first_name, last_name, hobbies))
        flash("Created new user!")
        return redirect(url_for("get_users"))
def register():
    if request.method == 'POST':
        # Realizamos una solicitud a la base de datos para ver si existe un usuario con ese nombre
        lista = database.get_user(request.form['Username'])

        # Comprobamos si el usuario existe
        if len(lista) == 1:
            err_text = "El usuario " + request.form[
                'Username'] + " ya existe. Elija otro nombre de usuario"
            context_dict = {'text': err_text}
            return render_template('register.html', err=context_dict)

        else:
            # Creamos un diccionario con los datos del usuario, y se lo mandamos a la funcion create_user para que lo meta en la base de datos
            dict = request.form.copy()
            # El saldo ahora es el income de los usuarios (el dinero que tienen)
            # por ello, su income inicial lo calculamos como un numero mas grande
            dict['saldo'] = random.randint(1, 60000)
            database.create_user(dict)
            return redirect(url_for('login',
                                    username=request.form['Username']))

    else:
        return render_template('register.html')
示例#8
0
def register():
   # if current_user.is_authenticated:
   #     return redirect(url_for('home.index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(UserName=form.username.data)
        new_salt = set_user_salt()
        hashed_password = hash_password(new_salt, form.password.data)
        new_user = create_user(
            role=form.role.data, 
            username=form.username.data, 
            firstname=form.firstname.data,
            lastname=form.lastname.data,
            passwordhash=hashed_password,
            passwordsalt=new_salt)
        if new_user == 'OK':
            flash('Registrace proběhla úspěšně.')
            #return redirect(url_for('auth.login'))
        else:
            flash('Bohužel, registrace byla neúspěšná.')

    return render_template('auth/register.html', title='Register', form=form)
示例#9
0
def create_user():
    data = request.get_json()
    if database.does_user_exist(data['username']):
        return jsonify("User already exists"), 422
    database.create_user(data)
    return jsonify("SUCCESS")
def create_user():
    validate_json(request.json)
    user = database.create_user(request.json)
    return jsonify(user), 201