Compare commits
22 Commits
v2.0.0.dev
...
develop
Author | SHA1 | Date |
---|---|---|
Tim Gröger | 607b29027b | |
Tim Gröger | df02808fb7 | |
Tim Gröger | 7dd3321246 | |
Tim Gröger | 2f7fdec492 | |
Tim Gröger | 81080404fb | |
Tim Gröger | 0570a9a32f | |
Tim Gröger | c06a12faaa | |
Tim Gröger | 4f20a94f60 | |
Tim Gröger | 001ef13014 | |
Tim Gröger | 0ae334620b | |
Tim Gröger | 645e2865a6 | |
Tim Gröger | bddb11d1b4 | |
Tim Gröger | cab172dc65 | |
Tim Gröger | b40d40644d | |
Tim Gröger | 319889ee43 | |
Tim Gröger | 4be7cccadb | |
Tim Gröger | 9077c9fd11 | |
Tim Gröger | d7428b2ed1 | |
Tim Gröger | 5bab4a7cde | |
Tim Gröger | d8028c4681 | |
Tim Gröger | 8b15a45902 | |
Tim Gröger | ae583a6d18 |
|
@ -0,0 +1,37 @@
|
|||
"""add name and description to api_key
|
||||
|
||||
Revision ID: 49118ea16b56
|
||||
Revises: f9aa4cafa982
|
||||
Create Date: 2024-10-14 08:15:16.348090
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
import flaschengeist
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "49118ea16b56"
|
||||
down_revision = "f9aa4cafa982"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table("api_key", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("name", sa.String(length=32), nullable=True))
|
||||
batch_op.add_column(sa.Column("description", sa.String(length=255), nullable=True))
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
|
||||
with op.batch_alter_table("api_key", schema=None) as batch_op:
|
||||
batch_op.drop_column("description")
|
||||
batch_op.drop_column("name")
|
||||
|
||||
# ### end Alembic commands ###
|
|
@ -0,0 +1,41 @@
|
|||
"""Add APIKeys
|
||||
|
||||
Revision ID: f9aa4cafa982
|
||||
Revises: 20482a003db8
|
||||
Create Date: 2024-10-11 13:04:21.877288
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
import flaschengeist
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "f9aa4cafa982"
|
||||
down_revision = "20482a003db8"
|
||||
branch_labels = ()
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"api_key",
|
||||
sa.Column("expires", flaschengeist.database.types.UtcDateTime(), nullable=True),
|
||||
sa.Column("token", sa.String(length=32), nullable=True),
|
||||
sa.Column("lifetime", sa.Integer(), nullable=True),
|
||||
sa.Column("id", flaschengeist.database.types.Serial(), nullable=False),
|
||||
sa.Column("user_id", flaschengeist.database.types.Serial(), nullable=True),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["user.id"], name=op.f("fk_api_key_user_id_user")),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_api_key")),
|
||||
sa.UniqueConstraint("token", name=op.f("uq_api_key_token")),
|
||||
)
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("api_key")
|
||||
# ### end Alembic commands ###
|
|
@ -89,6 +89,7 @@ def main(*args, **kwargs):
|
|||
from .docs_cmd import docs
|
||||
from .run_cmd import run
|
||||
from .install_cmd import install
|
||||
from .docker_cmd import docker
|
||||
|
||||
# Override logging level
|
||||
environ.setdefault("FG_LOGGING", logging.getLevelName(LOGGING_MAX))
|
||||
|
@ -98,4 +99,5 @@ def main(*args, **kwargs):
|
|||
cli.add_command(install)
|
||||
cli.add_command(plugin)
|
||||
cli.add_command(run)
|
||||
cli.add_command(docker)
|
||||
cli(*args, **kwargs)
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
import click
|
||||
from click.decorators import pass_context
|
||||
from flask.cli import with_appcontext
|
||||
from os import environ
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.controller import pluginController
|
||||
from werkzeug.exceptions import NotFound
|
||||
import traceback
|
||||
|
||||
|
||||
@click.group()
|
||||
def docker():
|
||||
pass
|
||||
|
||||
|
||||
@docker.command()
|
||||
@with_appcontext
|
||||
@pass_context
|
||||
def setup(ctx):
|
||||
"""Setup flaschengesit in docker container"""
|
||||
click.echo("Setup docker")
|
||||
|
||||
plugins = environ.get("FG_ENABLE_PLUGINS")
|
||||
|
||||
if not plugins:
|
||||
click.secho("no evironment variable is set for 'FG_ENABLE_PLUGINS'", fg="yellow")
|
||||
click.secho("set 'FG_ENABLE_PLUGINS' to 'auth_ldap', 'mail', 'balance', 'pricelist_old', 'events'")
|
||||
plugins = ("auth_ldap", "mail", "pricelist_old", "events", "balance")
|
||||
else:
|
||||
plugins = plugins.split(" ")
|
||||
|
||||
print(plugins)
|
||||
|
||||
for name in plugins:
|
||||
click.echo(f"Installing {name}{'.'*(20-len(name))}", nl=False)
|
||||
try:
|
||||
pluginController.install_plugin(name)
|
||||
except Exception as e:
|
||||
click.secho(" failed", fg="red")
|
||||
if logger.getEffectiveLevel() > 10:
|
||||
ctx.fail(f"[{e.__class__.__name__}] {e}")
|
||||
else:
|
||||
ctx.fail(traceback.format_exc())
|
||||
else:
|
||||
click.secho(" ok", fg="green")
|
||||
|
||||
for name in plugins:
|
||||
click.echo(f"Enabling {name}{'.'*(20-len(name))}", nl=False)
|
||||
try:
|
||||
pluginController.enable_plugin(name)
|
||||
click.secho(" ok", fg="green")
|
||||
except NotFound:
|
||||
click.secho(" not installed / not found", fg="red")
|
|
@ -0,0 +1,79 @@
|
|||
import secrets
|
||||
|
||||
from werkzeug.exceptions import Unauthorized
|
||||
|
||||
from .. import logger
|
||||
from ..database import db
|
||||
from ..models import ApiKey
|
||||
|
||||
|
||||
def validate_api_key(api_key, permission):
|
||||
"""Verify api key
|
||||
|
||||
Verify a ApiKey so if the User has permission or not.
|
||||
Retrieves the access token if valid else retrieves False
|
||||
|
||||
Args:
|
||||
api_key: ApiKey to verify
|
||||
permission: Permission needed to access restricted routes
|
||||
Returns:
|
||||
A ApiKey for this given Token
|
||||
Raises:
|
||||
Unauthorized: If api key is invalid
|
||||
Forbidden: If permission is insufficient
|
||||
"""
|
||||
logger.debug("check api_key {{ {} }} is valid".format(api_key))
|
||||
api_key = ApiKey.query.filter_by(_token=api_key).one_or_none()
|
||||
if api_key:
|
||||
logger.debug("api_key found")
|
||||
if not permission or api_key.user_.has_permission(permission):
|
||||
return api_key
|
||||
else:
|
||||
raise Forbidden
|
||||
logger.debug("no valid api key with api_key: {{ {} }} and permission: {{ {} }}".format(api_key, permission))
|
||||
raise Unauthorized
|
||||
|
||||
|
||||
def create(user, name, description=None) -> ApiKey:
|
||||
"""Create a ApiKey
|
||||
|
||||
Args:
|
||||
user: For which User is to create a ApiKey
|
||||
|
||||
Returns:
|
||||
A ApiKey for this given User
|
||||
"""
|
||||
logger.debug("create api key token")
|
||||
token_str = secrets.token_hex(16)
|
||||
logger.debug("create api_key for user {{ {} }}".format(user))
|
||||
api_key = ApiKey(_user_id=user.id_, name=name, description=description, _token=token_str)
|
||||
db.session.add(api_key)
|
||||
db.session.commit()
|
||||
api_key.token = api_key._token
|
||||
return api_key
|
||||
|
||||
|
||||
def get_users_api_keys(user) -> list[ApiKey]:
|
||||
"""Get all ApiKeys for a User
|
||||
|
||||
Args:
|
||||
user: For which User is to get all ApiKeys
|
||||
|
||||
Returns:
|
||||
List of ApiKeys for this given User
|
||||
"""
|
||||
return ApiKey.query.filter(ApiKey._user_id == user.id_).all()
|
||||
|
||||
|
||||
def delete_api_key(api_key):
|
||||
"""Delete a ApiKey
|
||||
|
||||
Args:
|
||||
api_key: ApiKey to delete
|
||||
"""
|
||||
logger.debug(f"delete api_key {{ {api_key} }} {{ {type(api_key)} }}")
|
||||
if isinstance(api_key, int):
|
||||
api_key = ApiKey.query.get(api_key)
|
||||
logger.debug("delete api_key {{ {} }}".format(api_key.token))
|
||||
db.session.delete(api_key)
|
||||
db.session.commit()
|
|
@ -108,9 +108,12 @@ def install_plugin(plugin_name: str):
|
|||
plugin.install()
|
||||
# Check migrations
|
||||
directory = entry_point[0].dist.locate_file("")
|
||||
logger.debug(f"Checking for migrations in {directory}")
|
||||
for loc in entry_point[0].module.split(".") + ["migrations"]:
|
||||
directory /= loc
|
||||
logger.debug(f"Checking for migrations with loc in {directory}")
|
||||
if directory.exists():
|
||||
logger.debug(f"Found migrations in {directory}")
|
||||
database_upgrade(revision=f"{plugin_name}@head")
|
||||
db.session.commit()
|
||||
return plugin
|
||||
|
|
|
@ -1,13 +1,12 @@
|
|||
import secrets
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from werkzeug.exceptions import Forbidden, Unauthorized
|
||||
|
||||
from ua_parser import user_agent_parser
|
||||
from werkzeug.exceptions import Forbidden, Unauthorized
|
||||
|
||||
from .. import logger
|
||||
from ..models import Session
|
||||
from ..database import db
|
||||
|
||||
from ..models import Session
|
||||
|
||||
lifetime = 1800
|
||||
|
||||
|
@ -72,7 +71,7 @@ def create(user, request_headers=None) -> Session:
|
|||
logger.debug(f"platform: {user_agent['os']['family']}, browser: {user_agent['user_agent']['family']}")
|
||||
session = Session(
|
||||
token=token_str,
|
||||
user_=user,
|
||||
_user_id=user.id_,
|
||||
lifetime=lifetime,
|
||||
platform=user_agent["os"]["family"],
|
||||
browser=user_agent["user_agent"]["family"],
|
||||
|
|
|
@ -1,11 +1,14 @@
|
|||
import re
|
||||
import secrets
|
||||
import hashlib
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Optional
|
||||
from typing import Optional, Union
|
||||
from flask import make_response
|
||||
from flask.json import provider
|
||||
from sqlalchemy import exc
|
||||
from sqlalchemy_utils import merge_references
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta, timezone, date
|
||||
from flask.helpers import send_file
|
||||
from werkzeug.exceptions import NotFound, BadRequest, Forbidden
|
||||
|
||||
|
@ -16,7 +19,12 @@ from ..models import Notification, User, Role
|
|||
from ..models.user import _PasswordReset
|
||||
from ..utils.hook import Hook
|
||||
from ..utils.datetime import from_iso_format
|
||||
from ..controller import imageController, messageController, pluginController, sessionController
|
||||
from ..controller import (
|
||||
imageController,
|
||||
messageController,
|
||||
pluginController,
|
||||
sessionController,
|
||||
)
|
||||
from ..plugins import AuthPlugin
|
||||
|
||||
|
||||
|
@ -195,7 +203,11 @@ def delete_user(user: User):
|
|||
deleted_user = get_user("__deleted_user__", True)
|
||||
except NotFound:
|
||||
deleted_user = User(
|
||||
userid="__deleted_user__", firstname="USER", lastname="DELETED", display_name="DELETED USER", deleted=True
|
||||
userid="__deleted_user__",
|
||||
firstname="USER",
|
||||
lastname="DELETED",
|
||||
display_name="DELETED USER",
|
||||
deleted=True,
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
|
@ -206,7 +218,10 @@ def delete_user(user: User):
|
|||
db.session.delete(user)
|
||||
db.session.commit()
|
||||
except exc.IntegrityError:
|
||||
logger.error("Delete of user failed, there might be ForeignKey contraits from disabled plugins", exec_info=True)
|
||||
logger.error(
|
||||
"Delete of user failed, there might be ForeignKey contraits from disabled plugins",
|
||||
exec_info=True,
|
||||
)
|
||||
# Remove at least all personal data
|
||||
user.userid = f"__deleted_user__{user.id_}"
|
||||
user.display_name = "DELETED USER"
|
||||
|
@ -228,6 +243,9 @@ def register(data, passwd=None):
|
|||
values = {key: value for key, value in data.items() if key in allowed_keys}
|
||||
roles = values.pop("roles", [])
|
||||
if "birthday" in data:
|
||||
if isinstance(data["birthday"], date):
|
||||
values["birthday"] = data["birthday"]
|
||||
else:
|
||||
values["birthday"] = from_iso_format(data["birthday"]).date()
|
||||
if "mail" in data and not re.match(r"[^@]+@[^@]+\.[^@]+", data["mail"]):
|
||||
raise BadRequest("Invalid mail given")
|
||||
|
@ -262,14 +280,22 @@ def register(data, passwd=None):
|
|||
return user
|
||||
|
||||
|
||||
def load_avatar(user: User):
|
||||
def get_last_modified(user: User):
|
||||
"""Get the last modification date of the user"""
|
||||
return get_provider(user.userid).get_last_modified(user)
|
||||
|
||||
|
||||
def load_avatar(user: User, etag: Union[str, None] = None):
|
||||
if user.avatar_ is not None:
|
||||
return imageController.send_image(image=user.avatar_)
|
||||
else:
|
||||
provider = get_provider(user.userid)
|
||||
avatar = provider.get_avatar(user)
|
||||
new_etag = hashlib.md5(avatar.binary).hexdigest()
|
||||
if new_etag == etag:
|
||||
return make_response("", 304)
|
||||
if len(avatar.binary) > 0:
|
||||
return send_file(BytesIO(avatar.binary), avatar.mimetype)
|
||||
return send_file(BytesIO(avatar.binary), avatar.mimetype, etag=new_etag)
|
||||
raise NotFound
|
||||
|
||||
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
from .api_key import *
|
||||
from .image import *
|
||||
from .notification import *
|
||||
from .plugin import *
|
||||
from .session import *
|
||||
from .user import *
|
||||
from .plugin import *
|
||||
from .notification import *
|
||||
from .image import *
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
from __future__ import \
|
||||
annotations # TODO: Remove if python requirement is >= 3.12 (? PEP 563 is defered)
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from secrets import compare_digest
|
||||
from typing import Union
|
||||
|
||||
from .. import logger
|
||||
from ..database import db
|
||||
from ..database.types import ModelSerializeMixin, Serial, UtcDateTime
|
||||
|
||||
|
||||
class ApiKey(db.Model, ModelSerializeMixin):
|
||||
"""Model for a Session
|
||||
|
||||
Args:
|
||||
expires: Is a Datetime from current Time.
|
||||
user: Is an User.
|
||||
token: String to verify access later.
|
||||
"""
|
||||
|
||||
__allow_unmapped__ = True
|
||||
__tablename__ = "api_key"
|
||||
expires: datetime = db.Column(UtcDateTime, nullable=True)
|
||||
_token: str = db.Column("token", db.String(32), unique=True)
|
||||
name: str = db.Column(db.String(32))
|
||||
description: str = db.Column(db.String(255), nullable=True)
|
||||
lifetime: int = db.Column(db.Integer, nullable=True)
|
||||
userid: str = ""
|
||||
|
||||
id: int = db.Column("id", Serial, primary_key=True)
|
||||
_user_id = db.Column("user_id", Serial, db.ForeignKey("user.id"))
|
||||
user_: User = db.relationship("User", back_populates="api_keys_")
|
||||
token: Union[str, None] = None
|
||||
|
||||
@property
|
||||
def userid(self):
|
||||
return self.user_.userid
|
||||
|
||||
def refresh(self):
|
||||
"""Update the Timestamp
|
||||
|
||||
Update the Timestamp to the current Time.
|
||||
"""
|
||||
logger.debug("update timestamp from session with token {{ {} }}".format(self._token))
|
||||
self.expires = datetime.now(timezone.utc) + timedelta(seconds=self.lifetime)
|
||||
|
||||
def __eq__(self, token):
|
||||
if isinstance(token, str):
|
||||
return compare_digest(self._token, token)
|
||||
else:
|
||||
return super(Session, self).__eq__(token)
|
|
@ -1,11 +1,13 @@
|
|||
from __future__ import annotations # TODO: Remove if python requirement is >= 3.12 (? PEP 563 is defered)
|
||||
from __future__ import \
|
||||
annotations # TODO: Remove if python requirement is >= 3.12 (? PEP 563 is defered)
|
||||
|
||||
from typing import Optional, Union, List
|
||||
from datetime import date, datetime
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from sqlalchemy.orm.collections import attribute_mapped_collection
|
||||
|
||||
from ..database import db
|
||||
from ..database.types import ModelSerializeMixin, UtcDateTime, Serial
|
||||
from ..database.types import ModelSerializeMixin, Serial, UtcDateTime
|
||||
|
||||
association_table = db.Table(
|
||||
"user_x_role",
|
||||
|
@ -45,7 +47,7 @@ class User(db.Model, ModelSerializeMixin):
|
|||
|
||||
Attributes:
|
||||
id: Id in Database as Primary Key.
|
||||
uid: User ID used by authentication provider
|
||||
userid: User ID used by authentication provider
|
||||
display_name: Name to show
|
||||
firstname: Firstname of the User
|
||||
lastname: Lastname of the User
|
||||
|
@ -69,6 +71,7 @@ class User(db.Model, ModelSerializeMixin):
|
|||
id_ = db.Column("id", Serial, primary_key=True)
|
||||
roles_: List[Role] = db.relationship("Role", secondary=association_table, cascade="save-update, merge")
|
||||
sessions_: List[Session] = db.relationship("Session", back_populates="user_", cascade="all, delete, delete-orphan")
|
||||
api_keys_: List[ApiKey] = db.relationship("ApiKey", back_populates="user_", cascade="all, delete, delete-orphan")
|
||||
avatar_: Optional[Image] = db.relationship("Image", cascade="all, delete, delete-orphan", single_parent=True)
|
||||
reset_requests_: List["_PasswordReset"] = db.relationship("_PasswordReset", cascade="all, delete, delete-orphan")
|
||||
|
||||
|
|
|
@ -248,6 +248,16 @@ class AuthPlugin(Plugin):
|
|||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_modified_time(self, user):
|
||||
"""If backend is using external data, then return the timestamp of the last modification
|
||||
|
||||
Args:
|
||||
user: User object
|
||||
Returns:
|
||||
Timestamp of last modification
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_avatar(self, user) -> _Avatar:
|
||||
"""Retrieve avatar for given user (if supported by auth backend)
|
||||
|
||||
|
|
|
@ -10,6 +10,8 @@ from ldap3.core.exceptions import LDAPPasswordIsMandatoryError, LDAPBindError
|
|||
from werkzeug.exceptions import BadRequest, InternalServerError, NotFound
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.config import config
|
||||
from flaschengeist.controller import userController
|
||||
|
@ -126,9 +128,12 @@ class AuthLDAP(AuthPlugin):
|
|||
def modify_user(self, user: User, password=None, new_password=None):
|
||||
try:
|
||||
dn = user.get_attribute("DN")
|
||||
logger.debug(f"LDAP: modify_user for user {user.userid} with dn {dn}")
|
||||
if password:
|
||||
logger.debug(f"LDAP: modify_user for user {user.userid} with password")
|
||||
ldap_conn = self.ldap.connect(dn, password)
|
||||
else:
|
||||
logger.debug(f"LDAP: modify_user for user {user.userid} with root_dn")
|
||||
if self.root_dn is None:
|
||||
logger.error("root_dn missing in ldap config!")
|
||||
raise InternalServerError
|
||||
|
@ -141,14 +146,31 @@ class AuthLDAP(AuthPlugin):
|
|||
("display_name", "displayName"),
|
||||
]:
|
||||
if hasattr(user, name):
|
||||
attribute = getattr(user, name)
|
||||
if attribute:
|
||||
modifier[ldap_name] = [(MODIFY_REPLACE, [getattr(user, name)])]
|
||||
if new_password:
|
||||
modifier["userPassword"] = [(MODIFY_REPLACE, [self.__hash(new_password)])]
|
||||
if "userPassword" in modifier:
|
||||
logger.debug(f"LDAP: modify_user for user {user.userid} with password change (can't show >modifier<)")
|
||||
else:
|
||||
logger.debug(f"LDAP: modify_user for user {user.userid} with modifier {modifier}")
|
||||
ldap_conn.modify(dn, modifier)
|
||||
self._set_roles(user)
|
||||
except (LDAPPasswordIsMandatoryError, LDAPBindError):
|
||||
raise BadRequest
|
||||
|
||||
def get_modified_time(self, user):
|
||||
self.ldap.connection.search(
|
||||
self.search_dn,
|
||||
"(uid={})".format(user.userid),
|
||||
SUBTREE,
|
||||
attributes=["modifyTimestamp"],
|
||||
)
|
||||
r = self.ldap.connection.response[0]["attributes"]
|
||||
modified_time = r["modifyTimestamp"][0]
|
||||
return datetime.strptime(modified_time, "%Y%m%d%H%M%SZ")
|
||||
|
||||
def get_avatar(self, user):
|
||||
self.ldap.connection.search(
|
||||
self.search_dn,
|
||||
|
|
|
@ -6,13 +6,15 @@ from werkzeug.exceptions import NotFound
|
|||
|
||||
@click.command(no_args_is_help=True)
|
||||
@click.option("--sync", is_flag=True, default=False, help="Synchronize users from LDAP -> database")
|
||||
@click.option("--sync-ldap", is_flag=True, default=False, help="Synchronize users from database -> LDAP")
|
||||
@with_appcontext
|
||||
@click.pass_context
|
||||
def ldap(ctx, sync):
|
||||
def ldap(ctx, sync, sync_ldap):
|
||||
"""Tools for the LDAP authentification"""
|
||||
if sync:
|
||||
from flaschengeist.controller import userController
|
||||
from flaschengeist.plugins.auth_ldap import AuthLDAP
|
||||
if sync:
|
||||
click.echo("Synchronizing users from LDAP -> database")
|
||||
from ldap3 import SUBTREE
|
||||
from flaschengeist.models import User
|
||||
from flaschengeist.database import db
|
||||
|
@ -33,3 +35,13 @@ def ldap(ctx, sync):
|
|||
user = User(userid=uid)
|
||||
db.session.add(user)
|
||||
userController.update_user(user, auth_ldap)
|
||||
if sync_ldap:
|
||||
click.echo("Synchronizing users from database -> LDAP")
|
||||
|
||||
auth_ldap: AuthLDAP = current_app.config.get("FG_PLUGINS").get("auth_ldap")
|
||||
if auth_ldap is None or not isinstance(auth_ldap, AuthLDAP):
|
||||
ctx.fail("auth_ldap plugin not found or not enabled!")
|
||||
users = userController.get_users()
|
||||
for user in users:
|
||||
userController.update_user(user, auth_ldap)
|
||||
|
||||
|
|
|
@ -5,6 +5,7 @@ Extends users plugin with balance functions
|
|||
|
||||
from flask import current_app
|
||||
from werkzeug.exceptions import NotFound
|
||||
from werkzeug.local import LocalProxy
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.config import config
|
||||
|
@ -82,3 +83,7 @@ class BalancePlugin(Plugin):
|
|||
balance_controller.set_limit(user, limit, override=False)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def getPlugin() -> LocalProxy["BalancePlugin"]:
|
||||
return LocalProxy(lambda: current_app.config["FG_PLUGINS"]["balance"])
|
||||
|
|
|
@ -21,6 +21,8 @@ __attribute_limit = "balance_limit"
|
|||
class NotifyType(IntEnum):
|
||||
SEND_TO = 0x01
|
||||
SEND_FROM = 0x02
|
||||
ADD_FROM = 0x03
|
||||
SUB_FROM = 0x04
|
||||
|
||||
|
||||
def set_limit(user: User, limit: float, override=True):
|
||||
|
@ -34,7 +36,7 @@ def get_limit(user: User) -> float:
|
|||
|
||||
|
||||
def get_balance(user, start: datetime = None, end: datetime = None):
|
||||
query = db.session.query(func.sum(Transaction.amount))
|
||||
query = db.session.query(func.sum(Transaction._amount))
|
||||
if start:
|
||||
query = query.filter(start <= Transaction.time)
|
||||
if end:
|
||||
|
@ -46,7 +48,13 @@ def get_balance(user, start: datetime = None, end: datetime = None):
|
|||
|
||||
|
||||
def get_balances(
|
||||
start: datetime = None, end: datetime = None, limit=None, offset=None, descending=None, sortBy=None, _filter=None
|
||||
start: datetime = None,
|
||||
end: datetime = None,
|
||||
limit=None,
|
||||
offset=None,
|
||||
descending=None,
|
||||
sortBy=None,
|
||||
_filter=None,
|
||||
):
|
||||
logger.debug(
|
||||
f"get_balances(start={start}, end={end}, limit={limit}, offset={offset}, descending={descending}, sortBy={sortBy}, _filter={_filter})"
|
||||
|
@ -54,7 +62,11 @@ def get_balances(
|
|||
|
||||
class _User(User):
|
||||
_debit = db.relationship(Transaction, back_populates="sender_", foreign_keys=[Transaction._sender_id])
|
||||
_credit = db.relationship(Transaction, back_populates="receiver_", foreign_keys=[Transaction._receiver_id])
|
||||
_credit = db.relationship(
|
||||
Transaction,
|
||||
back_populates="receiver_",
|
||||
foreign_keys=[Transaction._receiver_id],
|
||||
)
|
||||
|
||||
@hybrid_property
|
||||
def debit(self):
|
||||
|
@ -63,8 +75,8 @@ def get_balances(
|
|||
@debit.expression
|
||||
def debit(cls):
|
||||
a = (
|
||||
db.select(func.sum(Transaction.amount))
|
||||
.where(cls.id_ == Transaction._sender_id, Transaction.amount)
|
||||
db.select(func.sum(Transaction._amount))
|
||||
.where(cls.id_ == Transaction._sender_id, Transaction._amount)
|
||||
.scalar_subquery()
|
||||
)
|
||||
return case([(a, a)], else_=0)
|
||||
|
@ -76,8 +88,8 @@ def get_balances(
|
|||
@credit.expression
|
||||
def credit(cls):
|
||||
b = (
|
||||
db.select(func.sum(Transaction.amount))
|
||||
.where(cls.id_ == Transaction._receiver_id, Transaction.amount)
|
||||
db.select(func.sum(Transaction._amount))
|
||||
.where(cls.id_ == Transaction._receiver_id, Transaction._amount)
|
||||
.scalar_subquery()
|
||||
)
|
||||
return case([(b, b)], else_=0)
|
||||
|
@ -90,7 +102,12 @@ def get_balances(
|
|||
def limit(cls):
|
||||
return (
|
||||
db.select(_UserAttribute.value)
|
||||
.where(and_(cls.id_ == _UserAttribute.user, _UserAttribute.name == "balance_limit"))
|
||||
.where(
|
||||
and_(
|
||||
cls.id_ == _UserAttribute.user,
|
||||
_UserAttribute.name == "balance_limit",
|
||||
)
|
||||
)
|
||||
.scalar_subquery()
|
||||
)
|
||||
|
||||
|
@ -125,14 +142,25 @@ def get_balances(
|
|||
|
||||
if _filter:
|
||||
query = query.filter(
|
||||
or_(_User.firstname.ilike(f"%{_filter.lower()}%"), _User.lastname.ilike(f"%{_filter.lower()}%"))
|
||||
or_(
|
||||
_User.firstname.ilike(f"%{_filter.lower()}%"),
|
||||
_User.lastname.ilike(f"%{_filter.lower()}%"),
|
||||
)
|
||||
)
|
||||
|
||||
if sortBy == "balance":
|
||||
if descending:
|
||||
query = query.order_by((_User.credit - _User.debit).desc(), _User.lastname.asc(), _User.firstname.asc())
|
||||
query = query.order_by(
|
||||
(_User.credit - _User.debit).desc(),
|
||||
_User.lastname.asc(),
|
||||
_User.firstname.asc(),
|
||||
)
|
||||
else:
|
||||
query = query.order_by((_User.credit - _User.debit).asc(), _User.lastname.asc(), _User.firstname.asc())
|
||||
query = query.order_by(
|
||||
(_User.credit - _User.debit).asc(),
|
||||
_User.lastname.asc(),
|
||||
_User.firstname.asc(),
|
||||
)
|
||||
elif sortBy == "limit":
|
||||
if descending:
|
||||
query = query.order_by(_User.limit.desc(), User.lastname.asc(), User.firstname.asc())
|
||||
|
@ -178,6 +206,7 @@ def send(sender: User, receiver, amount: float, author: User):
|
|||
Raises:
|
||||
BadRequest if amount <= 0
|
||||
"""
|
||||
logger.debug(f"send(sender={sender}, receiver={receiver}, amount={amount}, author={author})")
|
||||
if amount <= 0:
|
||||
raise BadRequest
|
||||
|
||||
|
@ -191,7 +220,8 @@ def send(sender: User, receiver, amount: float, author: User):
|
|||
db.session.add(transaction)
|
||||
db.session.commit()
|
||||
if sender is not None and sender.id_ != author.id_:
|
||||
BalancePlugin.plugin.notify(
|
||||
if receiver is not None:
|
||||
BalancePlugin.getPlugin().notify(
|
||||
sender,
|
||||
"Neue Transaktion",
|
||||
{
|
||||
|
@ -201,9 +231,36 @@ def send(sender: User, receiver, amount: float, author: User):
|
|||
"amount": amount,
|
||||
},
|
||||
)
|
||||
else:
|
||||
BalancePlugin.getPlugin().notify(
|
||||
sender,
|
||||
"Neue Transaktion",
|
||||
{
|
||||
"type": NotifyType.SUB_FROM,
|
||||
"author_id": author.userid,
|
||||
"amount": amount,
|
||||
},
|
||||
)
|
||||
if receiver is not None and receiver.id_ != author.id_:
|
||||
BalancePlugin.plugin.notify(
|
||||
receiver, "Neue Transaktion", {"type": NotifyType.SEND_TO, "sender_id": sender.userid, "amount": amount}
|
||||
if sender is not None:
|
||||
BalancePlugin.getPlugin().notify(
|
||||
receiver,
|
||||
"Neue Transaktion",
|
||||
{
|
||||
"type": NotifyType.SEND_TO,
|
||||
"sender_id": sender.userid,
|
||||
"amount": amount,
|
||||
},
|
||||
)
|
||||
else:
|
||||
BalancePlugin.getPlugin().notify(
|
||||
receiver,
|
||||
"Neue Transaktion",
|
||||
{
|
||||
"type": NotifyType.ADD_FROM,
|
||||
"author_id": author.userid,
|
||||
"amount": amount,
|
||||
},
|
||||
)
|
||||
return transaction
|
||||
|
||||
|
|
|
@ -1,7 +1,9 @@
|
|||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from sqlalchemy.ext.hybrid import hybrid_property
|
||||
from math import floor
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.database import db
|
||||
from flaschengeist.models.user import User
|
||||
from flaschengeist.models import ModelSerializeMixin, UtcDateTime, Serial
|
||||
|
@ -18,8 +20,9 @@ class Transaction(db.Model, ModelSerializeMixin):
|
|||
# Public and exported member
|
||||
id: int = db.Column("id", Serial, primary_key=True)
|
||||
time: datetime = db.Column(UtcDateTime, nullable=False, default=UtcDateTime.current_utc)
|
||||
amount: float = db.Column(db.Numeric(precision=5, scale=2, asdecimal=False), nullable=False)
|
||||
_amount: float = db.Column("amount", db.Numeric(precision=5, scale=2, asdecimal=False), nullable=False)
|
||||
reversal_id: Optional[int] = db.Column(Serial, db.ForeignKey("balance_transaction.id"))
|
||||
amount: float
|
||||
|
||||
# Dummy properties used for JSON serialization (userid instead of full user)
|
||||
author_id: Optional[str] = None
|
||||
|
@ -56,3 +59,14 @@ class Transaction(db.Model, ModelSerializeMixin):
|
|||
@property
|
||||
def original_id(self):
|
||||
return self.original_.id if self.original_ else None
|
||||
|
||||
@property
|
||||
def amount(self):
|
||||
return self._amount
|
||||
|
||||
@amount.setter
|
||||
def amount(self, value):
|
||||
self._amount = floor(value * 100) / 100
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Transaction {self.id} {self.amount} {self.time} {self.sender_id} {self.receiver_id} {self.author_id}>"
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
from datetime import datetime, timezone
|
||||
from logging import log
|
||||
from werkzeug.exceptions import Forbidden, BadRequest
|
||||
from flask import Blueprint, request, jsonify
|
||||
|
||||
|
@ -163,6 +164,7 @@ def get_balance(userid, current_session: Session):
|
|||
end = datetime.now(tz=timezone.utc)
|
||||
|
||||
balance = balance_controller.get_balance(user, start, end)
|
||||
logger.debug(f"Balance of {user.userid} from {start} to {end}: {balance}")
|
||||
return {"credit": balance[0], "debit": balance[1], "balance": balance[2]}
|
||||
|
||||
|
||||
|
@ -224,6 +226,7 @@ def get_transactions(userid, current_session: Session):
|
|||
show_cancelled=show_cancelled,
|
||||
descending=descending,
|
||||
)
|
||||
logger.debug(f"transactions: {transactions}")
|
||||
return {"transactions": transactions, "count": count}
|
||||
|
||||
|
||||
|
@ -321,7 +324,11 @@ def get_balances(current_session: Session):
|
|||
_filter = request.args.get("filter", None, type=str)
|
||||
logger.debug(f"request.args: {request.args}")
|
||||
balances, count = balance_controller.get_balances(
|
||||
limit=limit, offset=offset, descending=descending, sortBy=sortBy, _filter=_filter
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
descending=descending,
|
||||
sortBy=sortBy,
|
||||
_filter=_filter,
|
||||
)
|
||||
return jsonify(
|
||||
{
|
||||
|
|
|
@ -31,7 +31,7 @@ class MailMessagePlugin(Plugin):
|
|||
self.send_mail(msg)
|
||||
|
||||
def send_mail(self, msg: Message):
|
||||
logger.debug(f"Sending mail to {msg.receiver}")
|
||||
logger.debug(f"Sending mail to {msg.receiver} with subject {msg.subject}")
|
||||
if isinstance(msg.receiver, User):
|
||||
if not msg.receiver.mail:
|
||||
logger.warning("Could not send Mail, mail missing: {}".format(msg.receiver))
|
||||
|
@ -41,18 +41,12 @@ class MailMessagePlugin(Plugin):
|
|||
recipients = userController.get_user_by_role(msg.receiver)
|
||||
|
||||
mail = MIMEMultipart()
|
||||
try:
|
||||
mail["From"] = self.mail
|
||||
mail["To"] = ", ".join(recipients)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
print(traceback.format_exc())
|
||||
mail["Subject"] = msg.subject
|
||||
mail.attach(MIMEText(msg.message))
|
||||
if not hasattr(self, "smtp"):
|
||||
self.__connect()
|
||||
self.smtp.sendmail(self.mail, recipients, mail.as_string())
|
||||
with self.__connect() as smtp:
|
||||
smtp.sendmail(self.mail, recipients, mail.as_string())
|
||||
|
||||
def __connect(self):
|
||||
if self.crypt == "SSL":
|
||||
|
@ -63,3 +57,4 @@ class MailMessagePlugin(Plugin):
|
|||
else:
|
||||
raise ValueError("Invalid CRYPT given")
|
||||
self.smtp.login(self.user, self.password)
|
||||
return self.smtp
|
||||
|
|
|
@ -2,19 +2,23 @@
|
|||
|
||||
Provides routes used to manage users
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from http.client import CREATED
|
||||
from flask import Blueprint, request, jsonify, make_response
|
||||
|
||||
from flask import Blueprint, Response, after_this_request, jsonify, make_response, request
|
||||
from werkzeug.exceptions import BadRequest, Forbidden, MethodNotAllowed
|
||||
|
||||
from . import permissions
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.config import config
|
||||
from flaschengeist.plugins import Plugin
|
||||
from flaschengeist.controller import apiKeyController, userController
|
||||
from flaschengeist.models import User
|
||||
from flaschengeist.utils.decorators import login_required, extract_session, headers
|
||||
from flaschengeist.controller import userController
|
||||
from flaschengeist.utils.HTTP import created, no_content
|
||||
from flaschengeist.plugins import Plugin
|
||||
from flaschengeist.utils.datetime import from_iso_format
|
||||
from flaschengeist.utils.decorators import extract_session, headers, login_required
|
||||
from flaschengeist.utils.HTTP import created, no_content
|
||||
|
||||
from . import permissions
|
||||
|
||||
|
||||
class UsersPlugin(Plugin):
|
||||
|
@ -57,7 +61,7 @@ def register():
|
|||
|
||||
@UsersPlugin.blueprint.route("/users", methods=["GET"])
|
||||
@login_required()
|
||||
@headers({"Cache-Control": "private, must-revalidate, max-age=3600"})
|
||||
# @headers({"Cache-Control": "private, must-revalidate, max-age=3600"})
|
||||
def list_users(current_session):
|
||||
"""List all existing users
|
||||
|
||||
|
@ -118,10 +122,13 @@ def frontend(userid, current_session):
|
|||
|
||||
|
||||
@UsersPlugin.blueprint.route("/users/<userid>/avatar", methods=["GET"])
|
||||
@headers({"Cache-Control": "public, max-age=604800"})
|
||||
@headers({"Cache-Control": "public, must-revalidate, max-age=10"})
|
||||
def get_avatar(userid):
|
||||
etag = None
|
||||
if "If-None-Match" in request.headers:
|
||||
etag = request.headers["If-None-Match"]
|
||||
user = userController.get_user(userid)
|
||||
return userController.load_avatar(user)
|
||||
return userController.load_avatar(user, etag)
|
||||
|
||||
|
||||
@UsersPlugin.blueprint.route("/users/<userid>/avatar", methods=["POST"])
|
||||
|
@ -256,3 +263,82 @@ def shortcuts(userid, current_session):
|
|||
user.set_attribute("users_link_shortcuts", data)
|
||||
userController.persist()
|
||||
return no_content()
|
||||
|
||||
|
||||
@UsersPlugin.blueprint.route("/users/<userid>/setting/<setting>", methods=["GET", "PUT"])
|
||||
@login_required()
|
||||
def settings(userid, setting, current_session):
|
||||
if userid != current_session.user_.userid:
|
||||
raise Forbidden
|
||||
user = userController.get_user(userid)
|
||||
if request.method == "GET":
|
||||
retVal = user.get_attribute(setting, None)
|
||||
logger.debug(f"Get setting >>{setting}<< for user >>{user.userid}<< with >>{retVal}<<")
|
||||
return jsonify(retVal)
|
||||
else:
|
||||
data = request.get_json()
|
||||
logger.debug(f"Set setting >>{setting}<< for user >>{user.userid}<< to >>{data}<<")
|
||||
user.set_attribute(setting, data)
|
||||
userController.persist()
|
||||
return no_content()
|
||||
|
||||
|
||||
@UsersPlugin.blueprint.route("/users/<userid>/api_keys", methods=["GET"])
|
||||
@login_required()
|
||||
def get_users_api_keys(userid, current_session):
|
||||
"""Get all API keys of a user
|
||||
|
||||
Route: ``/users/<userid>/api_keys`` | Method: ``GET``
|
||||
Args:
|
||||
userid: UserID of user to retrieve
|
||||
current_session: Session sent with Authorization Header
|
||||
|
||||
Returns:
|
||||
JSON encoded array of `flaschengeist.models.api_key.ApiKey` or HTTP error
|
||||
|
||||
"""
|
||||
if userid != current_session.user_.userid:
|
||||
raise Unauthorized
|
||||
return jsonify(apiKeyController.get_users_api_keys(current_session.user_))
|
||||
|
||||
|
||||
@UsersPlugin.blueprint.route("/users/<userid>/api_keys", methods=["POST"])
|
||||
@login_required()
|
||||
def create_api_key(userid, current_session):
|
||||
"""Create a new API key for a user
|
||||
|
||||
Route: ``/users/<userid>/api_keys`` | Method: ``POST``
|
||||
Args:
|
||||
userid: UserID of user to retrieve
|
||||
current_session: Session sent with Authorization Header
|
||||
|
||||
Returns:
|
||||
JSON encoded `flaschengeist.models.api_key.ApiKey` or HTTP error
|
||||
|
||||
"""
|
||||
data = request.get_json()
|
||||
if not data or "name" not in data:
|
||||
raise BadRequest
|
||||
if userid != current_session.user_.userid:
|
||||
raise Unauthorized
|
||||
return jsonify(apiKeyController.create(current_session.user_, data["name"], data.get("description", None)))
|
||||
|
||||
|
||||
@UsersPlugin.blueprint.route("/users/<userid>/api_keys/<int:keyid>", methods=["DELETE"])
|
||||
@login_required()
|
||||
def delete_api_key(userid, keyid, current_session):
|
||||
"""Delete an API key for a user
|
||||
|
||||
Route: ``/users/<userid>/api_keys/<keyid>`` | Method: ``DELETE``
|
||||
Args:
|
||||
userid: UserID of user to retrieve
|
||||
keyid: KeyID of the API key to delete
|
||||
current_session: Session sent with Authorization Header
|
||||
|
||||
Returns:
|
||||
HTTP-204 or HTTP error
|
||||
"""
|
||||
if userid != current_session.user_.userid:
|
||||
raise Unauthorized
|
||||
apiKeyController.delete_api_key(keyid)
|
||||
return no_content()
|
||||
|
|
|
@ -3,6 +3,7 @@ import sqlalchemy.exc
|
|||
from flask.cli import with_appcontext
|
||||
from werkzeug.exceptions import NotFound
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.database import db
|
||||
from flaschengeist.controller import roleController, userController
|
||||
|
||||
|
@ -70,12 +71,19 @@ def user(add_role, delete, user):
|
|||
if USER_KEY in ctx.meta:
|
||||
userController.register(ctx.meta[USER_KEY], ctx.meta[USER_KEY]["password"])
|
||||
else:
|
||||
if not isinstance(user, list) or not isinstance(user, tuple):
|
||||
user = [user]
|
||||
for uid in user:
|
||||
logger.debug(f"Userid: {uid}")
|
||||
user = userController.get_user(uid)
|
||||
logger.debug(f"User: {user}")
|
||||
if delete:
|
||||
logger.debug(f"Deleting user {user}")
|
||||
userController.delete_user(user)
|
||||
elif add_role:
|
||||
logger.debug(f"Adding role {add_role} to user {user}")
|
||||
role = roleController.get(add_role)
|
||||
logger.debug(f"Role: {role}")
|
||||
user.roles_.append(role)
|
||||
userController.modify_user(user, None)
|
||||
db.session.commit()
|
||||
|
|
|
@ -1,8 +1,22 @@
|
|||
from functools import wraps
|
||||
|
||||
from werkzeug.exceptions import Unauthorized
|
||||
|
||||
from flaschengeist import logger
|
||||
from flaschengeist.controller import sessionController
|
||||
from flaschengeist.controller import apiKeyController, sessionController
|
||||
|
||||
|
||||
def extract_api_key(permission=None):
|
||||
from flask import request
|
||||
|
||||
try:
|
||||
apiKey = request.headers.get("X-API-KEY")
|
||||
except AttributeError:
|
||||
logger.debug("Missing X-API-KEY header")
|
||||
raise Unauthorized
|
||||
|
||||
apiKey = apiKeyController.validate_api_key(apiKey, permission)
|
||||
return apiKey
|
||||
|
||||
|
||||
def extract_session(permission=None):
|
||||
|
@ -32,7 +46,10 @@ def login_required(permission=None):
|
|||
def wrap(func):
|
||||
@wraps(func)
|
||||
def wrapped_f(*args, **kwargs):
|
||||
try:
|
||||
session = extract_session(permission)
|
||||
except Unauthorized:
|
||||
session = extract_api_key(permission)
|
||||
kwargs["current_session"] = session
|
||||
logger.debug("token {{ {} }} is valid".format(session.token))
|
||||
return func(*args, **kwargs)
|
||||
|
|
|
@ -1,3 +1,6 @@
|
|||
[build-system]
|
||||
requires = ["setuptools", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[tool.black]
|
||||
line-length = 120
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[metadata]
|
||||
license = MIT
|
||||
version = 2.0.0.dev0
|
||||
version = 2.2.0
|
||||
name = flaschengeist
|
||||
author = Tim Gröger
|
||||
author_email = flaschengeist@wu5.de
|
||||
|
@ -22,7 +22,8 @@ include_package_data = True
|
|||
python_requires = >=3.10
|
||||
packages = find:
|
||||
install_requires =
|
||||
Flask>=2.2.2, <2.3
|
||||
#Flask>=2.2.2, <2.3
|
||||
Flask>=2.2.2, <2.9
|
||||
Pillow>=9.2
|
||||
flask_cors
|
||||
flask_migrate>=3.1.0
|
||||
|
@ -38,14 +39,14 @@ install_requires =
|
|||
|
||||
[options.extras_require]
|
||||
argon = argon2-cffi
|
||||
ldap = flask_ldapconn; ldap3
|
||||
ldap = flask_ldapconn @ git+https://github.com/rroemhild/flask-ldapconn.git; ldap3
|
||||
tests = pytest; pytest-depends; coverage
|
||||
mysql =
|
||||
PyMySQL;platform_system=='Windows'
|
||||
mysqlclient;platform_system!='Windows'
|
||||
|
||||
[options.package_data]
|
||||
* = *.toml, script.py.mako
|
||||
* = *.toml, script.py.mako, *.ini, */migrations/*, migrations/versions/*
|
||||
|
||||
[options.entry_points]
|
||||
console_scripts =
|
||||
|
|
Loading…
Reference in New Issue