Beispiel #1
0
def lwp_tokens():
    """
    returns api tokens info and get posts request: can show/delete or add token in page.
    this function uses sqlite3, require admin privilege
    """
    if session['su'] != 'Yes':
        return abort(403)

    if request.method == 'POST':
        if request.form['action'] == 'add':
            # we want to add a new token
            token = request.form['token']
            description = request.form['description']
            username = session['username']  # we should save the username due to ldap option
            g.db.execute("INSERT INTO api_tokens (username, token, description) VALUES(?, ?, ?)", [username, token,
                                                                                                   description])
            g.db.commit()
            flash(u'Token %s successfully added!' % token, 'success')

    if request.args.get('action') == 'del':
        token = request.args['token']
        g.db.execute("DELETE FROM api_tokens WHERE token=?", [token])
        g.db.commit()
        flash(u'Token %s successfully deleted!' % token, 'success')

    tokens = query_db("SELECT description, token, username FROM api_tokens ORDER BY token DESC")
    return render_template('tokens.html', containers=lxc.ls(), tokens=tokens)
Beispiel #2
0
def login():
    if request.method == 'POST':
        request_username = request.form['username']
        request_passwd = request.form['password']

        current_url = request.form['url']

        if AUTH == 'ldap':
            try:
                l = ldap.initialize('ldap://%s:%d' % (LDAP_HOST, LDAP_PORT))
                l.set_option(ldap.OPT_REFERRALS, 0)
                l.protocol_version = 3
                l.simple_bind(LDAP_BIND_DN, LDAP_PASS)
                q = l.search_s(LDAP_BASE, ldap.SCOPE_SUBTREE, '(&(objectClass=' + OBJECT_CLASS + ')(' + ID_MAPPING + '=' + request_username + '))', [])[0]
                l.bind_s(q[0], request_passwd, ldap.AUTH_SIMPLE)
                #set the parameters for user by ldap objectClass
                user = {
                    'username': q[1][ID_MAPPING][0].decode('utf8'),
                    'name': q[1][DISPLAY_MAPPING][0].decode('utf8'),
                    'su': 'Yes'
                }
            except Exception, e:
                print(str(e))
                user = None
        elif AUTH == 'htpasswd':
            from lwp.utils import check_htpasswd
            user = None
            if check_htpasswd(HTPASSWD_FILE, request_username, request_passwd):
                user = {
                    'username': request_username,
                    'name': request_username,
                    'su': 'Yes'
                }
        elif AUTH == 'pam':
            user = None
            p = pam.pam()
            if p.authenticate(request_username, request_passwd, service=PAM_SERVICE):
                user = {
                    'username': request_username,
                    'name': request_username,
                    'su': 'Yes'
                }
        else:
            request_passwd = hash_passwd(request_passwd)
            user = query_db('select name, username, su from users where username=? and password=?', [request_username, request_passwd], one=True)

        if user:
            session['logged_in'] = True
            session['token'] = get_token()
            session['last_activity'] = int(time.time())
            session['username'] = user['username']
            session['name'] = user['name']
            session['su'] = user['su']
            flash(u'You are logged in!', 'success')

            if current_url == url_for('auth.login'):
                return redirect(url_for('main.home'))
            return redirect(current_url)

        flash(u'Invalid username or password!', 'error')
Beispiel #3
0
def lwp_tokens():
    """
    returns api tokens info and get posts request: can show/delete or add token in page.
    this function uses sqlite3, require admin privilege
    """
    if session["su"] != "Yes":
        return abort(403)

    if request.method == "POST":
        if request.form["action"] == "add":
            # we want to add a new token
            token = request.form["token"]
            description = request.form["description"]
            username = session["username"]  # we should save the username due to ldap option
            g.db.execute(
                "INSERT INTO api_tokens (username, token, description) VALUES(?, ?, ?)", [username, token, description]
            )
            g.db.commit()
            flash(u"Token %s successfully added!" % token, "success")

    if request.args.get("action") == "del":
        token = request.args["token"]
        g.db.execute("DELETE FROM api_tokens WHERE token=?", [token])
        g.db.commit()
        flash(u"Token %s successfully deleted!" % token, "success")

    tokens = query_db("SELECT description, token, username FROM api_tokens ORDER BY token DESC")
    return render_template("tokens.html", containers=lxc.ls(), tokens=tokens)
