예제 #1
0
def userListExport():
    if not es.isAuthorized("usermgmt"):
        return "ERR_ACCESS_DENIED", 403
    data = StringIO()
    w = csv.writer(data,
                   delimiter=';',
                   quotechar='"',
                   quoting=csv.QUOTE_MINIMAL)
    w.writerow(('lastname', 'firstname', 'short', 'username', 'groups'))
    dbconn = db.database()
    dbconn.execute(
        "SELECT id, lastname, firstname, short, username FROM people")
    for user in dbconn.fetchall():
        groups = ''
        dbconn2 = db.database()
        dbconn2.execute(
            "select name from groups where id in(select group_id from people_has_groups where people_id='"
            + user['id'] + "');")
        first = True
        for g in dbconn2.fetchall():
            if first:
                first = False
            else:
                groups = groups + ';'
            groups = groups + g["name"]
        w.writerow((user["lastname"], user["firstname"], user["short"],
                    user["username"], groups))
    response = make_response(data.getvalue())
    response.headers[
        "Content-Disposition"] = "attachment; filename=userList.csv"
    response.headers["Content-Type"] = "text/csv"
    return response
    def event(self, service, current_status):
        if (bool(service['last_checked_status']) == current_status):
            # No change, send no alerts
            return

        if (current_status == False):
            # Service is now offline
            self.send_alert(service, False)

        if (current_status == True):
            # Service is now online
            self.send_alert(service, True)

        database().db_update_status(service, current_status)
예제 #3
0
def setupAdmin():
    if os.path.exists(config.CONFIG_ADMINUSER_FILE):
        return "ERR_SETUP_ALREADY_DONE", 403
    else:
        dir = directory.directory()
        if dir.exists(request.form.get("user"), "users"):
            return "ERR_FOLDER_EXISTS", 500
        id = idsrv.getNew()
        dbconn = db.database()
        dbconn.execute("INSERT INTO people (id, firstname, lastname, username, email, smb_homedir, preferredname, persistant) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", (id, request.form.get("firstname"), request.form.get("lastname"), request.form.get("user"), request.form.get("email"), "/home/users/" + request.form.get("user"), request.form.get("firstname") + " " + request.form.get("lastname"), 1))
        dbconn.execute("INSERT INTO userpassword (people_id, unix_hash, smb_hash, hint) VALUES (%s, %s, %s, %s)", (id, hash.unix(request.form.get("password")), hash.samba(request.form.get("password")), request.form.get("pwhint")))
        dbconn.execute("INSERT INTO people_has_groups (people_id, group_id) VALUES (%s, (SELECT id FROM groups WHERE name = 'root'))", (id,))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        lu = ldap.users()
        if not lu.update(id) == 0:
            return "ERR_LDAP_ERROR", 500
        if not dir.create(request.form.get("user"), "users") == 0 and not dir.setMode(request.form.get("user"), "users", "511"):
            return "ERR_CREATE_HOMEFOLDER", 500
        dbconn.execute("SELECT unix_userid FROM people WHERE id = %s LIMIT 1", (id,))
        result = dbconn.fetchone()
        if not dir.setOwner(request.form.get("user"), "users", result["unix_userid"]):
            return "ERR_CREATE_HOMEFOLDER", 500
        open(config.CONFIG_ADMINUSER_FILE, "a").close()
        return "SUCCESS", 200
예제 #4
0
def createSession():
    bf = bruteforceProtection()
    timeout = bf.isBlocked(request.form.get("uname"))
    if timeout > 0:
        return jsonify({
            "status": "ERR_TOO_MANY_FAILED_ATTEMPTS",
            "timeout": timeout
        }), 200
    dbconn = database()
    dbconn.execute("SELECT unix_hash, P.id FROM userpassword UP INNER JOIN people P ON UP.people_id = P.id WHERE P.username = %s", (request.form.get("uname"),))
    results = dbconn.fetchall()
    if not len(results) == 1:
        return "ERR_USERNAME_NOT_UNIQUE", 403
    if passlib.hash.ldap_salted_sha1.verify(request.form.get("passwd"), results[0]["unix_hash"]):
        user = apiUser(results[0]["id"])
        login_user(user)
        pCheck = permissionCheck()
        gMember = groupMembership()
        bf.successfulLogin(request.form.get("uname"))
        return jsonify({
            "status": "SUCCESS",
            "permissions": pCheck.get(current_user.username),
            "groups": gMember.getGroupsOfUser(current_user.username)
        }), 200
    else:
        timeout = bf.failedLogin(request.form.get("uname"))
        return jsonify({
            "status": "ERR_ACCESS_DENIED",
            "timeout": timeout
        }), 401
