More code

This commit is contained in:
Arti Zirk 2020-09-22 23:35:30 +03:00
parent 1252f7af9e
commit cf7342035d
7 changed files with 141 additions and 24 deletions

2
.gitignore vendored
View File

@ -65,3 +65,5 @@ target/
venv/ venv/
*.sqlite *.sqlite
ad.json ad.json
ookean_cards.json

41
contrib/ookean_export.py Normal file
View File

@ -0,0 +1,41 @@
from collections import defaultdict
import json
from MySQLdb import _mysql
db = _mysql.connect(host="localhost", db="ookean",
user="root", passwd="salakala")
db.query("""
select persons.name, t2.uid, t2.name from persons join tagowners t on persons.id = t.person_id join tags t2 on t.tag_id = t2.id
where persons.archived is null and t.revoked_date is null and t2.archived is null;
""")
r=db.store_result()
nicknames = {
"Adi": "Aaditya Parashar",
"Artur Kerge": "Artur Vincent Kerge",
"Alexander Sysoev": "Aleksander Sysoev",
"Pavel Kirienko": "Pavel Kirilenko",
"Erwin Orye": "Erwin Rudi J. Orye",
"Martti Rand (Protoskoop OÜ)": "Martti Rand",
"Arttu Valkonen": "Arttu Mikael Valkonen",
"Anima (Aleksandrs Naidjonovs)": "Aleksandrs Naidjonovs"
}
cards = defaultdict(list)
for x in range(r.num_rows()):
name, uid, descr = r.fetch_row()[0]
name, uid, descr = name.decode(), uid.decode(), descr.decode() if descr else descr
name = name.replace("(deactivated)", "")\
.replace("(Deactivated)","").replace("(Paused)", "").replace("(disactive)", "")\
.replace("(Disabled)", "").replace("(Protoskoop)", "")\
.strip()
if name in nicknames:
name = nicknames[name]
cards[name].append({"uid": uid, "descr": descr})
print(f"{name:30} {uid:20} {descr}")
with open("ookean_cards.json", "w") as fp:
json.dump(cards, fp, indent=2)

View File

@ -1,9 +1,31 @@
import sys import sys
from . import application from . import application
def print_help():
print("K-Door webserver")
print(f"Usage: {sys.argv[0]} [PORT|initdb|import_ookean]")
sys.exit(1)
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) > 1: if len(sys.argv) > 1:
cmd = sys.argv[1]
if cmd in {"-h", "--help"}:
print_help()
elif cmd == "initdb":
from .db import initdb
initdb()
sys.exit(0)
elif cmd == "import_ookean":
from .db import import_ookean
import_ookean()
sys.exit(1)
else:
try:
port = int(sys.argv[1]) port = int(sys.argv[1])
except ValueError:
print_help()
else: else:
port = 8080 port = 8080
application.run(host='127.0.0.1', port=port) application.run(host='127.0.0.1', port=port)

View File