Beispiel #4
0
def lwp_users():
    """
    returns users and get posts request : can edit or add user in page.
    this funtction uses sqlite3
    """
    if session['su'] != 'Yes':
        return abort(403)

    if AUTH != 'database':
        return abort(403, 'You are using an auth method other that database.')

    try:
        trash = request.args.get('trash')
    except KeyError:
        trash = 0

    su_users = query_db("SELECT COUNT(id) as num FROM users WHERE su='Yes'", [], one=True)

    if request.args.get('token') == session.get('token') and int(trash) == 1 and request.args.get('userid') and \
            request.args.get('username'):
        nb_users = query_db("SELECT COUNT(id) as num FROM users", [], one=True)

        if nb_users['num'] > 1:
            if su_users['num'] <= 1:
                su_user = query_db("SELECT username FROM users WHERE su='Yes'", [], one=True)

                if su_user['username'] == request.args.get('username'):
                    flash(u'Can\'t delete the last admin user : %s' % request.args.get('username'), 'error')
                    return redirect(url_for('main.lwp_users'))

            g.db.execute("DELETE FROM users WHERE id=? AND username=?", [request.args.get('userid'),
                                                                         request.args.get('username')])
            g.db.commit()
            flash(u'Deleted %s' % request.args.get('username'), 'success')
            return redirect(url_for('main.lwp_users'))

        flash(u'Can\'t delete the last user!', 'error')
        return redirect(url_for('main.lwp_users'))

    if request.method == 'POST':
        users = query_db('SELECT id, name, username, su FROM users ORDER BY id ASC')

        if request.form['newUser'] == 'True':
            if not request.form['username'] in [user['username'] for user in users]:
                if re.match('^\w+$', request.form['username']) and request.form['password1']:
                    if request.form['password1'] == request.form['password2']:
                        if request.form['name']:
                            if re.match('[a-z A-Z0-9]{3,32}', request.form['name']):
                                g.db.execute("INSERT INTO users (name, username, password) VALUES (?, ?, ?)",
                                             [request.form['name'], request.form['username'],
                                              hash_passwd(request.form['password1'])])
                                g.db.commit()
                            else:
                                flash(u'Invalid name!', 'error')
                        else:
                            g.db.execute("INSERT INTO users (username, password) VALUES (?, ?)",
                                         [request.form['username'], hash_passwd(request.form['password1'])])
                            g.db.commit()

                        flash(u'Created %s' % request.form['username'], 'success')
                    else:
                        flash(u'No password match', 'error')
                else:
                    flash(u'Invalid username or password!', 'error')
            else:
                flash(u'Username already exist!', 'error')

        elif request.form['newUser'] == 'False':
            if request.form['password1'] == request.form['password2']:
                if re.match('[a-z A-Z0-9]{3,32}', request.form['name']):
                    if su_users['num'] <= 1:
                        su = 'Yes'
                    else:
                        try:
                            su = request.form['su']
                        except KeyError:
                            su = 'No'

                    if not request.form['name']:
                        g.db.execute("UPDATE users SET name='', su=? WHERE username=?", [su, request.form['username']])
                        g.db.commit()
                    elif request.form['name'] and not request.form['password1'] and not request.form['password2']:
                        g.db.execute("UPDATE users SET name=?, su=? WHERE username=?",
                                     [request.form['name'], su, request.form['username']])
                        g.db.commit()
                    elif request.form['name'] and request.form['password1'] and request.form['password2']:
                        g.db.execute("UPDATE users SET name=?, password=?, su=? WHERE username=?",
                                     [request.form['name'], hash_passwd(request.form['password1']), su,
                                      request.form['username']])
                        g.db.commit()
                    elif request.form['password1'] and request.form['password2']:
                        g.db.execute("UPDATE users SET password=?, su=? WHERE username=?",
                                     [hash_passwd(request.form['password1']), su, request.form['username']])
                        g.db.commit()

                    flash(u'Updated', 'success')
                else:
                    flash(u'Invalid name!', 'error')
            else:
                flash(u'No password match', 'error')
        else:
            flash(u'Unknown error!', 'error')

    users = query_db("SELECT id, name, username, su FROM users ORDER BY id ASC")
    nb_users = query_db("SELECT COUNT(id) as num FROM users", [], one=True)
    su_users = query_db("SELECT COUNT(id) as num FROM users WHERE su='Yes'", [], one=True)

    return render_template('users.html', containers=lxc.ls(), users=users, nb_users=nb_users, su_users=su_users)
Beispiel #5
0
 def authenticate(self, username, password):
     hash_password = hash_passwd(password)
     return query_db('select name, username, su from users where username=? and password=?', [username, hash_password], one=True)