예제 #5
0
def specificGroup(id):
    if not es.isAuthorized("usermgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    lg = ldap.groups()
    if request.method == "GET":
        dbconn.execute("SELECT name, info FROM groups WHERE id = %s LIMIT 1",
                       (id, ))
        group = dbconn.fetchone()
        group["permissions"] = []
        group["users"] = []
        dbconn.execute(
            "SELECT P.id FROM permission P INNER JOIN groups_has_permission GHP ON P.id = GHP.permission_id INNER JOIN groups G ON G.id = GHP.group_id WHERE G.id = %s",
            (id, ))
        for permission in dbconn.fetchall():
            group["permissions"].append(permission["id"])
        dbconn.execute(
            "SELECT P.id FROM people P INNER JOIN people_has_groups PHG ON P.id = PHG.people_id INNER JOIN groups G ON G.id = PHG.group_id WHERE G.id = %s",
            (id, ))
        for user in dbconn.fetchall():
            group["users"].append(user["id"])
        return jsonify(group), 200
    elif request.method == "DELETE":
        if not lg.delete(id) == 0:
            return "ERR_LDAP_ERROR", 500
        dbconn.execute("DELETE FROM groups WHERE id = %s", (id, ))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        return "SUCCESS", 200
def fixUser(id):
    if not es.isAuthorized("usermgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    ldapUsers = ldap.users()
    dbconn.execute(
        "SELECT P.id, P.firstname, P.lastname, P.preferredname, P.username, P.smb_homedir, P.email, H.smb_hash, H.unix_hash, P.unix_userid FROM people P INNER JOIN userpassword H ON H.people_id = P.id WHERE P.id = %s",
        (id, ))
    user = dbconn.fetchone()
    check = checkers.checkLdapUserEntry(user)
    if check == False or isinstance(check, list):
        ldapResult = ldapUsers.update(id)
        if ldapResult == -1:
            return "ERR_LDAP_ERROR", 500
        if ldapResult == -2:
            return "ERR_DATABASE_ERROR", 500
    else:
        return "ERR_ALL_DONE", 200
    try:
        removeError = requests.delete(
            url="http://localhost:25252/removeError/" + id +
            "/ERR_LDAP_ENTRY_MISSING/1")
    except:
        return "ERR_CONNECTION_ERROR", 500
    try:
        removeError = requests.delete(
            url="http://localhost:25252/removeError/" + id +
            "/ERR_LDAP_ENTRY_INCOMPLETE/1")
    except:
        return "ERR_CONNECTION_ERROR", 500
    return "SUCCESS", 200
예제 #7
0
def profile(id):
    if not es.isAuthorized("devimgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    if request.method == "GET":
        dbconn.execute("SELECT name, comment, networklockDefault FROM devprofile WHERE id = %s", (id,))
        profile = dbconn.fetchone()
        profile["groups"] = []
        profile["shares"] = []
        dbconn.execute("SELECT group_id FROM devprofile_has_groups WHERE devprofile_id = %s", (id,))
        for group in dbconn.fetchall():
            profile["groups"].append(group["group_id"])
        dbconn.execute("SELECT shares_id FROM devprofile_has_shares WHERE devprofile_id = %s", (id,))
        for share in dbconn.fetchall():
            profile["shares"].append(share["shares_id"])
        return jsonify(profile), 200
    elif request.method == "PUT":
        dbconn.execute("UPDATE devprofile SET name = %s, comment = %s, networklockDefault = %s WHERE id = %s", (request.form.get("name"), request.form.get("comment"), request.form.get("networklockDefault"), id))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        return "SUCCESS", 200
    elif request.method == "DELETE":
        dbconn.execute("SELECT COUNT(*) AS count FROM device D INNER JOIN devprofile DP ON DP.id = D.devprofile_id WHERE DP.id = %s", (id,))
        count = dbconn.fetchone()["count"]
        if not count == 0:
            return "ERR_PROFILE_IN_USE", 409
        dbconn.execute("DELETE FROM devprofile WHERE id = %s", (id,))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        return "SUCCESS", 200
예제 #8
0
def listShares(id, gid):
    if not es.isAuthorized(["usermgmt", "devimgmt"]):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    if request.method == "POST":
        permissions = 1
        if request.form.get("permissions"):
            permissions = int(request.form.get("permissions"))
        dbconn.execute(
            "INSERT INTO groups_has_shares (shares_id, group_id, permission) VALUES (%s, %s, %s)",
            (id, gid, permissions))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        if not samba.update():
            return "ERR_UPDATE_SAMBA", 500
        return "SUCCESS", 201
    elif request.method == "PUT":
        dbconn.execute(
            "UPDATE groups_has_shares SET permission = %s WHERE shares_id = %s AND group_id = %s",
            (request.form.get("permission"), id, gid))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        if not samba.update():
            return "ERR_UPDATE_SAMBA", 500
        return "SUCCESS", 200
    elif request.method == "DELETE":
        dbconn.execute(
            "DELETE FROM groups_has_shares WHERE shares_id = %s AND group_id = %s",
            (id, gid))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        if not samba.update():
            return "ERR_UPDATE_SAMBA", 500
        return "SUCCESS", 200
예제 #9
0
def device(id):
    if not es.isAuthorized("devimgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    if request.method == "GET":
        dbconn.execute(
            "SELECT D.id, D.name, D.comment, D.devprofile_id AS devprofile, D.registered, D.networklock, D.lastknownIPv4 as ipv4, D.lastknownIPv6 as ipv6, D.requiresLogin, HW.address, HW.type as hardwareAddressType, D.people_id, D.room, D.teacher FROM device D INNER JOIN hardwareidentifier HW on HW.device_id = D.id WHERE D.id = %s",
            (id, ))
        device = dbconn.fetchone()
        device["logins"] = []
        dbconn.execute(
            "SELECT info, timestamp, people_id, type, affected FROM localLoginLog WHERE device_id = %s",
            (id, ))
        for logEntry in dbconn.fetchall():
            device["logins"].append(logEntry)
        return jsonify(device), 200
    elif request.method == "PUT":
        dbconn.execute(
            "UPDATE device SET name = %s, comment = %s, devprofile_id = %s, networklock = %s, requiresLogin = %s, teacher = %s, room = %s WHERE id = %s",
            (request.form.get("name"), request.form.get("comment"),
             request.form.get("devprofile"), request.form.get("networklock"),
             request.form.get("requiresLogin"), request.form.get("teacher"),
             request.form.get("room"), request.form.get("id")))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        return "SUCCESS", 200
    elif request.method == "DELETE":
        dbconn.execute("DELETE FROM device WHERE id = %s", (id, ))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        return "SUCCESS", 200
예제 #10
0
def getCoursePDF(id):
    dbconn = database()
    pCheck = permissionCheck()
    if "grouplst" not in pCheck.get(current_user.username):
        return "ERR_NOT_ALLOWED", 403
    courseName = cl.getCourseName(id)
    pdf = {"name": courseName, "content": "data:application/pdf;base64,"}
    tableCode = ""
    style = False
    for member in cl.getCourseDetails(id, True):
        name = member["lastname"]+', '+member["firstname"] if not member["lastname"] == "" else "-"
        email = member["email"] if not member["email"] == "" else "-"
        birthdate = member["birthdate"] if not member["birthdate"] == "" else "-"
        cssClass = " class=\"alt\"" if style else ""
        style = not style
        tableCode += "<tr" + cssClass + "><td>" + name + "</td><td>" + email + "</td><td>" + birthdate + "</td></tr>"
    htmlCode = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Kursliste " + courseName + "</title></head><body><h1>Kursliste " + courseName + "</h1><p>Erzeugt am " + datetime.datetime.now().strftime("%d.%m.%Y um %H:%M:%S") + "</p><div class=\"datagrid\"><table><thead><tr><th style=\"background-color:#1155B9;\">Name</th><th>E-Mail</th><th>Geburtsdatum</th></tr></thead><tbody></tbody>" + tableCode + "</table></div><p>PDF-Datei erzeugt mit PhilleConnect.</p></body></html>"
    options = {
        "page-size": "A4",
        "margin-top": "0.25in",
        "margin-right": "0.5in",
        "margin-bottom": "0.25in",
        "margin-left": "0.5in",
        "encoding": "UTF-8",
        "title": "Kursliste " + courseName
    }
    pdfCode = pdfkit.from_string(htmlCode, False, options=options, css="/usr/local/bin/selfservice/pdf.css")
    pdf["content"] += base64.b64encode(pdfCode).decode("UTF-8")
    return jsonify(pdf), 200
def fixFolder(id):
    if not es.isAuthorized("usermgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    dir = directory.directory()
    dbconn.execute("SELECT username, unix_userid FROM people WHERE id = %s",
                   (id, ))
    user = dbconn.fetchone()
    check = checkers.checkHomeFolder(user)
    if check == 1:
        if dir.create(user["username"], "users") < 0:
            return "ERR_CREATE_HOMEFOLDER", 500
        if not dir.setMode(user["username"], "users", "511"):
            return "ERR_FOLDER_ERROR", 500
    if check >= 1:
        if not dir.setOwner(user["username"], "users", user["unix_userid"]):
            return "ERR_FOLDER_ERROR", 500
    try:
        removeError = requests.delete(
            url="http://localhost:25252/removeError/" + id +
            "/ERR_HOMEFOLDER_MISSING/1")
    except:
        return "ERR_CONNECTION_ERROR", 500
    try:
        removeError = requests.delete(
            url="http://localhost:25252/removeError/" + id +
            "/ERR_HOMEFOLDER_PERMISSIONS/1")
    except:
        return "ERR_CONNECTION_ERROR", 500
    return "SUCCESS", 200
예제 #12
0
def updateIpfire():
    if os.path.exists("/tmp/customhosts"):
        os.remove("/tmp/customhosts")
    if os.path.exists("/tmp/customgroups"):
        os.remove("/tmp/customgroups")
    dbconn = db.database()
    dbconn.execute("SELECT lastknownIPv4, address, networklock FROM device D INNER JOIN hardwareidentifier HW ON HW.device_id = D.id")
    with open("/tmp/customhosts", "w") as customhosts:
        with open("/tmp/customgroups", "w") as customgroups:
            counter = 1
            for machine in dbconn.fetchall():
                customhosts.write(str(counter) + "," + machine["address"] + ",ip," + machine["lastknownIPv4"] + "/255.255.255.255\n")
                if machine["networklock"] == 0:
                    customgroups.write(str(counter) + ",blocked,," + machine["address"] + ",Custom Host\n")
    configfile = cf.configfile()
    sshConnection = ssh.ssh(configfile.get("ipfire", "url"), int(configfile.get("ipfire", "port")), "philleconnect", configfile.get("ipfire", "password"))
    if sshConnection == False:
        return False
    if not sshConnection.put("/tmp/customhosts", "/var/ipfire/fwhosts/customhosts"):
        return False
    if not sshConnection.put("/tmp/customgroups", "/var/ipfire/fwhosts/customgroups"):
        return False
    if not sshConnection.exec("/usr/local/bin/firewallctrl"):
        return False
    sshConnection.close()
    return True
예제 #13
0
def listDevices():
    if not es.isAuthorized("devimgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    dbconn.execute("SELECT name, comment, devprofile_id AS devprofile, people_id, networklock, screenlock, requiresLogin, id, room, teacher FROM device")
    devices = []
    for device in dbconn.fetchall():
        devices.append(device)
    return jsonify(devices), 200
예제 #14
0
def listPermissions():
    if not es.isAuthorized("usermgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    permissions = []
    dbconn.execute("SELECT id, name, info FROM permission")
    for permission in dbconn.fetchall():
        permissions.append(permission)
    return jsonify(permissions), 200
예제 #15
0
 def getName(self, id, user=False):
     query = "SELECT username AS name FROM people WHERE id = %s LIMIT 1" if user else "SELECT name FROM groups WHERE id = %s LIMIT 1"
     dbconn = db.database()
     try:
         dbconn.execute(query, (id, ))
         result = dbconn.fetchone()
         return result["name"]
     except:
         return False
예제 #16
0
def getNew():
    dbconn = db.database()
    dbconn.execute("SELECT id FROM people")
    ids = []
    for (id) in dbconn.fetchall():
        ids.append(id)
    id = "NOT_AN_ID"
    while id == "NOT_AN_ID" or id in ids:
        id = hash.sha256(str(time.time()) + es.randomString())
    return id
예제 #17
0
def listUsers():
    gMember = groupMembership()
    if not gMember.checkGroupMembership(current_user.username, "teachers"):
        return "ERR_NOT_ALLOWED", 403
    dbconn = database()
    dbconn.execute("SELECT P.id, preferredname, username FROM people P INNER JOIN people_has_groups PHG ON PHG.people_id = P.id INNER JOIN groups G ON G.id = PHG.group_id INNER JOIN groups_has_permission GHP ON GHP.group_id = G.id INNER JOIN permission PM ON PM.id = GHP.permission_id WHERE PM.detail = 'pwalwrst' ORDER BY username")
    users = []
    for user in dbconn.fetchall():
        users.append({"id":user["id"],"name":user["preferredname"] + " (" + user["username"] + ")"})
    return jsonify(users), 200
예제 #18
0
def listEmptyGroups():
    if not es.isAuthorized("usermgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    groups = []
    dbconn.execute(
        "SELECT id FROM groups WHERE type = 3 AND id NOT IN (SELECT group_id AS id FROM people_has_groups)"
    )
    for group in dbconn.fetchall():
        groups.append(group["id"])
    return jsonify(groups), 200
예제 #19
0
def listProfiles():
    if not es.isAuthorized("devimgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    dbconn.execute(
        "SELECT name, comment, networklockDefault, allowVNC, id FROM devprofile"
    )
    profiles = []
    for profile in dbconn.fetchall():
        profiles.append(profile)
    return jsonify(profiles), 200
예제 #20
0
def getCourseDetails(id, separateNames=False):
    dbconn = database()
    if separateNames:
        dbconn.execute(
            "SELECT lastname, firstname, email, DATE_FORMAT(birthdate, '%d.%m.%Y') AS birthdate FROM people P INNER JOIN people_has_groups PHG ON P.id = PHG.people_id INNER JOIN groups G ON G.id = PHG.group_id WHERE G.id = %s ORDER BY lastname, firstname",
            (id, ))
    else:
        dbconn.execute(
            "SELECT preferredname AS name, lastname, firstname, email, DATE_FORMAT(birthdate, '%d.%m.%Y') AS birthdate FROM people P INNER JOIN people_has_groups PHG ON P.id = PHG.people_id INNER JOIN groups G ON G.id = PHG.group_id WHERE G.id = %s ORDER BY lastname, firstname",
            (id, ))
    return dbconn.fetchall()
예제 #21
0
def saveEmail():
    dbconn = database()
    dbconn.execute("UPDATE people SET email = %s WHERE username = %s", (request.form.get("email"), current_user.username))
    if not dbconn.commit():
        return "ERR_DATABASE_ERROR", 500
    dbconn.execute("SELECT id FROM people WHERE username = %s", (current_user.username,))
    result = dbconn.fetchone()
    ldap = requests.post(url="http://pc_admin/api/public/usercheck/" + result["id"])
    if not ldap.text == "SUCCESS":
        return "ERR_LDAP_ERROR", 500
    return "SUCCESS", 200
예제 #22
0
def checkUser(id):
    dbconn = db.database()
    ldapUsers = ldap.users()
    dbconn.execute("SELECT P.id, P.firstname, P.lastname, P.preferredname, P.username, P.smb_homedir, P.email, H.smb_hash, H.unix_hash, P.unix_userid FROM people P INNER JOIN userpassword H ON H.people_id = P.id WHERE P.id = %s", (id,))
    user = dbconn.fetchone()
    check = checkers.checkLdapUserEntry(user)
    if check == False or isinstance(check, list):
        ldapResult = ldapUsers.update(id)
        if ldapResult == -1:
            return "ERR_LDAP_ERROR", 500
        if ldapResult == -2:
            return "ERR_DATABASE_ERROR", 500
    return "SUCCESS", 200
예제 #23
0
def updatePassword():
    dbconn = database()
    dbconn.execute("SELECT id FROM people WHERE username = %s", (current_user.username,))
    result = dbconn.fetchone()
    if not request.form.get("password1") == request.form.get("password2"):
        return "ERR_PASSWORDS_DIFFERENT", 500
    dbconn.execute("UPDATE userpassword SET unix_hash = %s, smb_hash = %s, hint = %s, autogen = 0, cleartext = NULL WHERE people_id = %s", (hash.unix(request.form.get("password1")), hash.samba(request.form.get("password1")), request.form.get("hint"), result["id"]))
    if not dbconn.commit():
        return "ERR_DATABASE_ERROR", 500
    ldap = requests.post(url = "http://pc_admin/api/public/usercheck/" + result["id"])
    if not ldap.text == "SUCCESS":
        return "ERR_LDAP_ERROR", 500
    return "SUCCESS", 200
예제 #24
0
def getCourseCSV(id):
    dbconn = database()
    pCheck = permissionCheck()
    if "grouplst" not in pCheck.get(current_user.username):
        return "ERR_NOT_ALLOWED", 403
    csv = {
        "name": cl.getCourseName(id),
        "content": "data:text/csv;charset=utf-8,Nachname;Vorname;E-Mail;Geburtsdatum\n"
    }
    for member in cl.getCourseDetails(id, True):
        row = member["lastname"] + ";" + member["firstname"] + ";" + member["email"] + ";" + member["birthdate"] + "\n"
        csv["content"] += row
    return jsonify(csv), 200
예제 #25
0
def runUpdate(previousVersion):
    if (compareVersions(previousVersion, "2.0.102") == 1):
        dbconn = db.database()
        dbconn.execute(
            "INSERT INTO permission (name, info, detail) VALUES (\"Passwort selbst zurücksetzen\", \"Nutzer kann sein Passwort selbst zurücksetzen, wenn eine E-Mail Adresse eingetragen ist.\", \"emailrst\")"
        )
        dbconn.execute(
            "INSERT INTO permission (name, info, detail) VALUES (\"Gruppenlisten einsehen\", \"Nutzer kann für all seine Gruppen eine Liste der Mitglieder einsehen und laden.\", \"grouplst\")"
        )
        dbconn.execute(
            "CREATE TABLE IF NOT EXISTS `schoolconnect`.`mailreset` (`time` TIMESTAMP NOT NULL, `token` VARCHAR(512) NOT NULL, `people_id` VARCHAR(64) NOT NULL, `unix_hash` TEXT NOT NULL, `smb_hash` TEXT NOT NULL, PRIMARY KEY (`time`, `people_id`), UNIQUE INDEX `token_UNIQUE` (`token` ASC), INDEX `fk_mailreset_people1_idx` (`people_id` ASC), CONSTRAINT `fk_mailreset_people1` FOREIGN KEY (`people_id`) REFERENCES `schoolconnect`.`people` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB;"
        )
        dbconn.commit()
예제 #26
0
def manageGroupPermissions(id, gid):
    if not es.isAuthorized("usermgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    if request.method == "POST":
        dbconn.execute("INSERT INTO groups_has_permission (group_id, permission_id) VALUES (%s, %s)", (gid, id))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        return "SUCCESS", 200
    elif request.method == "DELETE":
        dbconn.execute("DELETE FROM groups_has_permission WHERE group_id = %s AND permission_id = %s", (gid, id))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        return "SUCCESS", 200
예제 #27
0
def createGroup():
    if not es.isAuthorized("usermgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    lg = ldap.groups()
    failed = False
    if request.form.get("name") == "":
        return "ERR_INPUT_ERROR", 500
    dbconn.execute("INSERT INTO groups (name, info, type) VALUES (%s, %s, %s)",
                   (request.form.get("name"), request.form.get("info"),
                    request.form.get("type")))
    if not dbconn.commit():
        return "ERR_DATABASE_ERROR", 500
    id = dbconn.getId()
    if not lg.create(id) == 0:
        return "ERR_LDAP_ERROR", 500
    if request.form.get("permissions"):
        permissions = []
        for permission in json.loads(request.form.get("permissions")):
            permissions.append((id, permission))
        dbconn.execute(
            "INSERT INTO groups_has_permission (group_id, permission_id) VALUES (%s, %s)",
            permissions)
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
    usersToAdd = []
    if request.form.get("fromgroup"):
        for group in request.form.get("source"):
            dbconn.execute(
                "SELECT P.id FROM people P INNER JOIN people_has_groups PHG ON P.id = PHG.people_id INNER JOIN groups G ON G.id = PHG.group_id WHERE G.id = %s",
                (group, ))
            for user in dbconn.fetchall():
                if not user in usersToAdd:
                    usersToAdd.append((id, user["id"]))
    if request.form.get("users"):
        for user in json.loads(request.form.get("users")):
            usersToAdd.append((id, user))
    for element in usersToAdd:
        element = (id, element)
    dbconn.execute(
        "INSERT INTO people_has_groups (group_id, people_id) VALUES (%s, %s)",
        usersToAdd)
    if not dbconn.commit():
        return "ERR_DATABASE_ERROR", 500
    for (id, element) in usersToAdd:
        if not lg.addUser(element, id) == 0:
            failed = True
    if failed:
        return "ERR_LDAP_ERROR", 500
    return str(id), 201
예제 #28
0
def listUsers():
    if not es.isAuthorized("usermgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    users = []
    dbconn.execute("SELECT id, firstname, lastname, username, email, DATE_FORMAT(birthdate, '%Y-%m-%d') AS birthdate, persistant FROM people")
    for user in dbconn.fetchall():
        ids = []
        dbconn.execute("SELECT G.id AS id FROM groups G INNER JOIN people_has_groups PHG ON PHG.group_id = G.id INNER JOIN people P ON P.id = PHG.people_id WHERE P.id = %s", (user["id"],))
        for group in dbconn.fetchall():
            ids.append(group["id"])
        user["groups"] = ids
        users.append(user)
    return jsonify(users), 200
예제 #29
0
def profileShares(id, sid):
    if not es.isAuthorized("devimgmt"):
        return "ERR_ACCESS_DENIED", 403
    dbconn = db.database()
    if request.method == "POST":
        dbconn.execute("INSERT INTO devprofile_has_shares (devprofile_id, shares_id) VALUES (%s, %s)", (id, sid))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        return "SUCCESS", 200
    elif request.method == "DELETE":
        dbconn.execute("DELETE FROM devprofile_has_shares WHERE devprofile_id = %s AND shares_id = %s", (id, sid))
        if not dbconn.commit():
            return "ERR_DATABASE_ERROR", 500
        return "SUCCESS", 200
예제 #30
0
def createResetSession():
    isResetEnabled = os.environ.get("EMAIL_RESET_ENABLED")
    if not isResetEnabled.lower() == "true":
        return "ERR_SERVICE_DISABLED", 500
    dbconn = database()
    dbconn.execute(
        "SELECT COUNT(*) AS num, id, email, firstname FROM people WHERE username = %s",
        (request.form.get("username"), ))
    result = dbconn.fetchone()
    if not result["num"] == 1:
        return "ERR_USER_NOT_FOUND", 500
    pCheck = permissionCheck()
    permissions = pCheck.get(request.form.get("username"))
    if "emailrst" not in permissions:
        return "ERR_NOT_ALLOWED", 500
    if not request.form.get("password1") == request.form.get("password2"):
        return "ERR_PASSWORDS_DIFFERENT", 500
    if result["email"] == "" or result["email"] is None:
        return "ERR_NO_EMAIL", 500
    dbconn.execute(
        "SELECT COUNT(*) AS num, time FROM mailreset WHERE people_id = %s",
        (result["id"], ))
    oldTokens = dbconn.fetchone()
    if oldTokens["num"] > 0:
        earliestCreation = datetime.datetime.now() - datetime.timedelta(days=1)
        if oldTokens["time"] >= earliestCreation:
            return "ERR_OPEN_RESET_REQUEST", 500
        else:
            dbconn.execute("DELETE FROM mailreset WHERE people_id = %s",
                           (result["id"], ))
            if not dbconn.commit():
                return "ERR_DATABASE_ERROR", 500
    token = es.randomString(128)
    dbconn.execute(
        "INSERT INTO mailreset (time, token, people_id, unix_hash, smb_hash) VALUES (NOW(), %s, %s, %s, %s)",
        (token, result["id"], hash.unix(request.form.get("password1")),
         hash.samba(request.form.get("password1"))))
    if not dbconn.commit():
        return "ERR_DATABASE_ERROR", 500
    mailstatus = email.sendResetEmail(result["email"], token,
                                      result["firstname"])
    if mailstatus == -1:
        return "ERR_SMTP_CONNECTION_REFUSED", 500
    elif mailstatus == -2:
        return "ERR_SMTP_CREDENTIALS_ERROR", 500
    elif mailstatus <= -3:
        return "ERR_OTHER_SMTP_ERROR", 500
    return "SUCCESS", 200