@ -59,7 +59,8 @@ class DB:
); );
create table users ( create table users (
id integer primary key, id integer primary key,
user text, distinguished_name text unique,
user text unique,
full_name text, full_name text,
email text, email text,
disabled integer, disabled integer,
@ -91,6 +92,7 @@ class DB:
door_id integer, door_id integer,
keycard_id integer, keycard_id integer,
user_id integer, user_id integer,
log_msg text,
foreign key (door_id) foreign key (door_id)
references doors (id) references doors (id)
@ -116,53 +118,86 @@ class DB:
def add_users(self, users): def add_users(self, users):
self.db.executemany(""" self.db.executemany("""
insert into users(user, full_name, email, disabled, admin) insert into users(distinguished_name, user, full_name, email, disabled, admin)
values(?, ?, ?, ?, ?) values(?, ?, ?, ?, ?, ?)
""", users) """, users)
self.db.commit() self.db.commit()
def list_users(self): def list_users(self):
cur = self.db.execute( cur = self.db.execute("""
"select id, user, full_name, email from users" select users.id, users.user , users.full_name, users.email, users.disabled, count(k.id) as cards from users
left join keycards k on users.id = k.user_id group by users.id order by users.disabled
"""
) )
return cur.fetchall() return cur.fetchall()
def get_user(self, user_id): def get_user(self, user_id):
cur = self.db.execute( cur = self.db.execute(
"select * from users where id = ?", "select id, distinguished_name, user, full_name, email, admin, disabled from users where id = ?",
(user_id, ) (user_id, )
) )
return cur.fetchone() return cur.fetchone()
def get_user_by_name(self, user_name): def get_user_by_name(self, user_name):
cur = self.db.execute( cur = self.db.execute(
"select * from users where user = ?", "select id, distinguished_name, user, full_name, email, admin, disabled from users where user = ?",
(user_name, ) (user_name, )
) )
return cur.fetchone() return cur.fetchone()
def add_keycards(self, keycards):
self.db.executemany("""
insert into keycards(user_id, card_uid, name)
values(?, ?, ?)
""", keycards)
self.db.commit()
@staticmethod @staticmethod
def import_ad(json_file): def import_ad(json_file):
with open(json_file) as fp: with open(json_file) as fp:
json_data = json.load(fp) json_data = json.load(fp)
for user, fields in json_data.items(): for user, fields in json_data.items():
if fields.get("considered_active", False) and \
fields.get("groups", {}).get("floor_access", False):
yield ( yield (
user, fields.get("distinguished_name"),
fields.get("username"),
fields.get("full_name"), fields.get("full_name"),
fields.get("personal_mail"), fields.get("personal_mail"),
0, 0 if fields.get("considered_active") is True and
int(fields.get("groups",{}).get("onboarding", False)) fields.get("groups", {}).get("floor_access") is not False else 1,
0 if fields.get("groups",{}).get("onboarding") is False else 1
) )
def import_ookean(self, json_file):
unmatched = {}
with open(json_file) as fp:
json_data = json.load(fp)
for user, tokens in json_data.items():
self.db.execute("PRAGMA case_sensitive_like = true")
cur = self.db.execute(
"select id, user, distinguished_name from users where full_name like ?",
(f"%{user}%",)
)
user_row = cur.fetchone()
if user_row:
print(f"User {user:20} matched with {user_row['user']:20} ({user_row['distinguished_name']})")
self.add_keycards(((user_row["id"], card["uid"], card["descr"]) for card in tokens))
else:
unmatched[user] = tokens
print(f"Cound not match {len(unmatched)} users")
for user in unmatched:
print(f"User {user}")
def export_db(self, json_file):
for user in self.list_users():
pass
if __name__ == "__main__": def initdb():
dbfile = "../kdoorweb.sqlite" dbfile = "kdoorweb.sqlite"
import os, sys import os, sys
from pprint import pprint from pprint import pprint
try: try:
@ -175,3 +210,13 @@ if __name__ == "__main__":
users = db.list_users() users = db.list_users()
for user in users: for user in users:
print(dict(user)) print(dict(user))
def import_ookean():
dbfile = "kdoorweb.sqlite"
db = DB(dbfile)
db.import_ookean("../contrib/ookean_cards.json")
if __name__ == "__main__":
initdb()

View File

@ -12,10 +12,10 @@
<dl> <dl>
<dt>User</dt> <dt>User</dt>
<dd>{{user}}</dd> <dd>{{user}}</dd>
<dt>Full Name</dt>
<dd>{{full_name}}</dd>
<dt>Email</dt> <dt>Email</dt>
<dd>{{email}}</dd> <dd>{{email}}</dd>
<dt>Distinguished Name</dt>
<dd>{{distinguished_name}}</dd>
</dl> </dl>
<h3>Keycards</h3> <h3>Keycards</h3>

View File

@ -13,8 +13,12 @@
<tbody> <tbody>
% for user in users: % for user in users:
<tr> <tr>
% if user["disabled"]:
<td><s><a href="/info/{{user['id']}}">{{user["full_name"]}}</a></s></td>
% else:
<td><a href="/info/{{user['id']}}">{{user["full_name"]}}</a></td> <td><a href="/info/{{user['id']}}">{{user["full_name"]}}</a></td>
<td>-</td> % end
<td>{{user["cards"]}}</td>
<td>-</td> <td>-</td>
</tr> </tr>
% end % end

View File

@ -82,7 +82,10 @@ def login():
@app.post('/login', skip=[check_auth]) @app.post('/login', skip=[check_auth])
def do_login(db): def do_login(db):
user_name = request.forms.get("user") user_name = request.forms.get("user")
from pprint import pprint
pprint(db.list_users())
user = db.get_user_by_name(user_name) user = db.get_user_by_name(user_name)
print("user:", user)
if user: if user:
print(f"user {dict(user)}") print(f"user {dict(user)}")
login_user(user["id"]) login_user(user["id"])