Beispiel #6
0
def lwp_users():
    """
    returns users and get posts request : can edit or add user in page.
    this funtction uses sqlite3
    """
    if session["su"] != "Yes":
        return abort(403)

    if AUTH != "database":
        return abort(403, "You are using an auth method other that database.")

    try:
        trash = request.args.get("trash")
    except KeyError:
        trash = 0

    su_users = query_db("SELECT COUNT(id) as num FROM users WHERE su='Yes'", [], one=True)

    if (
        request.args.get("token") == session.get("token")
        and int(trash) == 1
        and request.args.get("userid")
        and request.args.get("username")
    ):
        nb_users = query_db("SELECT COUNT(id) as num FROM users", [], one=True)

        if nb_users["num"] > 1:
            if su_users["num"] <= 1:
                su_user = query_db("SELECT username FROM users WHERE su='Yes'", [], one=True)

                if su_user["username"] == request.args.get("username"):
                    flash(u"Can't delete the last admin user : %s" % request.args.get("username"), "error")
                    return redirect(url_for("main.lwp_users"))

            g.db.execute(
                "DELETE FROM users WHERE id=? AND username=?",
                [request.args.get("userid"), request.args.get("username")],
            )
            g.db.commit()
            flash(u"Deleted %s" % request.args.get("username"), "success")
            return redirect(url_for("main.lwp_users"))

        flash(u"Can't delete the last user!", "error")
        return redirect(url_for("main.lwp_users"))

    if request.method == "POST":
        users = query_db("SELECT id, name, username, su FROM users ORDER BY id ASC")

        if request.form["newUser"] == "True":
            if not request.form["username"] in [user["username"] for user in users]:
                if re.match("^\w+$", request.form["username"]) and request.form["password1"]:
                    if request.form["password1"] == request.form["password2"]:
                        if request.form["name"]:
                            if re.match("[a-z A-Z0-9]{3,32}", request.form["name"]):
                                g.db.execute(
                                    "INSERT INTO users (name, username, password) VALUES (?, ?, ?)",
                                    [
                                        request.form["name"],
                                        request.form["username"],
                                        hash_passwd(request.form["password1"]),
                                    ],
                                )
                                g.db.commit()
                            else:
                                flash(u"Invalid name!", "error")
                        else:
                            g.db.execute(
                                "INSERT INTO users (username, password) VALUES (?, ?)",
                                [request.form["username"], hash_passwd(request.form["password1"])],
                            )
                            g.db.commit()

                        flash(u"Created %s" % request.form["username"], "success")
                    else:
                        flash(u"No password match", "error")
                else:
                    flash(u"Invalid username or password!", "error")
            else:
                flash(u"Username already exist!", "error")

        elif request.form["newUser"] == "False":
            if request.form["password1"] == request.form["password2"]:
                if re.match("[a-z A-Z0-9]{3,32}", request.form["name"]):
                    if su_users["num"] <= 1:
                        su = "Yes"
                    else:
                        try:
                            su = request.form["su"]
                        except KeyError:
                            su = "No"

                    if not request.form["name"]:
                        g.db.execute("UPDATE users SET name='', su=? WHERE username=?", [su, request.form["username"]])
                        g.db.commit()
                    elif request.form["name"] and not request.form["password1"] and not request.form["password2"]:
                        g.db.execute(
                            "UPDATE users SET name=?, su=? WHERE username=?",
                            [request.form["name"], su, request.form["username"]],
                        )
                        g.db.commit()
                    elif request.form["name"] and request.form["password1"] and request.form["password2"]:
                        g.db.execute(
                            "UPDATE users SET name=?, password=?, su=? WHERE username=?",
                            [
                                request.form["name"],
                                hash_passwd(request.form["password1"]),
                                su,
                                request.form["username"],
                            ],
                        )
                        g.db.commit()
                    elif request.form["password1"] and request.form["password2"]:
                        g.db.execute(
                            "UPDATE users SET password=?, su=? WHERE username=?",
                            [hash_passwd(request.form["password1"]), su, request.form["username"]],
                        )
                        g.db.commit()

                    flash(u"Updated", "success")
                else:
                    flash(u"Invalid name!", "error")
            else:
                flash(u"No password match", "error")
        else:
            flash(u"Unknown error!", "error")

    users = query_db("SELECT id, name, username, su FROM users ORDER BY id ASC")
    nb_users = query_db("SELECT COUNT(id) as num FROM users", [], one=True)
    su_users = query_db("SELECT COUNT(id) as num FROM users WHERE su='Yes'", [], one=True)

    return render_template("users.html", containers=lxc.ls(), users=users, nb_users=nb_users, su_users=su_users)