]> git.datanom.net - liogui.git/commitdiff
Completed User Administration master
authorMichael Rasmussen <mir@datanom.net>
Tue, 26 Aug 2025 16:54:08 +0000 (18:54 +0200)
committerMichael Rasmussen <mir@datanom.net>
Tue, 26 Aug 2025 16:54:08 +0000 (18:54 +0200)
12 files changed:
requirements.txt [new file with mode: 0644]
webapp/auth.py [new file with mode: 0644]
webapp/dashboard.py [new file with mode: 0644]
webapp/db.py [new file with mode: 0644]
webapp/schema.sql [new file with mode: 0644]
webapp/static/style.css [new file with mode: 0644]
webapp/templates/auth/changepwd.html [new file with mode: 0644]
webapp/templates/auth/login.html [new file with mode: 0644]
webapp/templates/auth/register.html [new file with mode: 0644]
webapp/templates/auth/update.html [new file with mode: 0644]
webapp/templates/base.html [new file with mode: 0644]
webapp/templates/dashboard/index.html [new file with mode: 0644]

diff --git a/requirements.txt b/requirements.txt
new file mode 100644 (file)
index 0000000..83ebfb6
--- /dev/null
@@ -0,0 +1,513 @@
+acme==4.0.0
+agate==1.9.1
+agate-dbf==0.2.2
+agate-excel==0.4.1
+agate-sql==0.7.2
+altgraph==0.17.4
+aniso8601==10.0.1
+anyio==4.8.0
+apparmor==4.1.0
+apsw==3.46.0.1
+apt-xapian-index==0.49
+arrow==1.3.0
+asgiref==3.9.1
+asn1crypto==1.5.1
+astroid==3.3.8
+asttokens==3.0.0
+attrs==25.3.0
+autocommand==2.2.2
+babel==2.17.0
+bcrypt==4.2.0
+beautifulsoup4==4.13.4
+black==25.1.0
+blinker==1.9.0
+bmaptool==3.9.0
+boto3==1.37.9
+botocore==1.37.9
+Bottleneck==1.4.2
+Brlapi==0.8.6
+Brotli==1.1.0
+brotlicffi==1.1.0.0
+certbot==4.0.0
+certbot-dns-onecom==0.1.0
+certifi==2025.1.31
+chardet==5.2.0
+charset-normalizer==3.4.3
+click==8.1.8
+colorama==0.4.6
+colorlog==6.9.0
+colour==0.1.5
+ConfigArgParse==1.7
+configobj==5.0.9
+contourpy==1.3.1
+coverage==7.8.2
+crit==4.1.1
+cryptography==43.0.0
+css-parser==1.0.10
+cssselect==1.3.0
+csvkit==2.0.1
+cupshelpers==1.0
+cycler==0.12.1
+dbfread==2.0.7
+dbus-python==1.4.0
+decorator==5.2.1
+defcon==0.10.3
+defusedxml==0.7.1
+Deprecated==1.2.18
+devscripts==2.25.19
+dill==0.4.0
+distlib==0.3.9
+distro==1.9.0
+distro-info==1.14
+dns-lexicon==3.21.1
+dnspython==2.7.0
+docopt==0.6.2
+docutils==0.21.2
+duplicity==3.0.4
+easygui==0.98.1
+EditorConfig==0.17.0
+email_validator==2.2.0
+et_xmlfile==2.0.0
+evdev==1.9.1
+exceptiongroup==1.2.2
+executing==2.2.0
+fasteners==0.18
+feedparser==6.0.11
+fido2==1.2.0
+filelock==3.19.1
+Flask==3.1.1
+Flask-Login==0.6.3
+Flask-Principal==0.4.0
+Flask-RESTful==0.3.10
+Flask-Security==5.6.1
+Flask-SQLAlchemy==3.1.1
+Flask-WTF==1.2.2
+fontPens==0.2.5.dev0
+fonttools==4.57.0
+fqdn==1.5.1
+fs==2.4.16
+gbp==0.9.38
+GDAL==3.11.3
+gpg==1.24.2
+gphoto2==2.5.1
+greenlet==3.1.0
+h11==0.14.0
+h2==4.2.0
+hpack==4.0.0
+html2text==2025.4.15
+html5-parser==0.4.12
+html5lib-modern==1.2
+httpcore==1.0.7
+httplib2==0.22.0
+httpx==0.28.1
+hyperframe==6.0.0
+idna==3.10
+ifaddr==0.2.0
+importlib_metadata==8.7.0
+importlib_resources==6.5.2
+inflate64==1.0.3+ds
+inflect==7.3.1
+iniconfig==1.1.1
+invoke==2.2.0
+iotop==0.6
+ipython==8.35.0
+isodate==0.0.0
+isoduration==20.11.0
+isort==6.0.1
+itsdangerous==2.2.0
+jaraco.context==6.0.1
+jaraco.functools==4.1.0
+jaraco.text==4.0.0
+jdcal==1.0
+jedi==0.19.1
+jeepney==0.9.0
+Jinja2==3.1.6
+jmespath==1.0.1
+josepy==2.0.0
+jsonpointer==2.4
+jsonschema==4.19.2
+jsonschema-specifications==2023.12.1
+kiwisolver==1.4.7
+ldap3==2.9.1
+leather==0.4.0
+legacy-cgi==2.6.3
+legacycrypt==0.3
+lensfun==0.3.4
+LibAppArmor==4.1.0
+libevdev==0.11
+libvirt-python==11.3.0
+linkify-it-py==2.0.3
+logilab-common==2.1.0
+louis==3.33.0
+lxml==5.4.0
+lxml_html_clean==0.4.2
+lz4==4.4.0+dfsg
+Mako==1.3.9.dev0
+Markdown==3.7
+markdown-it-py==3.0.0
+MarkupSafe==2.1.5
+matplotlib==3.10.1+dfsg1
+matplotlib-inline==0.1.7
+mccabe==0.7.0
+mdurl==0.1.2
+mechanize==0.4.10
+mercurial==7.0.1
+meson==1.9.0
+mkchromecast==0.3.9
+monotonic==1.6
+more-itertools==10.7.0
+mpmath==1.3.0
+msal==1.32.3
+msgpack==1.0.3
+multivolumefile==0.2.3
+musicbrainzngs==0.7.1
+mutagen==1.47.0
+mypy_extensions==1.1.0
+mysql-connector-python==9.3.0
+mysqlx-connector-python==9.3.0
+ndiff==0.0.0
+netifaces==0.11.0
+notify2==0.3.1
+ntpsec==1.2.3
+numexpr==2.11.0
+numpy==2.2.4
+oauthlib==3.2.2
+odfpy==1.4.2
+olefile==0.47
+opencv==4.10.0
+openpyxl==3.1.5
+packaging==25.0
+pandas==2.2.3+dfsg
+paramiko==3.5.1
+parsedatetime==2.6
+parso==0.8.4
+passlib==1.7.4
+path-and-address==2.0.1
+pathspec==0.12.1
+pexpect==4.9.0
+pika==1.3.2
+pillow==11.1.0
+Pivy==0.6.10
+platformdirs==4.3.7
+pluggy==1.6.0
+ply==3.11
+pooch==1.8.2
+prompt_toolkit==3.0.51
+protobuf==4.21.12
+psutil==7.0.0
+psutils==3.3.8
+psycopg2==2.9.10
+ptyprocess==0.7.0
+pulsemixer==1.5.1
+pure_eval==0.2.3
+puremagic==1.30
+py==1.11.0
+py-cpuinfo==9.0.0
+py3exiv2==0.12.0
+py7zr==1.0.0+dfsg1
+pyasn1==0.6.1
+pyasyncore==1.0.2
+pybcj==1.0.6+ds
+pycairo==1.27.0
+pychm==0.8.6
+PyChromecast==9.4.0
+pycriu==4.1.1
+pycryptodomex==3.20.0
+pycups==2.0.4
+pycurl==7.45.6
+PyGithub==2.6.1
+Pygments==2.18.0
+PyGObject==3.50.0
+PyICU==2.14
+pyinotify==0.9.6
+pyinstaller==6.15.0
+pyinstaller-hooks-contrib==2025.8
+PyJWT==2.10.1
+pylint==3.3.4
+pymediainfo==7.0.1
+PyNaCl==1.5.0
+pyOpenSSL==25.1.0
+pyotp==2.9.0
+pyparsing==3.1.2
+pyparted==3.13.0
+pypdf==5.4.0
+PyPDF2==2.12.1
+pyppmd==1.2.0+ds
+PyQt5==5.15.11
+PyQt5_sip==12.17.0
+PyQt6==6.9.0
+PyQt6-QScintilla==2.14.1
+PyQt6-WebEngine==6.9.0
+PyQt6_sip==13.10.0
+pyRFC3339==2.0.1
+pysmbc==1.0.25.1
+PySocks==1.7.1
+pysvn==1.9.22
+pytest==8.4.1
+python-apt==3.0.0
+python-dateutil==2.9.0
+python-debian==1.0.1
+python-debianbts==4.1.1
+python-dotenv==1.0.1
+python-pam==2.0.2
+python-slugify==8.0.4
+python-xlib==0.33
+pytimeparse==1.1.5
+pytoolconfig==1.3.1
+pytz==2025.2
+pyudev==0.24.3
+pyxattr==0.8.1
+pyxdg==0.28
+PyYAML==6.0.2
+pyzmq==26.4.0
+pyzstd==0.17.0
+quodlibet==4.7.1
+Radicale==3.5.5
+rapid-photo-downloader==0.9.36
+referencing==0.36.2
+regex==2024.11.6
+reportbug==13.2.0
+repoze.lru==0.7
+requests==2.32.4
+requests-file==2.1.0
+requests-toolbelt==1.0.0
+rfc3339-validator==0.1.4
+rfc3986-validator==0.1.1
+rfc3987==1.3.8
+rich==13.9.4
+roman==5.1
+rope==1.13.0
+Routes==2.5.1
+rpds-py==0.21.0
+rpl==1.14
+s3transfer==0.11.4
+scipy==1.15.3
+scour==0.38.2
+semver==3.0.2
+Send2Trash==1.8.3
+setproctitle==1.3.6
+setuptools==78.1.1
+sgmllib3k==1.0.0
+show-in-file-manager==1.1.4
+simplejson==3.20.1
+six==1.17.0
+sniffio==1.3.1
+sortedcontainers==2.4.0
+soupsieve==2.7
+speedtest-cli==2.1.3
+SQLAlchemy==2.0.43
+stack-data==0.6.3
+svgwrite==1.4.3
+sympy==1.14.0
+tables==3.10.2
+telnetlib==0.0.0
+tenacity==8.4.2+really8.4.1
+terminator==2.1.5
+texttable==1.7.0
+tinycss2==1.4.0
+tldextract==5.3.0
+tomli==2.2.1
+tomlkit==0.13.2
+tornado==6.4.2
+tqdm==4.67.1
+traitlets==5.14.3
+trove-classifiers==2025.4.28.22
+typeguard==4.4.4
+types-aiofiles==24.1
+types-antlr4-python3-runtime==4.13
+types-assertpy==1.1
+types-atheris==2.3
+types-aws-xray-sdk==2.14
+types-beautifulsoup4==4.12
+types-bleach==6.2
+types-boltons==24.1
+types-braintree==4.31
+types-cachetools==5.5
+types-caldav==1.3
+types-capturer==3.0
+types-cffi==1.16
+types-chevron==0.14
+types-click-default-group==1.2
+types-click-spinner==0.1
+types-colorama==0.4
+types-commonmark==0.9
+types-console-menu==0.8
+types-corus==0.10
+types-croniter==5.0.1
+types-dateparser==1.2
+types-decorator==5.1
+types-defusedxml==0.7
+types-Deprecated==1.2.15
+types-docker==7.1
+types-dockerfile-parse==2.0
+types-docutils==0.21
+types-editdistance==0.8
+types-entrypoints==0.4
+types-ExifRead==3.0
+types-fanstatic==1.4
+types-first==2.0
+types-flake8==7.1
+types-flake8-bugbear==24.12.12
+types-flake8-builtins==2.5
+types-flake8-docstrings==1.7
+types-flake8-rst-docstrings==0.3
+types-flake8-simplify==0.21
+types-flake8-typing-imports==1.16
+types-Flask-Cors==5.0
+types-Flask-Migrate==4.0
+types-Flask-SocketIO==5.4
+types-fpdf2==2.8.2
+types-gdb==15.0
+types-gevent==24.11
+types-google-cloud-ndb==2.3
+types-greenlet==3.1
+types-hdbcli==2.23
+types-html5lib==1.1
+types-httplib2==0.22
+types-humanfriendly==10.0
+types-hvac==2.3
+types-ibm-db==3.2.4
+types-icalendar==6.1
+types-influxdb-client==1.45
+types-inifile==0.4
+types-JACK-Client==0.5
+types-Jetson.GPIO==2.1
+types-jmespath==1.0
+types-jsonschema==4.23
+types-jwcrypto==1.5
+types-keyboard==0.13
+types-ldap3==2.9
+types-libsass==0.23
+types-lupa==2.2
+types-lzstring==1.0
+types-m3u8==6.0
+types-Markdown==3.7
+types-mock==5.1
+types-mypy-extensions==1.0
+types-mysqlclient==2.2
+types-nanoid==2.0.0
+types-netaddr==1.3
+types-netifaces==0.11
+types-networkx==3.4.2
+types-oauthlib==3.2
+types-objgraph==3.6
+types-olefile==0.47
+types-openpyxl==3.1.5
+types-opentracing==2.4
+types-paramiko==3.5
+types-parsimonious==0.10
+types-passlib==1.7
+types-passpy==1.0
+types-peewee==3.17.8
+types-pep8-naming==0.14
+types-pexpect==4.9
+types-pika-ts==1.3
+types-polib==1.2
+types-portpicker==1.6
+types-protobuf==5.29.1
+types-psutil==6.1
+types-psycopg2==2.9.10
+types-pyasn1==0.6
+types-pyaudio==0.2
+types-PyAutoGUI==0.9
+types-pycocotools==2.0
+types-pycurl==7.45.4
+types-pyfarmhash==0.4
+types-pyflakes==3.2
+types-pygit2==1.15
+types-Pygments==2.18
+types-pyinstaller==6.11
+types-pyjks==20.0
+types-PyMySQL==1.1
+types-pynput==1.7.7
+types-pyOpenSSL==24.1
+types-pyRFC3339==2.0.1
+types-PyScreeze==1.0.1
+types-pyserial==3.5
+types-pysftp==0.2
+types-pytest-lazy-fixture==0.6
+types-python-crontab==3.2
+types-python-datemath==3.0.1
+types-python-dateutil==2.9
+types-python-http-client==3.3.7
+types-python-jenkins==1.8
+types-python-jose==3.3
+types-python-nmap==0.7
+types-python-xlib==0.33
+types-pytz==2024.2
+types-pywin32==308
+types-pyxdg==0.28
+types-PyYAML==6.0
+types-qrbill==1.1
+types-qrcode==8.0
+types-regex==2024.11.6
+types-reportlab==4.2.5
+types-requests==2.32
+types-requests-oauthlib==2.0
+types-retry==0.9
+types-RPi.GPIO==0.7
+types-s2clientprotocol==5
+types-seaborn==0.13.2
+types-Send2Trash==1.8
+types-setuptools==75.6
+types-shapely==2.0
+types-simplejson==3.19
+types-singledispatch==4.1
+types-six==1.17
+types-slumber==0.7
+types-str2bool==1.1
+types-tabulate==0.9
+types-tensorflow==2.18.0
+types-TgCrypto==1.2
+types-toml==0.10
+types-toposort==1.10
+types-tqdm==4.67
+types-translationstring==1.4
+types-tree-sitter-languages==1.10
+types-ttkthemes==3.2
+types-ujson==5.10
+types-unidiff==0.7
+types-untangle==1.2
+types-usersettings==1.1
+types-uWSGI==2.0
+types-vobject==0.9.9
+types-waitress==3.0.1
+types-WebOb==1.8
+types-whatthepatch==1.0
+types-workalendar==17.0
+types-WTForms==3.2.1
+types-wurlitzer==3.1
+types-xdgenvpy==3.0
+types-xmltodict==0.14
+types-zstd==1.5
+types-zxcvbn==4.4
+typing_extensions==4.14.1
+uc-micro-py==1.0.3
+ufw==0.36.2
+unattended-upgrades==0.1
+unicodedata2==15.1.0
+Unidecode==1.4.0
+unidiff==0.7.5
+uritemplate==4.1.1
+urllib3==2.5.0
+vboxapi==1
+virtualenv==20.34.0
+vobject==0.9.8
+watchdog==6.0.0
+wcwidth==0.2.13
+webcolors==1.13
+webencodings==0.5.1
+WebOb==1.8.9
+websockets==15.0.1
+Werkzeug==3.1.3
+wheel==0.46.1
+wrapt==1.15.0
+WTForms==3.2.1
+xdg==5
+xlrd==2.0.1
+xxhash==0.0.0
+yt-dlp==2025.8.22
+zeroconf==0.147.0
+zipp==3.21.0
+zope.interface==7.2
+zopfli==0.2.3.post1
diff --git a/webapp/auth.py b/webapp/auth.py
new file mode 100644 (file)
index 0000000..3a2fb40
--- /dev/null
@@ -0,0 +1,254 @@
+import functools
+from flask import (
+    Blueprint, flash, g, redirect, render_template, request, session, url_for,  abort
+)
+from werkzeug.security import check_password_hash, generate_password_hash
+
+
+from webapp.db import get_db
+
+bp = Blueprint('auth', __name__, url_prefix='/auth')
+
+@bp.route('/login', methods=('GET', 'POST'))
+def login():
+    if request.method == 'POST':
+        username = request.form['username']
+        password = request.form['password']
+        db = get_db()
+        error = None
+        user = db.execute(
+            'SELECT u.*, p.name FROM user u join permissions p on u.perm = p.id WHERE u.username = ?', (username,)
+        ).fetchone()
+
+        if user is None:
+            error = 'Incorrect username.'
+        elif not check_password_hash(user['password'], password):
+            error = 'Incorrect password.'
+
+        if error is None:
+            session.clear()
+            session['user_id'] = user['id']
+            session['user_perm'] = user['name']
+            return redirect(url_for('index'))
+
+        flash(error)
+    """db.execute(
+            "insert into user (username,password,perm) values (?,?,?)",
+            ('mir', generate_password_hash('Dupago'), 9),)
+    db.commit()"""
+
+    return render_template('auth/login.html')
+
+@bp.before_app_request
+def load_logged_in_user():
+    user_id = session.get('user_id')
+
+    if user_id is None:
+        g.user = None
+    else:
+        g.user = get_db().execute(
+            'SELECT u.*, p.name FROM user u join permissions p on u.perm = p.id WHERE u.id = ?', (user_id,)
+        ).fetchone()
+
+@bp.route('/logout')
+def logout():
+    session.clear()
+    return redirect(url_for('index'))
+
+def login_required(view):
+    @functools.wraps(view)
+    def wrapped_view(**kwargs):
+        if g.user is None:
+            return redirect(url_for('auth.login'))
+
+        return view(**kwargs)
+
+    return wrapped_view
+
+@bp.route('/register', methods=('GET', 'POST'))
+@login_required
+def register():
+    if request.method == 'POST':
+        if session.get('user_perm') != 'ADMIN':
+            abort(403)
+        username = request.form['username']
+        password = request.form['password']
+        confirm = request.form['confirm']
+        perm = request.form['perm']
+        db = get_db()
+        error = None
+
+        if not username:
+            error = 'Username is required.'
+        elif not password:
+            error = 'Password is required.'
+        elif password != confirm:
+            error = 'Confirmation of password failed.'
+
+        if error is None:
+            if not perm:
+                perm = 'USER'
+            else:
+                perm = perm.upper()
+            try:
+                row = get_db().execute('SELECT id FROM permissions where name = ?', (perm,)).fetchone()
+                db.execute(
+                    "INSERT INTO user (username, password, perm) VALUES (?, ?, ?)",
+                    (username, generate_password_hash(password), row[0]),
+                )
+                db.commit()
+            except db.IntegrityError:
+                error = f"User {username} is already registered."
+            except TypeError:
+                error = f"Permission '{perm}' is invalid."
+            else:
+                return redirect(url_for("dashboard.index"))
+
+        flash(error)
+
+    perms = get_db().execute('SELECT name FROM permissions').fetchall()
+
+    return render_template('auth/register.html', perms=[row[0] for row in perms])
+
+@bp.route('/changepwd/<id>', methods=('GET', 'POST'))
+@login_required
+def changepwd(id):
+    if request.method == 'POST':
+        oldpwd = request.form['oldpwd']
+        password = request.form['password']
+        confirm = request.form['confirm']
+        db = get_db()
+        error = None
+        id = int(id)
+        print(f"id: {id} oldpwd: {oldpwd} password: {password} confirm: {confirm} new: {generate_password_hash(password)} perm: {session.get('user_perm')}")
+        user = db.execute(
+            "select * from user where id = ?",
+            (id, ) 
+        ).fetchone()
+        if session.get('user_perm') == 'ADMIN':
+            if not password:
+                error = 'Password is required.'
+            elif password != confirm:
+                error = 'Confirmation of password failed.'
+        else:
+            if not oldpwd:
+                error = 'Old Password is required.'
+            elif not password:
+                error = 'Password is required.'
+            elif password != confirm:
+                error = 'Confirmation of password failed.'
+            elif not check_password_hash(user['password'],  oldpwd):
+                error = "Incorrect old Password."
+
+        if error is None:
+            try:
+                db.execute(
+                    "UPDATE user SET password = ? WHERE id = ?",
+                    (generate_password_hash(password), id),
+                )
+                db.commit()
+            except db.IntegrityError:
+                error = "User does not exist."
+            except TypeError:
+                error = "Permission is invalid."
+            else:
+                return redirect(url_for("dashboard.index"))
+
+        flash(error)
+
+    return render_template('auth/changepwd.html')
+
+@bp.route('/update', methods=('GET', 'POST'))
+@login_required
+def update():
+    if request.method == 'POST':
+        if session.get('user_perm') != 'ADMIN':
+            abort(403)
+        username = request.form['username']
+        password = request.form['password']
+        perm = request.form['perm']
+        db = get_db()
+        error = None
+
+        if not username:
+            error = 'Username is required.'
+        elif not password:
+            error = 'Password is required.'
+
+        if error is None:
+            if not perm:
+                perm = 'USER'
+            else:
+                perm = perm.upper()
+            try:
+                row = get_db().execute('SELECT id FROM permissions where name = ?', (perm,)).fetchone()
+                db.execute(
+                    "INSERT INTO user (username, password, perm) VALUES (?, ?, ?)",
+                    (username, generate_password_hash(password), row[0]),
+                )
+                db.commit()
+            except db.IntegrityError:
+                error = f"User {username} is already registered."
+            except TypeError:
+                error = f"Permission '{perm}' is invalid."
+            else:
+                return redirect(url_for("dashboard.index"))
+
+        flash(error)
+
+    perm = get_db().execute("""SELECT * FROM permissions""").fetchall()
+
+    user = get_db().execute("""
+        SELECT u.id, u.username, p.name FROM
+            user u join permissions p on u.perm = p.id
+    """).fetchall()
+
+    return render_template('auth/update.html', perms=perm, users=user)
+
+@bp.route('/userupdate/<id>', methods=('POST',))
+@login_required
+def userupdate(id):
+    if session.get('user_perm') != 'ADMIN':
+        abort(403)
+
+    content = request.json
+    id = int(id)
+    perm_id = content['perm_id']
+    print("Updating {0} perm = {1}".format(id, perm_id))
+    db = get_db()
+    try:
+        db.execute(
+          "UPDATE user set perm = ? where id = ?",
+          (perm_id, id),
+        )
+        db.commit()
+    except db.IntegrityError:
+        error = f"User {id} does not exist."
+    except TypeError:
+        error = f"Permission '{perm_id}' is invalid."
+    else:
+        return render_template('dashboard/index.html')
+
+#    logger.error(error)
+
+@bp.route('/userdelete/<id>', methods=('POST',))
+@login_required
+def userdelete(id):
+    if session.get('user_perm') != 'ADMIN':
+        abort(403)
+
+    print("Deleting {0}".format(id))
+    id = int(id)
+    db = get_db()
+    try:
+        db.execute(
+          "DELETE FROM user where id = ?",
+          (id, ),
+        )
+        db.commit()
+    except db.IntegrityError:
+        error = f"User {id} does not exist."
+    else:
+        return render_template('dashboard/index.html')
+
+#    logger.error(error)
diff --git a/webapp/dashboard.py b/webapp/dashboard.py
new file mode 100644 (file)
index 0000000..58bd6b9
--- /dev/null
@@ -0,0 +1,21 @@
+from flask import (
+    Blueprint, flash, g, redirect, render_template, session, request, url_for
+)
+from werkzeug.exceptions import abort
+
+from webapp.auth import login_required
+from webapp.db import get_db
+
+bp = Blueprint('dashboard', __name__)
+
+@bp.route('/')
+@login_required
+def index():
+    """db = get_db()
+    posts = db.execute(
+        'SELECT p.id, title, body, created, author_id, username'
+        ' FROM post p JOIN user u ON p.author_id = u.id'
+        ' ORDER BY created DESC'
+    ).fetchall()"""
+    return render_template('dashboard/index.html', perm=session.get('user_perm'))
+
diff --git a/webapp/db.py b/webapp/db.py
new file mode 100644 (file)
index 0000000..868bf94
--- /dev/null
@@ -0,0 +1,43 @@
+import sqlite3
+from datetime import datetime
+
+import click
+from flask import current_app, g
+
+def init_db():
+    db = get_db()
+
+    with current_app.open_resource('schema.sql') as f:
+        db.executescript(f.read().decode('utf8'))
+
+@click.command('init-db')
+def init_db_command():
+    """Clear the existing data and create new tables."""
+    init_db()
+    click.echo('Initialized the database.')
+
+sqlite3.register_converter(
+    "timestamp", lambda v: datetime.fromisoformat(v.decode())
+)
+
+def init_app(app):
+    app.teardown_appcontext(close_db)
+    app.cli.add_command(init_db_command)
+
+def get_db():
+    if 'db' not in g:
+        g.db = sqlite3.connect(
+            current_app.config['DATABASE'],
+            detect_types=sqlite3.PARSE_DECLTYPES
+        )
+        g.db.row_factory = sqlite3.Row
+
+    return g.db
+
+
+def close_db(e=None):
+    db = g.pop('db', None)
+
+    if db is not None:
+        db.close()
+
diff --git a/webapp/schema.sql b/webapp/schema.sql
new file mode 100644 (file)
index 0000000..749818d
--- /dev/null
@@ -0,0 +1,20 @@
+DROP TABLE IF EXISTS user;
+DROP TABLE IF EXISTS permissions;
+
+CREATE TABLE permissions (
+  id INTEGER PRIMARY KEY,
+  name TEXT NOT NULL
+);
+
+INSERT INTO permissions VALUES (1, 'USER');
+INSERT INTO permissions VALUES (3, 'SUPERUSER');
+INSERT INTO permissions VALUES (9, 'ADMIN');
+
+CREATE TABLE user (
+  id INTEGER PRIMARY KEY AUTOINCREMENT,
+  username TEXT UNIQUE NOT NULL,
+  password TEXT NOT NULL,
+  perm INTEGER DEFAULT 1,
+  FOREIGN KEY (perm) REFERENCES permissions (id)
+);
+
diff --git a/webapp/static/style.css b/webapp/static/style.css
new file mode 100644 (file)
index 0000000..4d16f27
--- /dev/null
@@ -0,0 +1,27 @@
+html { font-family: sans-serif; background: #eee; padding: 1rem; }
+body { max-width: 960px; margin: 0 auto; background: white; }
+h1 { font-family: serif; color: #377ba8; margin: 1rem 0; }
+a { color: #377ba8; }
+hr { border: none; border-top: 1px solid lightgray; }
+nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; }
+nav h1 { flex: auto; margin: 0; }
+nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; }
+nav ul  { display: flex; list-style: none; margin: 0; padding: 0; }
+nav ul li a, nav ul li span, header .action { display: block; padding: 0.5rem; }
+.content { padding: 0 1rem 1rem; }
+.content > header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; }
+.content > header h1 { flex: auto; margin: 1rem 0 0.25rem 0; }
+.flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; }
+.post > header { display: flex; align-items: flex-end; font-size: 0.85em; }
+.post > header > div:first-of-type { flex: auto; }
+.post > header h1 { font-size: 1.5em; margin-bottom: 0; }
+.post .about { color: slategray; font-style: italic; }
+.post .body { white-space: pre-line; }
+.content:last-child { margin-bottom: 0; }
+.content form { margin: 1em 0; display: flex; flex-direction: column; }
+.content label { font-weight: bold; margin-bottom: 0.5em; }
+.content input, .content textarea { margin-bottom: 1em; }
+.content textarea { min-height: 12em; resize: vertical; }
+input.danger { color: #cc2f2e; }
+input[type=submit] { align-self: start; min-width: 10em; }
+
diff --git a/webapp/templates/auth/changepwd.html b/webapp/templates/auth/changepwd.html
new file mode 100644 (file)
index 0000000..803f4fa
--- /dev/null
@@ -0,0 +1,17 @@
+{% extends 'base.html' %}
+
+{% block header %}
+  <h1>{% block title %}Change Password{% endblock %}</h1>
+{% endblock %}
+
+{% block content %}
+  <form method="post">
+    <label for="oldpwd">Current Password</label>
+    <input type="password" name="oldpwd" id="oldpwd"/>
+    <label for="password">Password</label>
+    <input type="password" name="password" id="password" required/>
+    <label for="confirm">Confirm</label>
+    <input type="password" name="confirm" id="confirm" required/>
+    <input type="submit" value="Change Password"/>
+  </form>
+{% endblock %}
diff --git a/webapp/templates/auth/login.html b/webapp/templates/auth/login.html
new file mode 100644 (file)
index 0000000..9c8287e
--- /dev/null
@@ -0,0 +1,16 @@
+{% extends 'base.html' %}
+
+{% block header %}
+  <h1>{% block title %}Log In{% endblock %}</h1>
+{% endblock %}
+
+{% block content %}
+  <form method="post">
+    <label for="username">Username</label>
+    <input name="username" id="username" required/>
+    <label for="password">Password</label>
+    <input type="password" name="password" id="password" required/>
+    <input type="submit" value="Log In"/>
+  </form>
+{% endblock %}
+
diff --git a/webapp/templates/auth/register.html b/webapp/templates/auth/register.html
new file mode 100644 (file)
index 0000000..81eaab6
--- /dev/null
@@ -0,0 +1,19 @@
+{% extends 'base.html' %}
+
+{% block header %}
+  <h1>{% block title %}Register{% endblock %}</h1>
+{% endblock %}
+
+{% block content %}
+  <form method="post">
+    <label for="username">Username</label>
+    <input name="username" id="username" required/>
+    <label for="password">Password</label>
+    <input type="password" name="password" id="password" required/>
+    <label for="confirm">Confirm</label>
+    <input type="password" name="confirm" id="confirm" required/>
+    <label for="permissions">Permissions - {{ perms }}</label>
+    <input name="perm" id="perm"/>
+    <input type="submit" value="Register"/>
+  </form>
+{% endblock %}
diff --git a/webapp/templates/auth/update.html b/webapp/templates/auth/update.html
new file mode 100644 (file)
index 0000000..2281ca0
--- /dev/null
@@ -0,0 +1,75 @@
+{% extends 'base.html' %}
+
+{% block header %}
+  <h1>{% block title %}User Administration{% endblock %}</h1>
+  <a class="action" href="{{ url_for('index') }}">Index</a>
+{% endblock %}
+
+{% block content %}
+  <table>
+         <tr>
+                 <th>Username</th><th>Permission</th><th>Action</th>
+         </tr>
+  {% for user in users %}
+         <tr>
+                 <td>{{ user.username }}</td>
+                 <td>
+                         <select name="perm" id="perm{{user.id}}">
+                 {% for perm in perms %}
+                   {% if perm.name == user.name %}
+                   <option value="{{ perm.id }}" selected>{{ perm.name }}</option>
+                   {% else %}
+                     <option value="{{ perm.id }}">{{ perm.name }}</option>
+                   {% endif %}
+                 {% endfor %}
+                 </select>
+                 </td>
+                 <td>
+           |
+          {% if g.user.id == user.id %}
+                         <button type="button" onclick="submit_update({{user.id}})">update</button>
+              | <button type="button" onclick="submit_chpwd({{user.id}})">change password</button>
+          {% else %}
+              <button type="button" onclick="submit_update({{user.id}})">update</button>
+              | <button type="button" onclick="submit_delete({{user.id}})">delete</button>
+              | <button type="button" onclick="submit_chpwd({{user.id}})">change password</button>
+          {% endif %}
+              </td>
+         </tr>
+  {% endfor %}
+  </table>
+  <script type="text/javascript">
+function submit_update(id) {
+    var perm =  document.getElementById("perm"+id).value;
+    var url = '/auth/userupdate/'+id;
+   fetch(url, {
+    method: 'POST',
+    headers: {
+        'Content-Type': 'application/json'
+    },
+    body: JSON.stringify({ "perm_id": parseInt(perm) })
+    })
+    return true;
+}
+</script>
+<script type="text/javascript">    
+function submit_delete(id) {
+   fetch('/auth/userdelete/'+id, {
+    method: 'POST',
+    headers: {
+        'Content-Type': 'application/json'
+    },
+    body: ""
+     })
+   document.location.replace('/auth/update'); 
+   return true;
+  }
+  </script>
+<script type="text/javascript">    
+function submit_chpwd(id) {
+   document.location.replace('/auth/changepwd/'+id); 
+   return true;
+  }
+  </script>
+{% endblock %}
+
diff --git a/webapp/templates/base.html b/webapp/templates/base.html
new file mode 100644 (file)
index 0000000..200c6e2
--- /dev/null
@@ -0,0 +1,23 @@
+<!doctype html>
+<title>{% block title %}{% endblock %} - LIU ADMIN</title>
+<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"/>
+<nav>
+  <h1>LIU ADMIN</h1>
+  <ul>
+    {% if g.user %}
+       <li><span>{{ g.user['username'] }}</span></li>
+       <li><a href="{{ url_for('auth.logout') }}">Log Out</a></li>
+    {% else %}
+       <li><a href="{{ url_for('auth.login') }}">Log In</a></li>
+    {% endif %}
+  </ul>
+</nav>
+<section class="content">
+  <header>
+    {% block header %}{% endblock %}
+  </header>
+  {% for message in get_flashed_messages() %}
+    <div class="flash">{{ message }}</div>
+  {% endfor %}
+  {% block content %}{% endblock %}
+</section>
diff --git a/webapp/templates/dashboard/index.html b/webapp/templates/dashboard/index.html
new file mode 100644 (file)
index 0000000..503d276
--- /dev/null
@@ -0,0 +1,29 @@
+{% extends 'base.html' %}
+
+{% block header %}
+  <h1>{% block title %}Dashboard{% endblock %}</h1>
+  {% if g.user and perm == 'ADMIN' %}
+  <a class="action" href="{{ url_for('auth.register') }}">New User</a>
+  <a class="action" href="{{ url_for('auth.update') }}">Manage Users</a>
+  {% endif %}
+{% endblock %}
+
+{% block content %}
+  {% for post in posts %}
+    <article class="post">
+      <header>
+        <div>
+          <h1>{{ post['title'] }}</h1>
+          <div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div>
+        </div>
+        {% if g.user['id'] == post['author_id'] %}
+          <a class="action" href="{{ url_for('blog.update', id=post['id']) }}">Edit</a>
+        {% endif %}
+      </header>
+      <p class="body">{{ post['body'] }}</p>
+    </article>
+    {% if not loop.last %}
+      <hr>
+    {% endif %}
+  {% endfor %}
+{% endblock %}
This page took 0.931725 seconds and 5 git commands to generate.