diff --git a/.claude/settings.local.json b/.claude/settings.local.json index feb28ae..087477f 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -70,7 +70,8 @@ "Bash(then echo \"- $template\")", "Bash(fi)", "Bash(done)", - "Bash(docker compose:*)" + "Bash(docker compose:*)", + "Bash(true)" ], "deny": [] } diff --git a/backups/backup_v2docker_20250618_030000_encrypted.sql.gz.enc b/backups/backup_v2docker_20250618_030000_encrypted.sql.gz.enc new file mode 100644 index 0000000..3e26d0a --- /dev/null +++ b/backups/backup_v2docker_20250618_030000_encrypted.sql.gz.enc @@ -0,0 +1 @@ +gAAAAABoUg-Q6j_Fx3e9SJc92fGYp4w5VGSbp6uq0fRNaMWSjXdpCbiVVGum04UWox-dJlgGOPRQUY8LZVViu_SdgoISHHwO-Kr18ZbchnmYioQ96TSc2jqIW2G32ZV12w84hGAFCJYFfqbSdVCKwyV9qO7xYYIhF8nLuI8cafF28EWgfvwMOGxpizGPH0qCBlOpEoEH8BzAsLQ_SeLrGx394rGWQaObAfBZ9PrAgLv6_0aBZPt-EminEYNytGieDeEsOLYKEqIrhQk3twwZ6rgD9eLKeaJ_b_wUQsOUPh8vTb5WhuWsTwC6u7vLFzXwZWm5Hvdc8BX5JosiNIsoRJbeHuiJbX4b5Y99er7Yui5tJRVBoCTlyK9SblfaUW22Kzfc_SFCtw3qsqKBps2PyPa1pohgAfADxwtPk6vUt--QHOjx3EO4xiM3dY7Ar8zO90NZbAcAZd6g1WZ07vPkwmSBvD3X-ZtASxstBAw3Vr8Mw8H5Fa-btrF0oZfxLR5VUXUy9B2O_xoAldyckCvmn9MpEUUFGK8fZLjPZ6wDr87W8SHyVNfilmRHb4snHlCs2wIUNvku19fPXw6prF34lRpcl2e200IRezJnrpUw3AfDIaKTog_gChnCzr8AIAGnfscUuNQLIe3PaNdzcN59KPMLIOAnhxIxlYRz8HMIk74c6jrovY472hdEIQm72U6w9ou788O9hZ_hIanAcdsbuAyyB0j5-Y2UGWRn0i6spnBVmJqucCH6fX1OUMYMQzhaY6nfRQpRH5ny2C4opSf770o2EStcfjXy0sdbJgIM0Mn43a_eZUJB8QmyxJXiQuso4FnXijvtPWv_ayW9-iPH_dKJWWklooiYLMrQSmAk3CwovYjk_D5bjv3pO5kiXz-EhWMAgSJKqMhgcWFI0KmyO0g_wYyRlIQ0eKinNaZ11_T1OqywUo06u9E2y_2Kd_uh5cJpXgLod_ED2W0Ol-W6md7WizwAVzZt4uKSaOmR5-YrEFPtz4IiNiNwLSzh_h-wt7sBdF7R6hlQAtrw4Dy5h1TJi7GSrF3ALd-sKXdR4k1FO4UYQKQX5lz681EK6wEkvWoUdfwO_d1r2IoTrtdU72-ZgnXLOHL_cqzS3VRKIC7NmB9Qo3biAI44LF34OR9To18BvH3t72exs2Nch9H1qy4N1DlwH9jW0BcZNlXU8B6hIi57yuskJ1VIHhJPRQnYAyY47gzPF5m7sW3X4Hb1MppDP2rDEqwGm2arNDB6fvgRO1A9fzVvVtxyOWUVcLqvC8L-B7XqL6nZ6LZ0Uiibr2sLPUwypMB8q8kL2ll1j_xd5cQAddPynupu8L1wRHvIzqYhKQuDz1chw4bLy_4sb3M2suUAZX4lxh-VBKqg8KwacScLivqvrPmUOYj8W-3hmQf7VNho6x3moOT0YtNDx3Jnkdv_YuR4pCJp7gPTuSsDPK6I_z8-e_mHTHQoJA2tfjsDIrL9l0V-_JRtkNiasThMb5Q3aNzP73VeITBe6yqlpVq1gl1tKFMQrz1v29itEo-QpV2XrVLd9ASXGUPv1jQqCh2a-oBiGgPpkXoqSAlwjzqPxtFyVdRU048iTZBgyiY-MPTfNSCS4ewKp_barlLDzBOTEsho5cGGCQhBJjP3B2LYhqZS5rL6wRAUDrRaQbBRKBCg2Fm9vsbuMETMRH4FIUSRN6x5--Lfi9YIZ3Ir3-Jjs9aq19GbQpGusn23-xcTbK4wrE68xsazuGTRr8LNAcez6U_qnggUvZi3vrmukZAZkoNbUS6pwxZVCW0AYmALX-KgVnAYPwU78X_3Aq9iIunBcmc7Ff1rtolXB98lBPCjvS9jDrvdQ1VV5DHRBsmk4FYfFd3Y9B8Oj5WraaOhg8cmZ29VaJYnqpVT91tN94D3Jq1skJYPEEywQg48uWrpFWJTg9KcFBR8NAOZuIgpB0_DgZFVbEB9B4i4LAe5DvDfaZyhXABmpGiMRrQh9lIa5Z7B2FfvEwFDyH9EzUWam7xHszEi0BFB-58g0AXyPRH1G1yJtPjIN6nAK5sCG_RWGI1gzOjPmkU-H9Hew2Yol2dSdnGGtIVAt_Pv5Cpnj3xEp-kqvBpGrCG6VBANQMWbecKnKSu6bbXmjRMJGacz6DwXRjYkkNSWiEJ3PSe-hVUhnx1MfHc6HnHkFQGcfWf9g4r97e7BaJQr6yG0V0X6a0wZ-1JWajsiAASEWl8G8KhVDz07zLAxPBbBZ2q1fpFiNKx887xLE2208HILLuAVB5a_bQU8bfZ9w_T5SBgrueBlxdXlPP3gwXjWa6HTIrL65Rku1PvOGgSCSwJREaA9d89QrrDtrbLCMqHhOzwIScInu-gjuhS9DI5TRb-Cy1ZzlaQg4mdSbDpfcQlxwdbV4GXUDiiWHzrJaqK8ggy0MyMyZVrY891Y2gER_iQJn432I6_hQMGtfZjzfzmxAJVJkZ3eLcmBlMb8rnqa-kq-eZ9chSr18FHvy0Rs_Tb2P-UlLi663ZZToOlEbWxkT6NNEywfe2C6H6HFPwCnH57KenSWo3gnBfncV1BXzGOcvjhml0cvVVyVMHc-J_mJOdBSpX3MM8JuAqRvMR_PQZ9mmRqc_JZLsPrtVnj3dEVW9nhNjtDXUKRtJ5doB3pplZt3-jO0AnTK0XAfiXmmzbBRsvv3pY9J6481ClO7MUWJjZGwCHRXewHQV6gKEyOWNVJlSZOSmXXcD7CoPmC8G5R5Ry2k0eu6s126LDdEvs7jhbdyA-znTjlFZrK01R-qwUJDzgZESi_ckrLlA9GkYVucS4o_gjHZxDbsTMM2lPWR1zvVkX-FM0GIi7glWS5Y2sk3K46CEmlAYHtQ3D-4R-0Jr0lBzFtguCzpuPvUg_IdD0HUfPcGcI_KdAoq3mK5EKkfC5L8fkCzjx_6-MpOweSpOCBkvf-D62XuEuyyQ2bMEInAWtuxRCt5aXB8BmyAKJKUWXIaOoNHIWB8tOV5td93pnn1eqHLfXQSdmFo7__RmwCCHNRKa9vHRYkTcy1n96GaG-gDIB5O2IxS910ZzRU-7qC8x-oROAQ3dvlCqfhNL9T51tdzMCs0veGPxg1ogKVctocmT5FPflbKe_crqXp6NX6xZ30WcluA6CWKN_5zsl9iSggqvZpPaLGrz8xVJwYxdQ_SlCRRCwgndL6ORiafTWxD2T4P72q2NN7yfFp2IwMojM2DiJO1KR2JuT2oXCEhv4pxsrq_rTgMqmMxqEy-d8464YIIQJN-FSaNNiklAZ9Pf47OUk-CE2S2nbjojH4FUISXbKY03EvmFZSUjtPmOrKgSbuD4abOJK1Mn724239CkYYhhuFoy8D7yH2MOC4dwAhfdWN8eml_AVOFGJvT_nxDV2nAq0pTpD7yCNsIl2HFUZzhpMvay9SMHQBCrxlsuw_Sjr4Ctpk0XVIb74iFxlnCTMcODYbB0nN6fP5ne32fPPunuH92GZKsYEnZrXQwOHox1i-OtylfcPM8vUfhC5hKvg10buh8qETiXf5hS61KbhVfJdcWnNrYHl58-zek7rK3tQhNqf5Et8RNOsBYOqEMEsTDuTstLyXr6BBqbOaE3xBbn7ojNGJHUKnoH3PkprSXzFPzwaNwD_Ed5AefJA_9GVOaCJrymprYiGYNk9W9DugseaZGCyoqG7U76FlFGh1UHlrg4r7vTi7mQ9fV2SgxWI1Y-JqkDtv_hAFwOfm1pmpMofvfyPqUa8qiG0YD-fr5kAi4LikNCWbrELUI7An6h60hZpUlcpbPS59qp00dNVv7ALHiVkdNrimWJIQOJCGKeKMysXE15QFVl2sVB-0NtGdoFpizseaZ4nJDP728QllBVYS652MmntSA-zbjwvjHpXihgNn0I8sAnxnkcOYKzFlfeta9UQxXRrVsfAjJfC9UDyslos3jAcrllTYuQLRy_-3lGuESVSj2hk-wUBQS0Lm4rmnP0cWP3TXPOKJ9849C5kSmh9LgEwn7FSDssne56_93WMhFnxgzn8wwug5VdSxpcLpG_g95CAdL_nhYGGciMB20nDAKYy5PVe1n3Ass0xwqQt1MpPfOV8--2_0cOO8bSMUOVkCuDt0M9fpvaJpR2N3A7ooyjaLrWtToZPcZuLopRci86yeNYwzaPr3FreFIaLPwTBgJQGPWcjsaw_0SAKj2xbkNQMqSyzNnm1I1HMdlpHhD8Ym7GypEnoizU5RZG7dDd1DJG3ViCDP5cLy9v1M2fepcTXN4un-XJUw4qjydd1LFcp-UfsUF2LcN0a4gZ9ERN3-oaqYFQL-6LKFMfY0gRkHe771FP2TPAuvPRmypfbigTsNPStPKkMlK8K-FVjK_v2NYEX71pZ4eAEpRdNnVkuCcaWTJvdiDAelx547moyLrOV-uYSnZM7AGVdBGvxWQvRqrlDxehmZEIfynlRSvNN2ofG01W_dKTdPFEv6-JCgUt3ZDAYWuagL_zxctlXmqhbwMQ2FgFr8yw_c_IgNeeR8x5HMRvU4leSlF47bkoZPrDndGKA7BMaS5IaFwV12znAtq0DREnCZ6F5M9d8mpbI0VmAiAGi8Sm9ast6c_86koPe2l3R2E1JWYBqzzrHb-lpfyU8gFk21EfvAQ4-a7mve7qkaeI4f4aoNdM5oBuYTuFUcHW_y_PxCpc1p3ClLs658jwBKe0JQxxzAwO4lNNMqKQx7bgRtI8EqvayEgrumSeIDoU5ipebtjAlPF67faA4rrXSyGKkzwsufTdUosoB2Jgfozg-yZwaOmfBARY0q8l22ipi9w6-mVhxyanPNaPF92SPD6cO7r4KVmazvh9jD5JTeFkSRtOVX3CQ7VY_xcsUxKyIM4t0EVfb29YRM0jZoHhm1LZ3gcwT-Y7rLccw7TtVgBE2Rd8uRyXIHk-K4Up3L-DzULAlYUOKxhbyEHMMCjFACiYsQoPKHvMUXTP8-Dh8jy8vQqFKKCUGPRTiC_68INBvkCf33oAjgnGq1yazhHEZoos4Fs4nYMOaRpts0IazblfHICEC2yXSB9y3J4hW9Yy7k2n9t8ndyj5fJj9acUWUdRLlm3rfYGyc8jHeXzGMhN92FAHrKO1X8WtWIqx4pZsrjunhSd9x-Q2ka2AMAZPNDdrKb4t2jHgMSnpmp6izpjWiP6YH81s0HNuHe8dh7iUhKwPzc8YMUBpKW6C6wLCpzQ1yH2Ckj_FS7UJvSlt1-Y9DApUo7tVeu5maMQpXDqk19sVQlKzy28ypVURhmzyKNWcrIq8jDiA9-IHvLHSh3zhiMtSqUH67bFd_SHXbBCXC-Ns9OfBQoMStizb9Y3p-xW28M8l-635voVivLwC7Cs7KT0uhOR6bnUBmHPhv8meemUyPqw_XBltqxZV3WQA8yxC2BOrVCzEKkqsrJAcXTdi8rkcI3r0s4I06SZj9pIfgNe3Jjmf1nu40AZzsEB4UeyBFo1bEH8f9zTrCEB2Z-QKCdcf1F0BH00SGBg_9lCPzT7oj4w_jsxJVfe0pR9TSPS7J2p2c9wiNzCO2eO-vMuQNwjADxX2ge5KnBUawwloqrVc90bBTtNucsI41cmmGAa1ndcb8rKRrlW6HzFAQ0jX2q3X58EQ4H_itgRdcXarjLH00e-9wVxJ1d6uXvRqEHCEgxrqfx8Qwck9MsOsqH4lG2Ne-fwe56bh-w492F3Fi1ZGKRiQVcaSS6T_z6Aw9rI4xjapfTDfM9jTm7_VAjbjKFoPWqAhR9QBtl-QLy8ce0v8kX1yrdXpW_IGHZ0ZyL0QM1DxI7pHNyRnD6beeqg27R1Zrxlyga0X437jHBXWH9yfoSxoTIbogv_j5S6gt6lHIv9jBw72JNyPzw4iYgUvBfuRH0c4cHzIoNUZSvCR1rcv7C_LRwkC9qjN9o_Xx3AyBWtT2CQ96476NU_Kl3l-vFSt2h11dd84gY-HuVWEzK1fGpQVGg8JmH2sdflqXubvRT3G3bq8Fn3Lhd50kXxd_kwK8DeCwI5221ERj4NeVHyTRpwsxOnIPrgyFc5qPEwzteT7coVFswwH_Ecv531GDTgHuL2QhLjGt06v0OZZxzj8OMVCgYT753-jyXMzluTsg1qky2zcJ7D0CkGM3usjKwLF-dMPI9qoBeVPl3f2Xh0qx8sSQZKDGDzYWJeKLke276Tn-wYlgWy_8exvMkWzjH_QW9F5zsuogxfmVempuZyL9SJh1YHZnk_rsAXEyJmhK-hk2ovOQpVsoMrmvffwrF9i3EgSjw2rxKqZaFxQ6OX2ZZVaMkwS0F5gamcgifezTIumIGx_cJz2dBhN1Pv5Tu38J8utQDNMDCC-yNoHu3gNKl7sb95fivZqcuzHOTyivwQm-E8cGh1c0-KkquPWy3jRx9T8tf4A1lYG8w96y0P160MxHt6xIFRlgE0KsF1_rdNPkrXpN26l-wW9aiXVfd9kve8R9Pz5I7m1_jygslNtaTeOaFYAHKda1OHMj9-27Hf2pEUNM7bWiXaOyCLlmEH2pNt3VPrLe_Rjp9XxJ3p2tkJSaXn-bVFMdM4yVM1m8OA5pDALOrdZpTnJT9V6FLkmrDzfrg5vaq0gKVPAHnPKHb-wHSM59Osf02nC7v2Rjea4eeN-XXTYeCk5wlK-HY0y323q3FQyjoWm7Ur1iF50nEAmw-0aAeyVTTQUmSWVwQYF7-kqff3FHRKVW3wyT6NxQ-HfP8b1qGnG6Jt5TVXRJyP0OcguEXMxmPqt4X3kPN6zwbVwVz8hbjepaNW051FVy_Tf39v9x7IDRrtdUqiSTmj0ss7ZTjStidWVNJFRn11GgnCu4E6ARkEBpcRJYv9AkNL-Hj-qbvDpVJa1tiiT0pmeMDkJGwpuRfIiqM90b1dc3NeELM1-3jrX8dciiZ-C4ALMpanLIHGFql339ERMEwtnF3fIvqNMXxshrIN8ifkwumrzNJPtymDp45yvOeB4csHFnEMAGJBKiMhIBk4MAjB9OgZy17LvP4HmxRUgrcSvs9epq9VLSgmECGxRDmZ3T-ksKUbCcGQKQWho_tLfp9FlQiDgvuN_PKudCMq-e12aonL3AEP8CrOnuRksW_HXkggkBf1uirD4oWt0ZUPZTreY4Of_Gg3y6qKhC6EmLDhdI0T8-UgFuCUyUeUMTn2OT0UG_ZJKUjKKI-awlo2TKr-Zpdv-qT0bqFq_5jRvpm0mmUP7J0j0Sprwb_5MYRz3im7KhxghWk9B8QFAoL7bsOjqXD9CN5KOLnN1hLPRN7m1d_E_gMjNkTY4yy6_fxlYgPo23J31mdzWIffeVm5wPLtjmUidbrLafuLE7r-0wNtEuqkspgPsfYGBxTqCgY5i5Q0jrSgCNSsN9t5OAVRvsZUENd8CWZ1KzNQhCDiSXcKDxVSGXB_CUO7DA9zBtKjQQES0y1wD_ARn591Qv7Cn1Ja4m81NbE2QUGYItXtcvHOTARTzJrq3Awn2GFJS1Mbr6fW6QI6idIrhHIvQIvNm2eJqOGHn7F9Gf9T9IP60j-ChLlxoOeT7CIILvKQgh5NTP0rXlH1NDMLkAx2YPjNfbs8fjkeHJLzJQ89rpOQL4kYtbuk4-hi2rdzmygwqASjqVUjBFSjt75KewqeGZp4KPQpO3bWsjOlnmYizm5X-B-idjIYxK6uGw_5O2EvLyEAUknFtb836kOpUHU8rvd5CBvrM8OmiNAtqPy3_7DyexmWODpGY83O89ARQ4EWonXKkf99xiQOjAYfxE-WFXrsoQ5DENqr4_Yt0v_lsmLh9JMclZqpXqxgDRwB_VWuOLfxfMXwjWnribMpHAHOyRIbjQJ25UCR9-lFYtf0G7SPEYzun8K3a6omW3mD05LjzHKehalKXjfWcR4-dkzG1wKYbq_bC0Nv1I4-kzjD-q72MrJfHqEDRn0tP5nkIRGoQaNV-TYWE3nNRH5EwcVYeUcBWO54K_15cfCkNQ2ombTFvo0itY7U2wfkquu5kJeskfDzJQP8kNP__l2ufwfzZXnWjTW5MUO0O59z6N9Njlp_4lsvocldw_ry4CAwY7fLopsNdNcR19KEqCHng1wysyhS2TECBP91eBuebuIZsFbYpq9ao242BKqCOu7M8Z1mQKhlWVz89AVzy5VJoCSy6Y6Jj7oOITrWbvSt6Ktgih1N3zlTbsB_R6P2I1dXFr4XoKdKzDeOXHXsw-iI2zIi7gzPFpq-bhcLZlRZTPDPQ9DMxSk0G9SN6_SlN13oBUGuMm_sqBSf3vmYE0D9KBr13kN83eazfhlQeZBvgyI2B-16TIBVSLA1ClJsZtd98QuhM0HeguzKN01gZKvKfWSGUaM0xLidc0Vn6dedTDbaihV6VbpSqQy-AAMrJs7Usk8u-CqZKkeRipNoM9obPJntL_maPa5FF2BxeIUcipWS3C5WNISPXenuAURDMznlYn1fubVx1wTsU-zIf8U_WKCf8fnhBhdGQItEft8zrbdEqIrVGP1W56u1Ksz0cKAy3_nuQxeU0LdZyaqqeWV7NRDtgiYVmuB4czczuEEo_ZuOMbv0QDwLy3tzHsplBNu29ffX8wpXQL-eDc81lEm_TC1nNHR1U6Tx_OBx1pimfKhQdcuyit2ia--_3cGTleQrrCX7dAcNuPtPf7QVUX20C_UudWOIoDoNUnZNIXSIMuem5soa15g1kBAnc-POzPq2ealjdKG_CAg6mE80bdqCQOebMhYhA00w-1_WH7sq2XurvZRMU09boa8c3AAqk7bSOuNVOOWr6qEw6ImtL3rIsKQIk_j8GfVmwFdlIoqztgMGeJAFbuS0tNXUMXJCfyGAm2DVFvPzGH7h5k3lXyeahHSRC48hxA6v2eneSbf4tJS6iais6Pqsm9eZQAIf8VnyKLmZkHggQJ-alQ38staltp22L38YOYxNh78GIQSC8L7YjiNL24Q-iPzfwE0oaQv3hVLIqwTgfhrQ4Gi68G_T1Ikz2gptXsv8j2LSD3xLVUhLSQVwyClYAk8dKL0CzXtmVOIy5QxQ7eZCNPdeKGfweGoudf-_8UbVjcsE2UUk2Bw2-7E9jcKfYPIPh3HyvvYZXWiDIQvrKv5ZQsSRC_o_-q5BCrPH1ZGd4deCw3Z4ynz7Amjqa_sk9x0YvNZ2fJuIiuJEW0LvM4tddmv0DiPEyTFvgSQtvHOi-mzkgeBj0Jg3gnhR45Z61IOuSGkVKYpvCaTxB14UR0Oj3gK66RUrfkjUuISfa9k1Wzh8s62CEXA2eZ_dpi48VMzTNMRYnjSpgFFPUVnqx-GXWPaI5nllGv6IWkeXdWPadV4y3kjZTP_8ji6LtJsw8VdKP3AuPzlRz3FNykElk-NJieyiBbw_TI9NV7Vu2jdrThzQUJhPP-ddW1q-odmkDCm8xxQ2oc4foxI1RMJd5XBVosrVIS6k2bkwxjrvz26TtJRXNWEUL3xM_t94nK87yiz-1xt-wzGRr4gV3zLxxcUIaHWK46yPKptIiz8YJpA02XLoGlb_5hXW0fkGKIIIKBRVJsm9HPaoMRvykNayYdn1qGM5IHRbKHjGQEmn0xxsXRAY30dxkX93WASnUhghB5WZQ6_CJ_61SOb73Tzat2WmyMvEAaC76QsInSyThtxcPJJv4vMfQb8PXfsBZf7j4xXoQ7T7UgPCULG6Gx0rQ1Mt0gGcBacwYUexLGaMvV5Tr4ltuYLBg8rspCiewKiSKWiYGHw7bfvxmWrM8UBv2BDJRTM8PhUYTl8-6AbnnQXXCGLvEzGFbNJmDt4d0NalbQz36x1qqY8n1pT2-hFedwUwTPkHsNsu7xxMoQp8sb_2NlafJE6Hh3bhfmpOo7NKgLROePpVY0WmJSJSYUzRSJR1FqX1SPOR6kGSuJ9MqDzx-ExUHVg2qCTC4jDHK57TfT-4fupkliYASDaKJ4TSEg5xg7zXc7d4AicqCEBCvH_oZjxyvcSrB6VYorcverUCI1XLdSl3NVbe3KGNuXjdATFCOjBuSMAaAJQZvJVUu-k1AHQCcRHucdJqaPUKqcyxpoFJU_xBs8gMNL27dS3poIzpj5xFvm0H8rOjMWCqs4C-mXYRYV6wbR-mfcoqVSsYrRhPdc0SH3SyrG1UAJvyaPoEwfA7r7IuJvBb12u0Jm5zd5OfiYlw6tbEtTHfRjjtWzKn_AgDRMTbPay0Jv7LkUaNinC856jSTE7N4F5y8kKBHbrN9TOu3qf52DZYe3fkTR_HzFmnctI0hIskrWxcY231Jais_j8ZlPUDlafo8fbMposd6MLBkG7FO0xU8raKooMEpt_Z9l-0fvfThysZ3CtKdwYaeN1C7TWV7pQJm8-dyNhlDLz0D2LEFu2DO_--lHGSjH9bppnC_rxIeXyPU4Xqah7PYLxrD5c6PFLFIFmKtxe5uqAH_07z2rseKKnqBLiJZsRGQh_uBAhAsWkmAS9sZ1YqjYQY2XzjRRdvzZb0gxGb1UwuLtloR2Agpe3JxWjcGA6H6RzpxJGk6KA25tonvr9q1PJHG_ssH5EbAg2OSuNXcUp1qIBMnY9_n0YF58nM4tfWOQMDxT-fS4CtV7ftgzDS9NYNxkQEWcejWrJvo5Cdan9YvEIK2WWX5h2NRVzsxdRAB81fqA7hNVSkq7_XEWmiVUHFTXRMND0SZ17dbVynvzCXc4_TojqVDO0uLNN7BRFgDiqYlKC5VD4H55PNmg7S2SHHIlR_P0hToIrKlHtA2spxWzPSr3sgn0Az8UUBzlrmc2rvVhHhxXwi2jPPiEtcLm_cydcnnHnzadhJDKoLnuGIj7-GoT-wNkMDBtnMQSNLIQ06rXaJy7r59Q2tiwsOXJTXsMtfkgjK6zYH-3tgNQpFvkJBNm89_HnorTVVjYMWcNWj-RfY0l59TIpPgeAWR2z2ITLsL3qr0X69iYKJWi4xHex4fQtAadQGjfXkabd2U9DbXraAhfFcwg0bS7NNIgHaCKF66pLIZboxalr60r1-Wy9hynkIx_KVCro8Ip8C_d_73UYzoSW6xqcu8aOYvFXwPZGJZFuLOZtaSXwVyPqqTlsPmYvz264d9feltJj0SJTXN-2u4xSI_LzOWo0c4i_68cJcRmI5R2baEMC5BdxPSWCToNTfARpAF5Y2pe07NEu848wq_0-i2m4J3wFSUVGxOwQ45rr8puCEJESCZWgd_rUbTjkMwz9JevjkOy92DGl1r0tKOSse4szlxUhBaFkIh0UViDqzDQZzpQRP4__2pd5F15Yt0gnqbM8xQlaXMVsRaTZSfPskA4r-m9pgZHRDvZhvxXH8ngMZLWL0XLCrS1pI5sbLM7bBN8KYyChJ4haGIohj8044rP9esvI9kuru8N2F3lhBghle7I7Sk-ZlkT4yrZ7k4yVdLUqw2VgY7vbE_dmX_qr1UyiPg7BDqmJ52Kn2gl2W4rFk-1j2ELUZqzi5hHPzEB7Ld3_yvi8HYhbPxC5Qtzl1jbfsUqGJgreCbv9HeNb9ztsta5tDhjSl8K7krIIro-vYyeTQ4S7Iq2Xvi8XS6hruK01RlbvVLn1p2QYNFWZxvzuNmPLOlT3u0gJE-muOd4JwdZZTY1geqI9zj5CRwo555GKXyMcfw7H9TDhdcgPu2EMM-Y5_Rtx_Lm6OWx1VuXbRS6POnO3Goh2ITQ3i-91tHtlyc39z01mCbSFCiQe9YQkApCZmvo0kZdOpOD_hHx9SfZXGyDzYLA_BHRNVZ4wl_gIV2rIquUZoGcRxGS-1A7K2o9gsy5QGUeut6zHNpXc7ks8PBWpOcercl3rqQUHAex2xERMXtc_KD7bw8mJIsqdvM7jYNK9_D7KOfrw7PKGJRZNHzUZ3H9aLBxLmHXz5rmYnzTU3KlMilNQ7O_bIejd6GuW2yghLcZ2XpjcYFibcYcTdpRvIDLJWIQPOV1Uy2WdPEVFVLhpZBrSQQOYSuB_tDSex6LdJ7d8AigR8eIj2w8v7roNbY1r-AyJ0PDRTsC4mfXbHUkaHpFomjTTNo9b3off6lKMBygcfTOGXlIlyrl8liW-s7kWGzK4EMfjiAMbav7xO-Gww2ae5zchaBSrj5ExX9pFNM9Gpvlyiw3l0f01hefhcEIraWnk4Z767OxJjJ-Hwy6sTnG8HO_zpBG2Hr0csFgiokvweiJ9iwG-iMlMNhUa7RcKlaNg3UWyFxOXSaQU6MTMaa-okSwruiWG_zaWOdWUF92e6oIcJc_WSq1MdfXaG1rSHs3j_F0uDWsQaE79w1dMiYm-6-G3RmbyKnJzP62wMdgaj8Gfyy9Ga3OjatSAx3vWN-78AeCdQOKUAOVxcG9pQZwYRUuESHfabKYlWe45kIHA-KxSNbTfdPqHJ_aoLWr3vqs51FLmfFVAWDKsDCA770N1gD-PwutSgqFlhukV_Pf9lGQubsf5v4WCR7nmmMpHRv9xOXuHLgDQZD2z9hOdU1Rb5Z8vLQMCKE1OCx3yo5HTta_wP2IFksfAVsKlBjXgJm9rmWa_y8GT7IG2R6qJlTbqzGIfGbOLoYRK0fKz91fDd_AIluH1-D2zZjEsXCPTrVCrjRE0uh8g7QSz5UmCg0rSG1jOF4RY2-x1DIQZ72YwFa3iB7_a6BzmJg-a00o1NN2LQGhlDHNLQelbIR9yWtkeycHllEnK2NMLQV7nBuaW13BHURuQ1iVbHUMJmcbSccU02-Sk_w2ScUe1VZ7Dv-I_vTTIrjg0mAQs1nUmNN-E69qor4dvkGxWsOVDqQU8wVqSHaLAj2DoY_wu2_pjCdaklWh5uWzFNtB64xybTtHDm8R15wQOqWs7ZgtM1b8HsSZ0_aZ7yJaeEWD7zRYBQg0SBKLO2enkMvecseyilYdDmcURoWj8dF9WwrswSXw4T9PngXs7pOXk2k4hi-DsOZE_CAyT9XPKj1oXDj-X-1zsk1z8ZPw62mVBn3qPBqpVlZ0Rfdd-CDX_OFUNaGRqQnbMJkYLZ-RSzv9f94d_aa-Dlx-jZXfKxZVmMoe3kc3t5hnhhFYXOtbAzJ61eoTNZLm0FVeS2yX4vUY7iXXkJPGMpj2gFokaKpVuB0uTcUnFbhiO7ss0K0EaZ9alCj71G5muXtyZKfpXTXa9iJKDFtKHlRJSPxnGHhIbd24ERak8H5AjkXBjLJGapyLUEjO7UKV16A52GcNpUjWU8QrOcONwpceI11frP9AyfiOGpUybymja1Y2JFXhPoDmDB0gUjzkvmJTTwktCPfIswWyRoq_smxoUJ5UTnD_RouZ27fjL4-zeHc2pZ9SUkCxpBRBjjkItHsOiNW00bDZgX_wRybWDZUM8F37hbagWH0GtRbr2ox_GTP-Jn1v8iEPlyhXhAzIaau9XbEU56f1gvMD1IB-zFKGgKB_KB5YmusWuAtXJxqUZUrXU1Lgvtk5NEb0N7HpC_MQHn2zCP-g4_OkfjMcpwXRFmCCi6Ohi3TypOMH8WYuYug575D3GbGrnjDMyoFm6baQEsvfwGTvFb_CHBQVCCTauorbqqVyfm-SolZEdFJKbl-jTmr1_fO5r6vzvNzdRUWUFSnYvbSYNr8wTj-OXXuwAKhZwUtFMEm2akrmLpVEhUKTzNiCy8cyT2KEYQASstIUtg-XqkATr-IStc2M_UOdYCRStxn7BhsbS7p2JzBmUMIxH7d9bmqzo0mD_OCl6SZIrLTO3cpcUPENY1YQoXkAbU-jL6ulVlrDtnyhVPWgcnQMMulGDCI8wOnix8qm-Z3Q9ChvX1PzfcHZ2w-aTHRiLmU8GUCitTa3xqNTJds1oTbs562YWq1ghx6uhFaF7enG0L6WqW_OexY2WTQHc37HWft7qaj--XqKQKds7jQiDECKYWz-HUfj6Jm4vLKhzfkWaTERp1noYxE6oDz8hBbnVMO-IoTTuncRot9d2sJottbmtwQrRj_TblT_w_7ldfQmB30weYYrqxd3XszdNA2dCOY5djSDlWyn8Z9i11wEFTgnZAjMRF_8j4OFMoBQgfaTkrHn1A7VaWuy3TAFlFraxC1gwjaZy6si59iWdZfiVH5lT4Ig6pvGKKHWIOVgYE2VZkRhnEJawqRqj3OuaYY-86ciOFEahpCi-_1Uey-QwTUDeHINbVDicZPBUSbpkZJ3aNql47qFbY5xS4hSwJOmNUnTkYOUkUVqy9CSXQIyp6pi4VRU1Yb7z4vWKSbLgMhv4PXnUQvUVkkBdaUHTAPLjJhVdp8DEjxz3KZiCKQx8jGhRWyDCnNHvF2K5hyudVVh4CY9te8UMjVQDq2eeWNR1buTza5M3r7hxxn9yUVibfMme-NnpsgZpC2Ues4W1e4AJEF4PZwir8JXygSYqkZwHfAcyq1w9AjllReaQ95UWqMszMUOQz31026UatiFKxkfjr9SEGY8HrU5bfuw8cxGDzpLgWj8eesAD3_fTmOmq5rZbPiTWP3jR38rOxou6Uesz-37rFCcdSqT8z9e-Gu11sKoxnFwXmSRK_0g1xbeqYLtvZzkubwu1Cyki32x3-GCW2SY449VZr2L5zMeV88-mg7NGVfWRWlzMt-ZbTQPDeVuan3H1KN-nrmE8CQPIiYiK5go0WhERkgoiXcIXvvUsMvD8jH-zhMP-bcdKd_PE2bI9pm1345dsoBt7MRe7MsJZjvLQgcGRxrrilit7jtehGzCWacsqI2x2haQWcO9-DoKiinIMer_yPL4BdmJD7OpHNKztJqXKXw61T5BhgbMT-JJ8SDtdHIduGMfwJqMgRjmKxQY8-LhigRCm-5w0PajLPGea5Q6eDR6vC1YqZXXOSsR3UWGKAOX331QEIQ1T-j0M7nr457R0r0bRdgr4d1nec_BSbu9VmEMa_DVU5d1OwGQIBd6_4E8yHCB5gvwqNRU5qf88QK_zmZS0QwAey_yLZAIDLGxQeZ_e6nUw7gS7s1wUz836g1BXfFUp-CH24HaoO94O0z3K3PZty-90OaYHuv7GFxStOZO-kPjBYVgf3ybz10tn-zRzh1etjjaENmcqGIcQqFvr3Rc1QH_UgQRn8A9Pg1YiHhQKywfpV9PJu0_QE9kvE2atzaI3Z5_8MiZumbbvnAU5a4HYx5sPWfkDbz2dSh_Ib-zxrEhm6W6iO2aMaAfBHzf1Shahn7Y1ZnHD-LLf-THPlukGRc8OopCPC-jmJ1udpvg1YIBoayd12jmo1cqQcM-v3k5jptIvts9w1jUGO4-9l58Pvwvg_i1C_qarYB_Y6nQVovuxuPhjjGummQUrSSerooW1vJkyWKFa64Gs_obiq7QJKXyZHs91bqKz6DG6Pr4ITEavOJEtYzsB-JTolkQwycZynAiDgSHAdZzTmFCxO3ylj9HraD8ulLCxtDdo5yy8sxP9iPQ5IujnEget3MLwKyem4iVNd8lrL_4LdWNKHUPx0K7wTiiL36csrxUmsQeXBWYo0vFLa8sxvVnfARoi7DMU7HIt8M42MfiuJ7PR30LwC8EgCHcV5iQ2O9C6_m-W6HmWn-be08SUKCKPEBvzNobiwJyh-xWzZ1OzgbPcpgAMOki9YfHkzN07vPUqLJ3CgO5dQxz2qV0DHREFSLOwRPId7Uk7xtFeOPoRlzXCTzes-LReUygyylzZnpIxdET2VvuJyK9XdeXcCz1SGAdsPECOD02B0vwXca8qOhXrP809iLaLk3QhgK8MeuPXruK48beFg6L2a4AM6ugxggukYkJv5UYsw_mUL9IVY8hxC4OXKfvpi_95zSY30DrniZ1RNHgJGqEe2_zhQoywd9dIEVmKa0FG5H_V7_Nq3-NFB1lZ1r4NQN9wrp0F0GjdT7FL9fH1wpOtvgQ8HtoJ-juKM3ytugI4LczWhY8dgtPvnEFgEsNJg-YRpQzuCQzzDwJC45h3t6p_xdmF3YJEJyuzVLrLL4N78y5ufkboxTu7oyWCpuuH9Zd_FI3SBO-_KxyME_A5uALJO8OS3fXEE8RAfazzfeClDIShPvbrVZTC6el-cKql6gAFO9t0HMeO8MyP7vOmOZV-j8H-7UQjroXwyIqudKa-PkeR9thFc125g4ewrv2gwjiKqyQIicGNxPAvHlfmPp0zzXBuqyPA77fQRpy2OOHFK7fXThlV_QvDlftYglqhQKVy-e2M1DztJbHTfdhTXpQXrsNLeyS2q2NKbiY11amxdFbgeve-BiBVztJFD-Fi-v6atwlvAGPJN-tEkcA5lIi6sC3Erwz0KNt8WvNIOrx2VMQ8rURlSx9AZ3U_wsOA9PNcEI1CYNtjX4SUpIXk987F0TH3y7XsHnO0ZnE0WigfzUzFJe_j-wkSA0n5sNSbZbCCDXfqC5klBb17ILcRMp_B5jR7hcjm0SLa5ooWOtext11b9ky88YFmnqNklFEEq0UfgolCspqNrecwAvXLw6pIILYs38hER2Y5XaR7iNl6p0tsxZwLsn-sBIS38FJK7nT32H1TaEemsLd-LDAqX4Gwc3t0oWsqaUcLkwjEM39hIQ-YCuxrL5zaOxhMn9ONdNREOyMW_YdW_YKyOTzIPPZ5YSH_rlko4zWDCyC1d2PSIpB7MSJODSLUCXf22HLkjqLiHw6GKPJGazUi2_IjekXsQKeVmIB20CM4cZnmi58XM-gj2OK7uGAScMRVZYM5Sljjswu8S-N8PMXaSICAymhJGGpLXopYzub6120V1K4XynXluTDpAHS7V7EiPVEzKHfP7cSeIK41LTJmTN_3D1xvCtgfBC-CKOT9CAVPcVg1-oVuLeDPlfNxzD3bFTUpYuxGFvxDcpyRF6iN-mODqHOcMWpGuz2tMkEz4ONo-opPZDwHiwYvqF0L1wfWIZnwx9M7EDFgp6cJ5gkUeuC7MtAzcn9YCtYXDjz0X7fuJ9D_5dOl3ZsnFqv4RKC_lBIhFDGNZtNMAiTtBsuvpYfLdMFZL-lp1OA6zBWvPOINIUXCNt3rRizsT9dTDvwLxfGyLuJtimL9ZS0ZgOMd8Me1XctMIL7VJ2jurDyMWvWW6KGDUucylVDF5BJTx0yiwVwJ0mFkAaFV4_JBKbpqgoDi4XHNmnN7FA5XqmxcQLdvwW91_m2btCKiZ2yjXTRvkjnkgEsbBb_FJxLGG9iefj_kQUX-pYr5Msc5P9UttPyfZd6H3nZ5-RNHzNVn6RZobTcoDxg6sFAA7YbNjZw2twVKvXOXRdeFak7vQv7ZIUguGdsa-WHUJwdrPVeD60DrqPEq5FVo2yusBJT19NIjL4mMOUL2gKyRu5Kf6lMZYlWZUkrCscaRE55SlpXMYFpPNMSyOTHukpuaWUPQdC-0bUfvaF0lrvXkpyilzL4lFha_lXfxDP7H-8IR6XGsN2ULfQDsyhPrBIq7EhBh3EG68Stbl2l9rHiQfYWEFCy4A2cK8d0u0O7Yyb-qpA4FPbC84UV_zpNV4LGYB85wCyQNXIS00Xxs0a2PUA9kf3h7sq_H7YBbkBpA9qchDNyf5gco3f01VAClaG2h5T9fF4pcpqHQ4eunqIrhuPkM6rMADpk0bApiiMAxW3WmIUdomKoWRIPh-fqOoWPJ5D6vhS1IxH9kj897nPeKXjRzZ0L9jO9ka2gUSsU9EPtwydt_2xqwNkR0rD-Gv3y1M0-Ihaq8h461lii-6XESXLTs09drNLBAjUN1PR6p6GMgKytqAUGdt03wze27QcvYueUzI7WYn8-JbPWjgjMXydqoeeLhVPWDONJDYz7FcyBi4yzkLLnkfo9IA2JFHL_Q-1S8yRwyZipMQBfVwhSVU64NZgrzVODOBpF1tFpTAX4ZwJzx7GvTiUDxAmZhSZGl--q0oH8gD_BZa2FuVhJZzPPi4JYbUqjQApkG3psylrFLxKn0XJs78KDcmrZCNww7KAu_shClf4mXuvKvkmIcWlC1U5E6750Vj4C2yBxMwruijPHrcfi_QHH7yVLUBwp8Ammv49S_fPE8F6ykRyZ4Z9iOCR6DIPYnMIyA8Y8ytoL_RWoXg_cX7tnPBYGyrYZx3GJPxsVTKL1T-9sYBNnl_mDsFYQdgx1uuoDmvAG6ERX6h8rRN22mxbKxbunolPARV4YX0kIMxkruzelLAYf2dG1t-PY11b-5W1WYUp3EJ1n6oTcgfj3Tmz4-t8_JjS48lnAmD1OnNrPdQFu6Lkf3iw2bfXkulse7PRjkKGh6nhVAp0umtwqu-78zGuK5z11DFbNcgLp_-O2SItPGaXl8m9NCs1BeKF3MlReI4C7tpHxphUbKAskFOX2zRFZ6ALLoL_HW6sJiPUe-vi8h_litkWSM03YqIb6wgsnLl07IUJpwDcsiL8_dS3JV8vf__IoH4YkQ25JJqNQjtIupnMGW96HVyFq9tjpQfYp3oXSvnd6as5aHhlA_1t7IC3l68USxUMxoQEbrRL8Qy9Og0HNi4DxEi17XBPSWTDL-KP2TxLlm3YAsE56N1xhlHNV7r2UpFVvi8My55iMG6jdgZZ7ApX62j0qAWY9R3P4Et4WWlr8Df2iZECK9Svc9sNEzHUhOly-dZ_fmJZAAR65hoD2tQnqy-dUNWziWbGhZ7A8xYDxVmsspaEdDLJgftchDt9zPikYh4lO2dwzdyNXrv6xq0XaJWcdES2gD-Jb5RDOWaSkeGm7DANZtHOE1EyaUoHf8r53ZsugfMvq2cSvo7_JJvT83cnLCbL_pLYNQjt9rHaXxSI9a1ZMjUdhGIh80WnJHYM0L0qyuCI6SJZa-WOYVroVQMc8PLxZ6BRAkCFs3gu8UZtVp1E4TJH1u0EFor5TXAS-LrIkQscYdSBOm1JD5pmIZ1F5LJZEIaozdsEqDT1TaFKitP74asqPvJSDDMwoVubyvN8MAod7_jxUybBRAg2BMlpMqa5FbK3OrM0hGYbSXgBWNbNB7whuBlX4W7Dks96Pe5JSLpY0aaRtuLbc5bivnpoJYBctwJSSdXRAgIZBCGQbSSfQ0E2rpN_fzyfhogQXsEReh__w8J9dD7ukm3kIKgN9ZQUpareHp_R1c2ZEiI4m9tztqp60P5Jx9_q3X0H9bKSMmNjbtD5yKRvquKCq739YHpFoPkbmvpWrf4Lq6DUt-mMjewu3ZcW0EGiTnovHAk_OWR__lwNJBpXlDDNQKcaFKNIFWFW8mtA_6biqCb51pUyL7kFkOqBjEOBfIuRE_mUqI-LGvJppg92RlicSY1M5SG7BG-0D6XZaKjYQPKgTI7jLQ-EkDeAlPlhV2acRx3v5T4FMoxqi82mnFRTNanLKLbnkMwhIABU766sbwkDk4_KHdDqu7YgWgq_eIHhqIBk1i37HCNvKrkEq7Y6tODRS5Cm1p2fJwnrE3fpWjVZplycUuPpz70EsEnvrp-qeOoMq_gTEpO4_-j1scQUyzu_jHlRrfjRXkdRs21rAMUwV7dQIUqiwfGktEhbMf7cL-EqdWMJh1ZsyT2g0K1TtcMHpNersT4iaL4BuberQq2ez7Bkv5IttiQUDYsxMCGrDv80yP8MDeaAx9Q4MR-9uvDmUdBfMtHMrtjdip5D35TmnltAXa11OWX0m5LSiRn_fAQp_fNywPXyiR2RMxZQLWZKcRFw0KzgleAOjjP_drU0XLdbfQIsr3Lr_nw8zd8mM12xBctLqDGmzPhkcD0EZfj3U4ih2NBf6z057jNINQ9lqRscNNCrw6tPPk3RSVQYEBrhAFedHJc7sghGBHAyWEvckybOEq1b4UfApxx_yDtGph25fpnjdQMFKeBWTFPDy8HWhM_YVnC_ruWSICcve_MmB0Psyz1Iy_jei5Fkdz4L3Bp6q6XonZ7wuZDLqgqEEyCyB6KF8LD1Bdu-uzeyGx65qPyjMVtpL_ZACko4Ed7KUQhnBmG53NFzadBppq5l8r9R1mi8rDgF1-hbcP8uBRyRsad-Lock-_JI6zG5NLXP6ZL0Z7Ht4JYGO1S6yvNQUiHqONvgwSEjMaifOsBzt6fxyo3TFxKsqrc8dC4Uo1_LVDBZY7QDIm_pFQmftahbaTUdZnFsGwHlQUVpU4MK7XlCfp9cO7iE1a05JEzDdEJeR264GCSFysHM-ed3haT1xshC5yLhVhfO3Kb64DoExkrGCko8RT8KQacoKM-kHT7KPBVFkc-zu99DStY0o5GUuoDImQZiaoqxkatApc1R8suUMOM7veMAdgVjOJWmWKkgy_Qhj06smxLTV4-DUEGp7NAU6qgnvhBjbwIO2p7EZZdCa08ABXuVQN3_DhQPtubwaRxcNd2ep6rr0jASOOjyLrPd_hx4AqZUGfhGgPeaG4fyQlyQ3_rg3fzFQDnfE6Jy91RfEbyUXIqGuh1Fu6m63v8GiWiXTNTaTQDNeW7D_08HR7XXP-JjeERLs2qLrDQ3dmbZIyaiJfQHwzKPMJ1Ip8nY00liNT0ema_EgDAgSPqlXUmZaKcs-bKL-1kzaW9jK397ql75dneli13ACuvFFKUf8CWqK8UUDE_G2wKPhvy2BAtNjk7hPUu3O_Q989Eu61axJbMZSAkxXUSnMQFV5gZy0yPwSDbIUBv_4HDjTAfuqd_B9lrCwFxP-TjTnvBUkk37iFO-SmOnD1bD2sb9b1p9MT_GmiX5t-n6T_TzWynMYmmvzW-xDbVbqqZgwSEadK9iQgn9r23S6AXlrVXu4JktWMI-sBNiQXDZrZf0qZ1kpkTJTH9-9gKol9ZC-UJq-PET9mhGeY0mAxZfPEG42VA6TXjGEmvfb2lazNV0BjPNivhzfkeF1TZyp-AG9HZTTeN-UvMRHZ0cUBczg1MTmHdK7QvFfPjgnxEPh34fZ1QRF1RG2TWYfJlT74Avl0P4GrLy9MkzItOc2CbNQj2WwUqmsuwIJdJ7nOFESlAE8bfDQ96XZJDRqVxdnmTWnGm1jSDUfYVkyvSWTJAmraAYmnbutNXWNGUMZ6Cb2cqu0o62wYBUbll6Zy96hCazEkxcUI1-z-wN9LIb9_7nZQkMmLClaJXxLJHn1fz6mZwtYdUPjS8p7zfKdH_Y7Q5lD7vYkFDSS3yzeHeIYqBsb9I5Jk2lK6ss53CvERZrVIvquTvkIzCJ1C-OspWPa6PiJjH_vdlUM05jvjiJDow8TUBzMirbZeC91HjCoimqBeEBDye5jJu4Eocbwtr_suPNqLxZhPRH_xzMTh2SFy3_DCduWXThBBZaFTKGZooObt3LCjIab37skZSr6hIihhuEBrB8srsDGnzrVIR1gQkzZ8VztGzpNLVqnIWVgiBMToG8-zGU5EZVgdczmPQWvabLtJOhw-tAvRrHuIHT4knUVlSOj0kcnzme-P_vcUNCzDVORjFrGDZEFB2b25DLrO97TKStazPUdCCyChQRCp2OqKC8abvolkfjfgOdQIRFB7aL2zxzX7aaf0xhpqMcqm4zeMWTyiF-qKbiZNSucyq3vohj9KVai_XOtjhEOe6H4tRKA7mrhPdlHCgDY3UXjwuUULV3JEItIE2lyrJpwkesT4r2FNTxsWETvMJ0AapvCBc5J0L15VUqsTAQPl3vkO3fL_NxlRGC6sSWPz_yqfqWNIdRPxgNRo1_Zv1Z_JsC4X_f9hB2YiyJbIatZhqDwpQFPJ2MbSa1LC8VMFLp8e21zOEx8cTr3bU5o8R-sSI3nTU5sal6woN3hJRMeR6xq0KBHCZQra3t4EZ5lrXGBpHYpsLUfMB1lP8rk-inljJYQUtm28J7t3AIvNXJ7aexBBCjb2mxEi7NgDGffQSHCBNcHyfRI9sZoNaavNwG4EMwHqHhfWEMFYi8-171dP6nwqAGyv7KAbCx79YxvW36WMx5hadX7e1IOXBrFbE_KcxIuxSk4SJXsQlt2fQy6zXNuGTNgdxhsJ5In5XkeJIp6aB-jg-AhraHetSokpAa4l_WAlsygpvkwvu27NBBmUi-_M-o1yZgaYzcUmoVMfY9esoPHSkPzonr46fOYdqg6YE-wd--_fBMpbAw4by5q1vKd5M1EY3vOnCZWtG2AUv8yz-esDbvClKfe6I-oJHfSHANtAya1hJF5X9TPdPxxIE3GgMskyR0ch2czDU2GciA_ReW36PzQOB3YZ2a93srVrdcplxn-L_NTsMpYL8dfwD5TLFgZ8BJKd9hTlDu8V42i_RTCAoL9Uo2OsJuVr7fg2gWbjRqZRGCa8r_Vn6Ekp9tHu-nbpzzUZOrzcYsIX-h5LQUi85y7dl-DiK-T6M-MbnDTScsm0tM_vwoaeOzjX7--h2XTkuJF1S6XnBb4wIRhfY_YRj314PrqxWUzBnqajsvOrYTS_ynUeZEzM_VgN9mYGv_lVKDjsMLgXrO1mLFeTY7Ku4vdSdmaWmWRJ-adlUeoVBCBi5tmkltk_vsg-WLi6NnI89WnVt5e2aM8on7n9_PgYT1y_KrpDgL25lqB9IHch_oSyeHFflrted_1tnb4Hjt2PPOVAlcathK2K5JKHw_o-HAdQs6L5LsKqO-ffwj4PnJc8gcgTZzo8bZNJ99UVG0t-fQH_gwCFLBqSboLdnAlgwjP7Z8mJA-RsJu2wbzcpvUwA2AT1BPfbu7qDGc7VkoWRfkrNq0zgAJjpQzQAosPV-zP4tGgvzUkpK3tAQKYlbkk2mbz1-a1BZHZldFu5Tjk1JNM9adM9N5y55IYMYJulRgV3gYmecSJUSrWfHFnki0_LHcQVlu6sW-r7FdVH714GkEBVSdlx-AgAnkVNuwKQ2lKo0gowEwrshZyFS4sBHW8FfuuqQD1CdNaKIfYIAySVHEqdst-CJfbsZpHaA3Q8I3TqRCvR0LVLEp_2wfJ23GCXnn0mfUB2vih5diPtpw2higiITujBZuJmdZsOvewvQKJs1gq1PrQCrR688YzwrReGI_WHYK9YrmqfBjshFTFWcz5Zk6YYsWvY3elIvVWarwMBDp3QuadjSdScDH7Eg2B5GtvrL8hUlQK5l44vC9-9bpYmctsSdYdKao8nPCfCIa7ljGxHRQy4Ao21axA4Qq1AnWE5EzMdNK5JftAGPFRpRhZeTvB6VQhi-LJNV7xr-CJbNnCe_DMIFozDAWSkUjfCLUWio1hWgyGOVzOD-utI8c72tNBQ95ZSlBzhJkHeu-gd9Xn6mAdLCAx8T3kPOq27dvdjWywKKtiKFaYIoGo0aHMz3L9VKCuiaQlKzj1aEr7_1-aBMAAfS9U4iq6v9kbFsETSNmO2uS96J10c8jFhN7oVYfNKtI1LNtz9maUi52cnRqP68L4OMw7au5U4VSpg4MkPt_VCpPXknwBPSpioMUSwjGjdOyVH0PkeTk33coj5A_3DD4oZAvhY6T8iRxgs5p5ktsWBJLOHUg2BrEnN0j2IjSXMfq2jHw1B0svvDogTFSdBRTn30pfKkoKV9EzWYTmo9BZZR5cal9c_k8wet1slnnWOmzxLoM5IngROyGYZbKw_MibSJu1HsQIgbg65tLY5SkM6ZfryRzg3ZAWcDQ_P7lua4dLOUV4dFQuLYt-o25ZcLo6YaaL-OC4QskZFhEi8D1qdDbO5MKEqGGIEJKNLKm2y2P78FFiJZ2l0Pe2GoQJbVQ0FpoLoSqlvn2CZKNNtQQJZHKheOufL3QeUxdMLFT8ILavcbWvLS-ZTyU3k6T32SzOyYjH9d8uvhmwXbDhb-L44IMZgSDsDoO0R5-Q0LKBsZt8MWnnJ43VdtAkRzBGVvdt_Kx37foBZfEEbFT2yKk3_5vtywGEj8wXqwJfUqsWaviScca0krnljSRYNSygxwO-OzzOu1buWPRMd6BG1AhYqAuM9gCEpPTptTQ9LOVm3CYbr916PGdwp_Q40xdbweM1m6ZpnUwv2vsICZOpCcYJD_k2MkLhA96kxAlRbG3aod7d8Qdy279658PTqyV1KlI-1HNtEPlVFouTRICfSJ6nhGbVTo2nEUg4I_q9RSIKuCchc80V9bLBf4znK3AQVbGaAGThOt-QSFnlCWbs5aUBJ5VG-BHos78ho531IQFbcYNhPelY23dvV6XE8aETvOIF23Es4sDMvUcbGs5xqNAhi-ks1bPukyjEQdlfvcJON0nyVlwBGpFXiSvFYDhR7EE-_4NBMIxldKHqzi2OgfGh9YyiBz_UiT2yJSJIEUJvCT-L1bCwPGsSRWdRkX2a6PRarmoImEDIF_dZ64UHAACC1QgI4iXLdrjU6g97scMuqtymqoUpc7nb0LgJyQ6fNwiHrvAG_kOG-UuXFMPYkfN0q8SLxqQ77Td8VfJFrjZ2xw6OMLxn5GN5lxLiXPImr8eCPmz2IN7Qwlh0zshUsXezrI72doyXIvXyUlk6_u90pYh_yKEoSP8IfSrBBooGxof0zG7i3wwoUF2PL_2kGgZNkhN0P3yz7IXhImZqytyv6aMgTbuHaHkqUNSAMU_-CyiZSR_sKAL8R_QnUJW93roHj3MxTsi0L3XVjTJVyjatyz-x7kci15SbVqZe1AJpCJeThiRQcQdSkKcLDHKTW6bmTeMJ2oKSJLfnVq972TY6VLusCXtQFB4miWvzlt5zViJQGYHsVOIx_Jwun6ZgIR19PCzDZkzEo2edI6xteLyUd-XDk0LXDxlloDwg7kIz4kenLrD04my87ibFvrt9X1ymVAWq0HBHgqoq9q0qYUjEFLbhV2j85yLpppRpYWWOz-CeuXP_1ID-xhGAZbfygNXqFEAzeZ33HgEPPyMSaPpnMyXoqhSxpxVYNWzWgNGDZkbIjoKHsZ0IiwpGERPl1xoMJomDHhfd8MeTn5mLJogbWRuOkT5fUn1dD21ZoVC8MSxB3q72LmDO8LwyGzj8c3kwMWvPWAwLOcR5ql-05LLLSCR1-65ObBkpn3kxuIU72NT7RlTyxDWmZCNBvRRLy9ccD5dmNXywIZRqgUMisWeU4ScSe6t2NANCnTmO5EQbX5QtKO-OWzYrCrxBk9WjHB89H-4gEaovB_c76zNFh9NDNIQvecdXE__JOQG4JfyOZZGg_607FPFuWxM7WOEAjKQO6qqvktaOWozMNjgUDN4ZPO6iQUujby696VBgGQb5vPuD8k2onfrBeONHEB_cb-jNA_ezl3p8rlyIRdMsa1tjNu88rk6ptYRFdT7lCDIcVPkXxGOYGz_hNKr2t5Dfq7IeMqOsj6OsdlvcJ-U497rWVT2LVgMNQgUtNe0kPUEo4rdIWEF26P2EOTy9gshjF64La_JEkMJSqHvILU32ROLpao-eOJILZH_suVI54GKOpyaFv56z5pfheT5yG83M9aa262gmYdrvaT2oX-C7aTn9PTan6kn5q0QFp-qH24i0pgUZr4GCXX-QQZSzGB-ULL40TWvxL_wUYDtdIzs4iFWxBplHXCDksXhfm5sSZuJtXo9UuLqmAY1YdyClk82N5EKd8R0amM7toIXdPNCG4twQBJvsSlOa6_sbzLBxpRoZRWMwXURcmRcAG6rK-hQGoyBl8EJFytY8nduIwMxn06273dMW1eyjYKgOGHfM1qzAVGv3wbzUTqdoaJKJzoGvh5rIhI9z360nNt3W13yTt5lx3AJyaDPUixBEWHkbfXq5AEPiInfcVT5tFPM-x6-KBGjraukgdVBlN5U9W5hTBvHDJkqIAASvne58aydtHq4cdU54cq2_Lhqwk9P00qYkarAjs8f8NkkMxuvhr6XlrciXMzqesngAsLnSXsjn6fmEMBPccIaUFMzvSdwXDenDlbkObSEcpEk3pExUqBRViExxtcg5j021-FJ-RCJMe1ffbnN5KmMUm6m7g8rEluuxkoOIY_HBaQBZG01tEQQ-Surnc0RwW3MlRIpwwhYMwZpLzrrzJ741UFSb1ABbwSPsa2iwqGluLW2lx4DNHZKyB0r94sUTL0h-Enjl3lCeNfLiOB5kxpU7pLo9IYU3fWC0aJNuMMqmNsPKrvfONUPRmIseDmzY75k-KUWfpsP3hEeJpk1-PBOLydXGGCDEEO8QYJQVpfNBRF6rcFi9ENCT9mgeE67sSUa2OV2gmh85LX5AjvBG7Sk1W-tm6r2rJPTTltwaf5dvnuBBrR3-JPbxjwNJUC9jdcK_S6Ahe4gZOg3ZrMHWOrGet1eHRHNWHGtOBgzqHZfQA-m0daUle_qW6VefIXlKXpSVzvE3KIjOoURtIASUtrdrzgi0S6zlP7oIYYda8cS8EY_f7dUIsflTGMpzPztmsnHrTButCVXzjvjIpMbhOEgTj6iq1SpvfJZk2RU50xVB0_vpFgM29TS3WaL50X_haLtVywWLpKKhOvDVGL9Zle04wLYDrWhiTHfhxKAlhDJjk8Nyya05VFoW0g5U-o_Z6JR-2rp2xsZBTiBWHxX1R_MGNjo6yBNDGBzMkUOkXPnzRjlfUk6zXviqUShPplM_f32KQTUhuJieHIBspys6YlxcJXnE4Br4i5g0Kz83JDWcKazecxQXe4e4TM7KgOHFvhZieGApNmDN7EiqfUZSPvoxfmrMnh8NGKNVseKuk0z_gAuK7QXrAHNI0cYjTKyIXLviPg9_1zRHjYBCqB08lDt6G0SmnuxPGhlFvsORc5kTt-JmArH_2LkhZ7J3cMZgkApEZsx4fQKB1Z7pwMIDQUdVStYLq_kyrZgQgDaBJqF5LPz_7MGsoDyGxf990WapcIyTZ7f8mMHPzfoHEXgpHjOHqIFPAaw1tgQJD9zngc43pB9sJLDXn2J3O__r81edFy17C2yg_JM3FYzQ2UCILIIslS2L3MvADh3qGB \ No newline at end of file diff --git a/v2_adminpanel/BLUEPRINT_MIGRATION_COMPLETE.md b/v2_adminpanel/BLUEPRINT_MIGRATION_COMPLETE.md deleted file mode 100644 index e1af8df..0000000 --- a/v2_adminpanel/BLUEPRINT_MIGRATION_COMPLETE.md +++ /dev/null @@ -1,42 +0,0 @@ -# Blueprint Migration Complete - -## Summary - -The blueprint migration has been successfully completed. All 60 routes that were previously in `app.py` have been moved to their respective blueprint files and the originals have been commented out in `app.py`. - -## Changes Made - -1. **Commented out all duplicate routes in app.py** - - 60 routes total were commented out - - Routes are preserved as comments for reference - -2. **Registered all blueprints** - - auth_bp (auth_routes.py) - 9 routes - - admin_bp (admin_routes.py) - 10 routes - - api_bp (api_routes.py) - 14 routes (with /api prefix) - - batch_bp (batch_routes.py) - 4 routes - - customer_bp (customer_routes.py) - 7 routes - - export_bp (export_routes.py) - 5 routes (with /export prefix) - - license_bp (license_routes.py) - 4 routes - - resource_bp (resource_routes.py) - 7 routes - - session_bp (session_routes.py) - 6 routes - -3. **Fixed route inconsistencies** - - Updated `/session/terminate/` to `/session/end/` in session_routes.py to match the original - -## Application Structure - -The application now follows a proper blueprint structure: -- `app.py` - Contains only Flask app initialization, configuration, and scheduler setup -- `routes/` - Contains all route blueprints organized by functionality -- All routes are properly organized and no duplicates exist - -## Next Steps - -1. Test the application to ensure all routes work correctly -2. Remove commented route code from app.py once verified working -3. Consider further refactoring of large blueprint files if needed - -## Backup - -A backup of the original app.py was created with timestamp before making changes. \ No newline at end of file diff --git a/v2_adminpanel/FEHLERSUCHE.md b/v2_adminpanel/FEHLERSUCHE.md deleted file mode 100644 index 4f4a5b3..0000000 --- a/v2_adminpanel/FEHLERSUCHE.md +++ /dev/null @@ -1,318 +0,0 @@ -# Fehlersuche - v2_adminpanel Refactoring - -## Aktueller Stand (18.06.2025 - 02:30 Uhr) -✅ **ALLE KRITISCHEN PROBLEME GELÖST** -- Resources Route funktioniert jetzt korrekt -- Customers-Licenses Route funktioniert jetzt korrekt -- Container startet ohne Fehler - -### Finale Fixes (18.06.2025 - 02:45 Uhr) - -#### Customers-Licenses Testdaten-Filter -- Problem: `/customers-licenses?show_test=false` zeigte trotzdem alle Kunden (auch Testdaten) -- Ursache: Die SQL-Query in `customers_licenses()` berücksichtigte den `show_test` Parameter nicht -- Lösung: - - `show_test` Parameter aus der URL auslesen - - WHERE-Klausel hinzugefügt: `WHERE (%s OR c.is_test = false)` - - `c.is_test` in SELECT und GROUP BY hinzugefügt - - `show_test` Parameter an Template weitergeben - - Standardverhalten: Nur Produktivdaten werden angezeigt (wenn show_test=false oder nicht gesetzt) - -### Bereits gelöste Probleme (18.06.2025 - 02:35 Uhr) - -#### Backups Route Fix -- Problem 1: 500 Error bei `/backups` - `url_for('admin.create_backup')` existiert nicht -- Lösung 1: - - `url_for('admin.create_backup')` → `url_for('admin.create_backup_route')` - - `url_for('admin.restore_backup', backup_id='')` → `/backup/restore/${backupId}` - - `url_for('admin.delete_backup', backup_id='')` → `/backup/delete/${backupId}` - -- Problem 2: "SyntaxError: Unexpected token '<'" beim Backup erstellen -- Ursache: Routes gaben HTML (redirect) statt JSON zurück -- Lösung 2: - - `create_backup_route()` und `restore_backup_route()` geben jetzt JSON zurück - - Entfernt: `return redirect(url_for('admin.backups'))` - - Hinzugefügt: `return jsonify({'success': True/False, 'message': '...'})` - -### Bereits gelöste Probleme (18.06.2025 - 02:30 Uhr) -1. **Customers-Licenses Template Fix**: - - Problem: `url_for('api.toggle_license', license_id='')` mit leerem String - - Lösung: Hardcodierte URL verwendet: `/api/license/${licenseId}/toggle` - -2. **Resources Route Fix**: - - Problem 1: `invalid literal for int() with base 10: ''` bei page Parameter - - Lösung 1: Try-except Block für sichere Konvertierung des page Parameters - - Problem 2: `url_for('resources.quarantine', resource_id='')` mit leerem String im Template - - Lösung 2: Hardcodierte URL verwendet: `/resources/quarantine/${resourceId}` - - Zusätzlich: Debug-Logging hinzugefügt für bessere Fehlerdiagnose - -### Wichtige Erkenntnisse: -- Flask's `url_for()` kann nicht mit leeren Parametern für Integer-Routen umgehen -- Bei JavaScript-generierten URLs ist es oft besser, hardcodierte URLs zu verwenden -- Container muss nach Template-Änderungen neu gestartet werden - -## Stand vom 17.06.2025 - 11:00 Uhr - -### Erfolgreiches Refactoring -- Die ursprüngliche 5000+ Zeilen große app.py wurde erfolgreich in Module aufgeteilt: - - 9 Blueprint-Module in `routes/` - - Separate Module für auth/, utils/, config.py, db.py, models.py - - Hauptdatei app.py nur noch 178 Zeilen - -### Funktionierende Teile -- ✅ Routing-System funktioniert (alle Routen sind registriert) -- ✅ Login-System funktioniert -- ✅ Einfache Test-Routen funktionieren (/simple-test) -- ✅ Blueprint-Registrierung funktioniert korrekt -- ✅ /test-db Route funktioniert nach Docker-Rebuild -- ✅ Kunden-Anzeige funktioniert mit Test-Daten-Filter -- ✅ Lizenzen-Anzeige funktioniert mit erweiterten Filtern -- ✅ Batch-Lizenzerstellung funktioniert -- ✅ Ressourcen-Pool funktioniert vollständig -- ✅ Ressourcen hinzufügen funktioniert - -### Gelöste Probleme - -#### 1. **Dict/Tuple Inkonsistenzen** ✅ GELÖST -**Problem**: Templates erwarteten Tuple-Zugriff (row[0], row[1]), aber models.py lieferte Dictionaries -**Lösung**: Alle betroffenen Templates wurden auf Dictionary-Zugriff umgestellt: -- customers.html: `customer[0]` → `customer.id`, `customer[1]` → `customer.name`, etc. -- customers_licenses.html: Komplett auf Dictionary-Zugriff umgestellt -- licenses.html, edit_license.html, sessions.html, audit_log.html, resources.html, backups.html: Alle konvertiert - -#### 2. **Fehlende /api/customers Route** ✅ GELÖST -**Problem**: Batch-Lizenzerstellung konnte keine Kunden laden (Select2 AJAX-Fehler) -**Lösung**: api_customers() Funktion zu api_routes.py hinzugefügt - -#### 3. **Doppelte api_customers Funktion** ✅ GELÖST -**Problem**: AssertionError beim Start - View function mapping is overwriting existing endpoint -**Lösung**: Doppelte Definition in api_routes.py entfernt (Zeilen 833-943) - -#### 4. **502 Bad Gateway Error** ✅ GELÖST -**Problem**: Admin-Panel war nicht erreichbar, nginx gab 502 zurück -**Ursache**: Container startete nicht wegen doppelter Route-Definition -**Lösung**: Doppelte api_customers Funktion entfernt, Container neu gebaut - -#### 5. **Test-Daten Filter** ✅ GELÖST -**Problem**: Test-Daten wurden immer angezeigt, Checkbox funktionierte nicht -**Lösung**: get_customers() in models.py unterstützt jetzt show_test Parameter - -## Debugging-Schritte - -### 1. Container komplett neu bauen -```bash -cd C:\Users\Administrator\Documents\GitHub\v2-Docker\v2 -docker-compose down -docker-compose build --no-cache -docker-compose up -d -``` - -### 2. Logs überprüfen -```bash -docker logs admin-panel --tail 100 -``` - -### 3. Test-Routen -- `/simple-test` - Sollte "Simple test works!" zeigen -- `/debug-routes` - Zeigt alle registrierten Routen -- `/test-db` - Testet Datenbankverbindung - -### 4. Login-Test -1. Gehe zu https://admin-panel-undso.z5m7q9dk3ah2v1plx6ju.com/ -2. Logge dich mit den Admin-Credentials ein -3. Versuche dann /customers-licenses aufzurufen - -## Code-Fixes bereits implementiert - -### 1. Datenbankverbindungen -- Alle kritischen Funktionen verwenden jetzt `conn = get_connection()` mit normalem Cursor -- Verhindert Dictionary/Tuple Konflikte - -### 2. Spaltennamen korrigiert -- `is_active` statt `active` für licenses Tabelle -- `is_active` statt `active` für sessions Tabelle -- `is_test` statt `is_test_license` -- Entfernt: phone, address, notes aus customers (existieren nicht) - -### 3. Blueprint-Referenzen -- Alle url_for() Aufrufe haben korrekte Blueprint-Präfixe -- z.B. `url_for('auth.login')` statt `url_for('login')` - -## Nächste Schritte - -1. **Container neu bauen** (siehe oben) -2. **Einloggen** und testen ob /customers-licenses funktioniert -3. **Falls weiterhin Fehler**: Docker Logs nach "CUSTOMERS-LICENSES ROUTE CALLED" durchsuchen -4. **Alternative**: Temporär auf die große app.py.backup zurückwechseln: - ```bash - cp app.py.backup app.py - docker-compose restart admin-panel - ``` - -## Bekannte funktionierende Routen (nach Login) -- `/` - Dashboard -- `/customers` - Kundenliste -- `/licenses` - Lizenzliste -- `/resources` - Ressourcen -- `/audit` - Audit Log -- `/sessions` - Sessions - -## Debug-Informationen in customer_routes.py -Die customers_licenses Funktion hat erweiterte Logging-Ausgaben: -- "=== CUSTOMERS-LICENSES ROUTE CALLED ===" -- "=== QUERY RETURNED X ROWS ===" -- Details über Datentypen der Ergebnisse - -Diese erscheinen in den Docker Logs und helfen bei der Fehlersuche. - -## Zusammenfassung der Fixes - -### Template-Konvertierungen (Dict statt Tuple) -Folgende Templates wurden von Tuple-Zugriff auf Dictionary-Zugriff umgestellt: -1. **customers.html**: customer[0] → customer.id, etc. -2. **customers_licenses.html**: Komplett umgestellt -3. **edit_customer.html**: customer[0] → customer.id, etc. -4. **licenses.html**: license[0] → license.id, etc. -5. **edit_license.html**: license[0] → license.id, etc. -6. **sessions.html**: session[0] → session.id, etc. -7. **audit_log.html**: log[0] → log.id, etc. -8. **resources.html**: resource[0] → resource.id, etc. -9. **backups.html**: backup[0] → backup.id, etc. - -### API-Fixes -1. **api_routes.py**: Fehlende /api/customers Route hinzugefügt -2. **api_routes.py**: Doppelte api_customers Funktion entfernt - -### Model-Fixes -1. **models.py**: get_customers() unterstützt jetzt show_test und search Parameter -2. **customer_routes.py**: customers() nutzt die neuen Parameter - -### Status -✅ **Alle bekannten Probleme wurden behoben** -✅ **Admin-Panel ist vollständig funktionsfähig** -✅ **Docker Container läuft stabil** - -## Weitere gelöste Probleme (17.06.2025 - 11:00 Uhr) - -### 1. **Test-Daten Checkbox funktioniert nicht** ✅ GELÖST -**Problem**: Die Checkbox zum Anzeigen von Test-Daten in Kunden- und Lizenzansicht funktionierte nicht -**Ursache**: Fehlende Blueprint-Präfixe in Template-URLs -**Lösung**: -- `customers.html`: Alle `url_for('customers')` → `url_for('customer.customers')` -- `licenses.html`: Alle `url_for('licenses')` → `url_for('license.licenses')` -- Formulare senden jetzt korrekt mit `show_test` Parameter - -### 2. **Lizenz-Filter erweitert** ✅ GELÖST -**Problem**: Filter für Test-/Live-Daten fehlte in Lizenzansicht -**Lösung**: `license_routes.py` erweitert mit: -- Typ-Filter: `full`, `test`, `test_data`, `live_data` -- Status-Filter: `active`, `expiring`, `expired`, `inactive` -- Suche über Lizenzschlüssel, Kundenname und E-Mail - -### 3. **Resource Pool Anzeige** ✅ GELÖST -**Problem**: Ressourcen-Pool Seite hatte fehlerhafte Links und Filter funktionierten nicht -**Lösung**: -- `resources.html`: Form-Action korrigiert zu `url_for('resources.resources')` -- JavaScript `toggleTestResources()` arbeitet jetzt mit URL-Parametern -- Alle Sortier- und Paginierungs-Links korrigiert - -### 4. **Ressourcen hinzufügen fehlte** ✅ GELÖST -**Problem**: Route `/resources/add` existierte nicht -**Lösung**: Komplette `add_resources()` Funktion in `resource_routes.py` implementiert: -- Validierung für Domains, IPv4-Adressen und Telefonnummern -- Duplikat-Prüfung -- Bulk-Import mit detailliertem Feedback -- Test/Produktion Unterscheidung - -### 5. **Navigation-Links** ✅ GELÖST -**Problem**: Sidebar-Links für Ressourcen verwendeten hardcodierte URLs -**Lösung**: `base.html` aktualisiert: -- Resource Pool Link: `href="{{ url_for('resources.resources') }}"` -- Add Resources Link: `href="{{ url_for('resources.add_resources') }}"` -- Active-Status Prüfung korrigiert für Blueprint-Endpunkte - -## Routing-Analyse (17.06.2025 - 11:30 Uhr) - -### Identifizierte Routing-Probleme - -Nach systematischer Analyse wurden folgende Routing-Probleme gefunden: - -#### 1. **Fehlende Blueprint-Präfixe** ⚠️ OFFEN -Viele `url_for()` Aufrufe fehlen Blueprint-Präfixe. Dies verursacht 500-Fehler: - -**Betroffene Templates:** -- `profile.html`: 3 fehlerhafte Aufrufe (`change_password`, `disable_2fa`, `setup_2fa`) -- `setup_2fa.html`: 2 fehlerhafte Aufrufe (`profile`, `enable_2fa`) -- `backup_codes.html`: 1 fehlerhafter Aufruf (`profile`) -- `resource_history.html`: 2 fehlerhafte Aufrufe (`resources`, `edit_license`) -- `resource_metrics.html`: 2 fehlerhafte Aufrufe (`resources`, `resources_report`) -- `resource_report.html`: 2 fehlerhafte Aufrufe -- `sessions.html`: Mehrere fehlerhafte Aufrufe -- `audit_log.html`: Mehrere fehlerhafte Aufrufe - -#### 2. **Hardcodierte URLs** ⚠️ OFFEN -Über 50 hardcodierte URLs gefunden, die mit `url_for()` ersetzt werden sollten: - -**Hauptprobleme in `base.html`:** -- `href="/"` → `href="{{ url_for('admin.dashboard') }}"` -- `href="/profile"` → `href="{{ url_for('auth.profile') }}"` -- `href="/logout"` → `href="{{ url_for('auth.logout') }}"` -- `href="/customers-licenses"` → `href="{{ url_for('customer.customers_licenses') }}"` -- `href="/customer/create"` → `href="{{ url_for('customer.create_customer') }}"` -- `href="/create"` → `href="{{ url_for('license.create_license') }}"` -- `href="/batch"` → `href="{{ url_for('batch.batch_create') }}"` -- `href="/audit"` → `href="{{ url_for('admin.audit_log') }}"` -- `href="/sessions"` → `href="{{ url_for('session.sessions') }}"` -- `href="/backups"` → `href="{{ url_for('admin.backups') }}"` - -#### 3. **Doppelte Route-Definitionen** ✅ GELÖST -- Entfernt: Doppelte `add_resource` Funktion in `resource_routes.py` - -#### 4. **Route-Namenskonsistenz** ⚠️ OFFEN -- `resource_report` vs `resources_report` - inkonsistente Benennung - -### Prioritäten für Fixes - -1. **KRITISCH**: Fehlende Blueprint-Präfixe (verursachen 500-Fehler) -2. **HOCH**: Hardcodierte URLs in Navigation (`base.html`) -3. **MITTEL**: Andere hardcodierte URLs -4. **NIEDRIG**: Namenskonsistenz - -### Vollständiger Report -Ein detaillierter Report wurde erstellt: `ROUTING_ISSUES_REPORT.md` - -## Aktuelle Probleme (18.06.2025 - 01:30 Uhr) - -### 1. **Resources Route funktioniert nicht** ✅ GELÖST (18.06.2025 - 02:00 Uhr) -**Problem**: `/resources` Route leitete auf Dashboard um mit Fehlermeldung "Fehler beim Laden der Ressourcen!" -**Fehlermeldungen im Log**: -1. Ursprünglich: `FEHLER: Spalte l.customer_name existiert nicht` -2. Nach Fix: `'dict object' has no attribute 'total'` - -**Gelöst durch**: -1. Stats Dictionary korrekt initialisiert mit allen erforderlichen Feldern inkl. `available_percent` -2. Fehlende Template-Variablen hinzugefügt: `total`, `page`, `total_pages`, `sort_by`, `sort_order`, `recent_activities`, `datetime` -3. Template-Variable `search_query` → `search` korrigiert -4. Route-Namen korrigiert: `quarantine_resource` → `quarantine`, `release_resources` → `release` -5. Export-Route korrigiert: `resource_report` → `resources_report` - -### 2. **URL-Generierungsfehler** ✅ GELÖST -**Problem**: Mehrere `url_for()` Aufrufe mit falschen Endpunkt-Namen -**Gelöste Fehler**: -- `api.generate_license_key` → `api.api_generate_key` -- `api.customers` → `api.api_customers` -- `export.customers` → `export.export_customers` -- `export.licenses` → `export.export_licenses` -- `url_for()` mit leeren Parametern durch hardcodierte URLs ersetzt - -### 3. **Customers-Licenses Route** ✅ GELÖST (18.06.2025 - 02:00 Uhr) -**Problem**: `/customers-licenses` Route leitete auf Dashboard um -**Fehlermeldung im Log**: `ValueError: invalid literal for int() with base 10: ''` -**Ursache**: Template versuchte Server-seitiges Rendering von Daten, die per AJAX geladen werden sollten - -**Gelöst durch**: -1. Entfernt: Server-seitiges Rendering von `selected_customer` und `licenses` im Template -2. Template zeigt jetzt nur "Wählen Sie einen Kunden aus" bis AJAX-Daten geladen sind -3. Korrigiert: `selected_customer_id` Variable entfernt -4. Export-Links funktionieren jetzt ohne `customer_id` Parameter -5. API-Endpunkt korrekt referenziert mit `url_for('customers.api_customer_licenses')` \ No newline at end of file diff --git a/v2_adminpanel/MIGRATION_2FA.md b/v2_adminpanel/MIGRATION_2FA.md deleted file mode 100644 index d60855b..0000000 --- a/v2_adminpanel/MIGRATION_2FA.md +++ /dev/null @@ -1,43 +0,0 @@ -# Migration zu Passwort-Änderung und 2FA - -## Übersicht -Das Admin Panel unterstützt jetzt Passwort-Änderungen und Zwei-Faktor-Authentifizierung (2FA). Um diese Features zu nutzen, müssen bestehende Benutzer migriert werden. - -## Migration durchführen - -1. **Container neu bauen** (für neue Dependencies): - ```bash - docker-compose down - docker-compose build adminpanel - docker-compose up -d - ``` - -2. **Migration ausführen**: - ```bash - docker exec -it v2_adminpanel python migrate_users.py - ``` - - Dies erstellt Datenbankeinträge für die in der .env konfigurierten Admin-Benutzer. - -## Nach der Migration - -### Passwort ändern -1. Einloggen mit bisherigem Passwort -2. Klick auf "👤 Profil" in der Navigation -3. Neues Passwort eingeben (min. 8 Zeichen) - -### 2FA aktivieren -1. Im Profil auf "2FA einrichten" klicken -2. QR-Code mit Google Authenticator oder Authy scannen -3. 6-stelligen Code eingeben -4. Backup-Codes sicher aufbewahren! - -## Wichtige Hinweise -- Backup-Codes unbedingt speichern (Drucker, USB-Stick, etc.) -- Jeder Backup-Code kann nur einmal verwendet werden -- Bei Verlust des 2FA-Geräts können nur Backup-Codes helfen - -## Rückwärtskompatibilität -- Benutzer aus .env funktionieren weiterhin -- Diese haben aber keinen Zugriff auf Profil-Features -- Migration ist erforderlich für neue Features \ No newline at end of file diff --git a/v2_adminpanel/MIGRATION_DISCREPANCIES.md b/v2_adminpanel/MIGRATION_DISCREPANCIES.md deleted file mode 100644 index 7aa7632..0000000 --- a/v2_adminpanel/MIGRATION_DISCREPANCIES.md +++ /dev/null @@ -1,156 +0,0 @@ -# Migration Discrepancies - Backup vs Current Blueprint Structure - -## 1. Missing Routes - -### Authentication/Profile Routes (Not in any blueprint) -- `/profile` - User profile page -- `/profile/change-password` - Change password endpoint -- `/profile/setup-2fa` - Setup 2FA page -- `/profile/enable-2fa` - Enable 2FA endpoint -- `/profile/disable-2fa` - Disable 2FA endpoint -- `/heartbeat` - Session heartbeat endpoint - -### Customer API Routes (Missing from api_routes.py) -- `/api/customer//licenses` - Get licenses for a customer -- `/api/customer//quick-stats` - Get quick stats for a customer - -### Resource Routes (Missing from resource_routes.py) -- `/resources` - Main resources page -- `/resources/add` - Add new resources page -- `/resources/quarantine/` - Quarantine a resource -- `/resources/release` - Release resources from quarantine -- `/resources/history/` - View resource history -- `/resources/metrics` - Resource metrics page -- `/resources/report` - Resource report page - -### Main Dashboard Route (Missing) -- `/` - Main dashboard (currently in backup shows dashboard with stats) - -## 2. Database Column Discrepancies - -### Column Name Differences -- **created_by** - Used in backup_history table but not consistently referenced -- **is_test_license** vs **is_test** - The database uses `is_test` but some code might reference `is_test_license` - -### Session Table Aliases -The sessions table has multiple column aliases that need to be handled: -- `login_time` (alias for `started_at`) -- `last_activity` (alias for `last_heartbeat`) -- `logout_time` (alias for `ended_at`) -- `active` (alias for `is_active`) - -## 3. Template Name Mismatches - -### Templates Referenced in Backup -- `login.html` - Login page -- `verify_2fa.html` - 2FA verification -- `profile.html` - User profile -- `setup_2fa.html` - 2FA setup -- `backup_codes.html` - 2FA backup codes -- `dashboard.html` - Main dashboard -- `index.html` - Create license form -- `batch_result.html` - Batch operation results -- `batch_form.html` - Batch form -- `edit_license.html` - Edit license -- `edit_customer.html` - Edit customer -- `create_customer.html` - Create customer -- `customers_licenses.html` - Customer-license overview -- `sessions.html` - Sessions list -- `audit_log.html` - Audit log -- `backups.html` - Backup management -- `blocked_ips.html` - Blocked IPs -- `resources.html` - Resources list -- `add_resources.html` - Add resources form -- `resource_history.html` - Resource history -- `resource_metrics.html` - Resource metrics -- `resource_report.html` - Resource report - -## 4. URL_FOR References That Need Blueprint Prefixes - -### In Templates and Redirects -- `url_for('login')` → `url_for('auth.login')` -- `url_for('logout')` → `url_for('auth.logout')` -- `url_for('verify_2fa')` → `url_for('auth.verify_2fa')` -- `url_for('profile')` → `url_for('auth.profile')` (needs implementation) -- `url_for('index')` → `url_for('main.index')` or appropriate blueprint -- `url_for('blocked_ips')` → `url_for('admin.blocked_ips')` -- `url_for('audit_log')` → `url_for('admin.audit_log')` -- `url_for('backups')` → `url_for('admin.backups')` - -## 5. Missing Functions/Middleware - -### Authentication Decorators -- `@login_required` decorator implementation needs to be verified -- `@require_2fa` decorator (if used) - -### Helper Functions -- `get_connection()` - Database connection helper -- `log_audit()` - Audit logging function -- `create_backup()` - Backup creation function -- Rate limiting functions for login attempts - -### Session Management -- Session timeout handling -- Heartbeat mechanism for active sessions - -## 6. API Endpoint Inconsistencies - -### URL Prefix Issues -- API routes in backup don't use `/api` prefix consistently -- Some use `/api/...` while others are at root level - -### Missing API Endpoints -- `/api/generate-license-key` - Generate license key -- `/api/global-search` - Global search functionality - -## 7. Export Routes Organization - -### Current vs Expected -- Export routes might need different URL structure -- Check if all export types are covered: - - `/export/licenses` - - `/export/audit` - - `/export/customers` - - `/export/sessions` - - `/export/resources` - -## 8. Special Configurations - -### Missing Configurations -- TOTP/2FA configuration -- Backup encryption settings -- Rate limiting configuration -- Session timeout settings - -### Environment Variables -- Check if all required environment variables are properly loaded -- Database connection parameters -- Secret keys and encryption keys - -## 9. JavaScript/AJAX Endpoints - -### API calls that might be broken -- Device management endpoints -- Quick edit functionality -- Bulk operations -- Resource allocation checks - -## 10. Permission/Access Control - -### Missing or Incorrect Access Control -- All routes need `@login_required` decorator -- Some routes might need additional permission checks -- API routes need proper authentication - -## Action Items - -1. **Implement missing profile/auth routes** in auth_routes.py -2. **Add missing customer API routes** to api_routes.py -3. **Create complete resource management blueprint** with all routes -4. **Fix main dashboard route** - decide which blueprint should handle "/" -5. **Update all url_for() calls** in templates to use blueprint prefixes -6. **Verify database column names** are consistent throughout -7. **Check template names** match between routes and actual files -8. **Implement heartbeat mechanism** for session management -9. **Add missing helper functions** to appropriate modules -10. **Test all export routes** work correctly with new structure \ No newline at end of file diff --git a/v2_adminpanel/ROUTING_ISSUES_REPORT.md b/v2_adminpanel/ROUTING_ISSUES_REPORT.md deleted file mode 100644 index 98c4b07..0000000 --- a/v2_adminpanel/ROUTING_ISSUES_REPORT.md +++ /dev/null @@ -1,118 +0,0 @@ -# V2 Admin Panel - Routing Issues Report - -Generated: 2025-06-17 - -## Summary of Findings - -After systematically analyzing the v2_adminpanel application, I've identified several routing issues that need to be addressed: - -### 1. Missing Blueprint Prefixes in url_for() Calls - -The following templates have `url_for()` calls that are missing the required blueprint prefix: - -#### In `profile.html`: -- `url_for('change_password')` → Should be `url_for('auth.change_password')` -- `url_for('disable_2fa')` → Should be `url_for('auth.disable_2fa')` -- `url_for('setup_2fa')` → Should be `url_for('auth.setup_2fa')` - -#### In `setup_2fa.html`: -- `url_for('profile')` → Should be `url_for('auth.profile')` -- `url_for('enable_2fa')` → Should be `url_for('auth.enable_2fa')` - -#### In `backup_codes.html`: -- `url_for('profile')` → Should be `url_for('auth.profile')` - -#### In `resource_history.html`: -- `url_for('resources')` → Should be `url_for('resources.resources')` -- `url_for('edit_license', license_id=...)` → Should be `url_for('licenses.edit_license', license_id=...)` - -#### In `resource_metrics.html`: -- `url_for('resources')` → Should be `url_for('resources.resources')` -- `url_for('resources_report')` → Should be `url_for('resources.resource_report')` - -#### In `resource_report.html`: -- `url_for('resources')` → Should be `url_for('resources.resources')` -- `url_for('resources_report')` → Should be `url_for('resources.resource_report')` - -#### In `sessions.html`: -- `url_for('sessions', ...)` → Should be `url_for('sessions.sessions', ...)` - -#### In `audit_log.html`: -- `url_for('audit_log', ...)` → Should be `url_for('admin.audit_log', ...)` - -#### In `licenses.html`: -- `url_for('licenses', ...)` → Should be `url_for('licenses.licenses', ...)` - -#### In `customers.html`: -- `url_for('customers', ...)` → Should be `url_for('customers.customers', ...)` - -#### In `resources.html`: -- Several instances of incorrect references: - - `url_for('customers.customers_licenses', ...)` → Should be `url_for('customers.customers_licenses', ...)` - - `url_for('licenses.edit_license', ...)` → Correct - - `url_for('resource_history', ...)` → Should be `url_for('resources.resource_history', ...)` - - `url_for('edit_license', ...)` → Should be `url_for('licenses.edit_license', ...)` - - `url_for('customers_licenses', ...)` → Should be `url_for('customers.customers_licenses', ...)` - -### 2. Hardcoded URLs That Need Replacement - -Many templates contain hardcoded URLs that should be replaced with `url_for()` calls: - -#### In `base.html`: -- `href="/"` → Should be `href="{{ url_for('admin.index') }}"` -- `href="/profile"` → Should be `href="{{ url_for('auth.profile') }}"` -- `href="/logout"` → Should be `href="{{ url_for('auth.logout') }}"` -- `href="/customers-licenses"` → Should be `href="{{ url_for('customers.customers_licenses') }}"` -- `href="/customer/create"` → Should be `href="{{ url_for('customers.create_customer') }}"` -- `href="/create"` → Should be `href="{{ url_for('licenses.create_license') }}"` -- `href="/batch"` → Should be `href="{{ url_for('batch.batch_licenses') }}"` -- `href="/audit"` → Should be `href="{{ url_for('admin.audit_log') }}"` -- `href="/sessions"` → Should be `href="{{ url_for('sessions.sessions') }}"` -- `href="/backups"` → Should be `href="{{ url_for('admin.backups') }}"` -- `href="/security/blocked-ips"` → Should be `href="{{ url_for('admin.blocked_ips') }}"` - -#### In `customers_licenses.html` and `customers_licenses_old.html`: -- Multiple hardcoded URLs for editing, creating, and exporting that need to be replaced with proper `url_for()` calls - -#### In `edit_license.html`, `create_customer.html`, `index.html`: -- `href="/customers-licenses"` → Should use `url_for()` - -#### In `dashboard.html`: -- Multiple hardcoded URLs that should use `url_for()` - -#### In error pages (`404.html`, `500.html`): -- `href="/"` → Should be `href="{{ url_for('admin.index') }}"` - -### 3. Blueprint Configuration - -Current blueprint configuration: -- `export_bp` has `url_prefix='/export'` -- `api_bp` has `url_prefix='/api'` -- All other blueprints have no url_prefix - -### 4. Route Naming Inconsistencies - -Some routes have inconsistent naming between the route definition and the function name: -- Route `/resources/report` has function name `resource_report` (note the singular vs plural) -- This causes confusion with `url_for()` calls - -### 5. Duplicate Route Risk Areas - -While no exact duplicates were found, there are potential conflicts: -- Both `admin_bp` and `customer_bp` might handle customer-related routes -- API routes in `api_bp` overlap with functionality in other blueprints - -## Recommendations - -1. **Fix all `url_for()` calls** to include the correct blueprint prefix -2. **Replace all hardcoded URLs** with `url_for()` calls -3. **Standardize route naming** to match function names -4. **Add url_prefix to blueprints** where appropriate to avoid conflicts -5. **Create a route mapping document** for developers to reference - -## Priority Actions - -1. **High Priority**: Fix missing blueprint prefixes in `url_for()` calls - these will cause runtime errors -2. **High Priority**: Replace hardcoded URLs in navigation (base.html) - affects site-wide navigation -3. **Medium Priority**: Fix other hardcoded URLs in individual templates -4. **Low Priority**: Refactor route naming for consistency \ No newline at end of file diff --git a/v2_adminpanel/TEMPLATE_FIXES_NEEDED.md b/v2_adminpanel/TEMPLATE_FIXES_NEEDED.md deleted file mode 100644 index 74d75da..0000000 --- a/v2_adminpanel/TEMPLATE_FIXES_NEEDED.md +++ /dev/null @@ -1,73 +0,0 @@ -# Template Fixes Needed - Tuple to Dictionary Migration - -## Problem -Die models.py Funktionen geben Dictionaries zurück, aber viele Templates erwarten noch Tupel mit numerischen Indizes. - -## Betroffene Templates und Routes: - -### 1. ✅ FIXED: customers.html -- Route: `/customers` -- Funktion: `get_customers()` -- Status: Bereits gefixt - -### 2. ✅ FIXED: customers_licenses.html -- Route: `/customers-licenses` -- Status: Teilweise gefixt (customers list) -- TODO: selected_customer wird per JavaScript geladen - -### 3. ✅ FIXED: edit_customer.html -- Route: `/customer/edit/` -- Funktion: `get_customer_by_id()` -- Status: Bereits gefixt - -### 4. ❌ licenses.html -- Route: `/licenses` -- Funktion: `get_licenses()` -- Problem: Nutzt license[0], license[1], etc. -- Lösung: Ändern zu license.id, license.license_key, etc. - -### 5. ❌ edit_license.html -- Route: `/license/edit/` -- Funktion: `get_license_by_id()` -- Problem: Nutzt license[x] Syntax - -### 6. ❌ sessions.html -- Route: `/sessions` -- Funktion: `get_active_sessions()` -- Problem: Nutzt session[x] Syntax - -### 7. ❌ audit_log.html -- Route: `/audit` -- Problem: Nutzt entry[x] Syntax - -### 8. ❌ resources.html -- Route: `/resources` -- Problem: Nutzt resource[x] Syntax - -### 9. ❌ backups.html -- Route: `/backups` -- Problem: Nutzt backup[x] Syntax - -### 10. ✅ FIXED: batch_form.html -- Route: `/batch` -- Problem: Fehlende /api/customers Route -- Status: API Route hinzugefügt - -### 11. ❌ dashboard.html (index.html) -- Route: `/` -- Problem: Möglicherweise nutzt auch numerische Indizes - -## Batch License Problem -- batch_create.html existiert nicht, stattdessen batch_form.html -- Template mismatch in batch_routes.py Zeile 118 - -## Empfohlene Lösung -1. Alle Templates systematisch durchgehen und von Tupel auf Dictionary-Zugriff umstellen -2. Alternativ: Models.py ändern um Tupel statt Dictionaries zurückzugeben (nicht empfohlen) -3. Batch template name fix: batch_create.html → batch_form.html - -## Quick Fix für Batch -Zeile 118 in batch_routes.py ändern: -```python -return render_template("batch_form.html", customers=customers) -``` \ No newline at end of file diff --git a/v2_adminpanel/__pycache__/app.cpython-312.pyc b/v2_adminpanel/__pycache__/app.cpython-312.pyc index 446fde5..37a2c18 100644 Binary files a/v2_adminpanel/__pycache__/app.cpython-312.pyc and b/v2_adminpanel/__pycache__/app.cpython-312.pyc differ diff --git a/v2_adminpanel/__pycache__/app_no_duplicates.cpython-312.pyc b/v2_adminpanel/__pycache__/app_no_duplicates.cpython-312.pyc deleted file mode 100644 index d47d7f3..0000000 Binary files a/v2_adminpanel/__pycache__/app_no_duplicates.cpython-312.pyc and /dev/null differ diff --git a/v2_adminpanel/__pycache__/app_refactored.cpython-312.pyc b/v2_adminpanel/__pycache__/app_refactored.cpython-312.pyc deleted file mode 100644 index 9c9153c..0000000 Binary files a/v2_adminpanel/__pycache__/app_refactored.cpython-312.pyc and /dev/null differ diff --git a/v2_adminpanel/__pycache__/config.cpython-312.pyc b/v2_adminpanel/__pycache__/config.cpython-312.pyc deleted file mode 100644 index 09aafeb..0000000 Binary files a/v2_adminpanel/__pycache__/config.cpython-312.pyc and /dev/null differ diff --git a/v2_adminpanel/app.py.backup b/v2_adminpanel/app.py.backup deleted file mode 100644 index 96c85f1..0000000 --- a/v2_adminpanel/app.py.backup +++ /dev/null @@ -1,5032 +0,0 @@ -import os -import psycopg2 -from psycopg2.extras import Json -from flask import Flask, render_template, request, redirect, session, url_for, send_file, jsonify, flash -from flask_session import Session -from functools import wraps -from dotenv import load_dotenv -import pandas as pd -from datetime import datetime, timedelta -from zoneinfo import ZoneInfo -import io -import subprocess -import gzip -from cryptography.fernet import Fernet -from pathlib import Path -import time -from apscheduler.schedulers.background import BackgroundScheduler -import logging -import random -import hashlib -import requests -import secrets -import string -import re -import bcrypt -import pyotp -import qrcode -from io import BytesIO -import base64 -import json -from werkzeug.middleware.proxy_fix import ProxyFix -from openpyxl.utils import get_column_letter - -load_dotenv() - -app = Flask(__name__) -app.config['SECRET_KEY'] = os.urandom(24) -app.config['SESSION_TYPE'] = 'filesystem' -app.config['JSON_AS_ASCII'] = False # JSON-Ausgabe mit UTF-8 -app.config['JSONIFY_MIMETYPE'] = 'application/json; charset=utf-8' -app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=5) # 5 Minuten Session-Timeout -app.config['SESSION_COOKIE_HTTPONLY'] = True -app.config['SESSION_COOKIE_SECURE'] = False # Wird auf True gesetzt wenn HTTPS (intern läuft HTTP) -app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' -app.config['SESSION_COOKIE_NAME'] = 'admin_session' -# WICHTIG: Session-Cookie soll auch nach 5 Minuten ablaufen -app.config['SESSION_REFRESH_EACH_REQUEST'] = False -Session(app) - -# ProxyFix für korrekte IP-Adressen hinter Nginx -app.wsgi_app = ProxyFix( - app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 -) - -# Backup-Konfiguration -BACKUP_DIR = Path("/app/backups") -BACKUP_DIR.mkdir(exist_ok=True) - -# Rate-Limiting Konfiguration -FAIL_MESSAGES = [ - "NOPE!", - "ACCESS DENIED, TRY HARDER", - "WRONG! 🚫", - "COMPUTER SAYS NO", - "YOU FAILED" -] - -MAX_LOGIN_ATTEMPTS = 5 -BLOCK_DURATION_HOURS = 24 -CAPTCHA_AFTER_ATTEMPTS = 2 - -# Scheduler für automatische Backups -scheduler = BackgroundScheduler() -scheduler.start() - -# Logging konfigurieren -logging.basicConfig(level=logging.INFO) - - -# Login decorator -def login_required(f): - @wraps(f) - def decorated_function(*args, **kwargs): - if 'logged_in' not in session: - return redirect(url_for('login')) - - # Prüfe ob Session abgelaufen ist - if 'last_activity' in session: - last_activity = datetime.fromisoformat(session['last_activity']) - time_since_activity = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) - last_activity - - # Debug-Logging - app.logger.info(f"Session check for {session.get('username', 'unknown')}: " - f"Last activity: {last_activity}, " - f"Time since: {time_since_activity.total_seconds()} seconds") - - if time_since_activity > timedelta(minutes=5): - # Session abgelaufen - Logout - username = session.get('username', 'unbekannt') - app.logger.info(f"Session timeout for user {username} - auto logout") - # Audit-Log für automatischen Logout (vor session.clear()!) - try: - log_audit('AUTO_LOGOUT', 'session', additional_info={'reason': 'Session timeout (5 minutes)', 'username': username}) - except: - pass - session.clear() - flash('Ihre Sitzung ist abgelaufen. Bitte melden Sie sich erneut an.', 'warning') - return redirect(url_for('login')) - - # Aktivität NICHT automatisch aktualisieren - # Nur bei expliziten Benutzeraktionen (wird vom Heartbeat gemacht) - return f(*args, **kwargs) - return decorated_function - -# DB-Verbindung mit UTF-8 Encoding -def get_connection(): - conn = psycopg2.connect( - host=os.getenv("POSTGRES_HOST", "postgres"), - port=os.getenv("POSTGRES_PORT", "5432"), - dbname=os.getenv("POSTGRES_DB"), - user=os.getenv("POSTGRES_USER"), - password=os.getenv("POSTGRES_PASSWORD"), - options='-c client_encoding=UTF8' - ) - conn.set_client_encoding('UTF8') - return conn - -# User Authentication Helper Functions -def hash_password(password): - """Hash a password using bcrypt""" - return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') - -def verify_password(password, hashed): - """Verify a password against its hash""" - return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8')) - -def get_user_by_username(username): - """Get user from database by username""" - conn = get_connection() - cur = conn.cursor() - try: - cur.execute(""" - SELECT id, username, password_hash, email, totp_secret, totp_enabled, - backup_codes, last_password_change, failed_2fa_attempts - FROM users WHERE username = %s - """, (username,)) - user = cur.fetchone() - if user: - return { - 'id': user[0], - 'username': user[1], - 'password_hash': user[2], - 'email': user[3], - 'totp_secret': user[4], - 'totp_enabled': user[5], - 'backup_codes': user[6], - 'last_password_change': user[7], - 'failed_2fa_attempts': user[8] - } - return None - finally: - cur.close() - conn.close() - -def generate_totp_secret(): - """Generate a new TOTP secret""" - return pyotp.random_base32() - -def generate_qr_code(username, totp_secret): - """Generate QR code for TOTP setup""" - totp_uri = pyotp.totp.TOTP(totp_secret).provisioning_uri( - name=username, - issuer_name='V2 Admin Panel' - ) - - qr = qrcode.QRCode(version=1, box_size=10, border=5) - qr.add_data(totp_uri) - qr.make(fit=True) - - img = qr.make_image(fill_color="black", back_color="white") - buf = BytesIO() - img.save(buf, format='PNG') - buf.seek(0) - - return base64.b64encode(buf.getvalue()).decode() - -def verify_totp(totp_secret, token): - """Verify a TOTP token""" - totp = pyotp.TOTP(totp_secret) - return totp.verify(token, valid_window=1) - -def generate_backup_codes(count=8): - """Generate backup codes for 2FA recovery""" - codes = [] - for _ in range(count): - code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8)) - codes.append(code) - return codes - -def hash_backup_code(code): - """Hash a backup code for storage""" - return hashlib.sha256(code.encode()).hexdigest() - -def verify_backup_code(code, hashed_codes): - """Verify a backup code against stored hashes""" - code_hash = hashlib.sha256(code.encode()).hexdigest() - return code_hash in hashed_codes - -# Audit-Log-Funktion -def log_audit(action, entity_type, entity_id=None, old_values=None, new_values=None, additional_info=None): - """Protokolliert Änderungen im Audit-Log""" - conn = get_connection() - cur = conn.cursor() - - try: - username = session.get('username', 'system') - ip_address = get_client_ip() if request else None - user_agent = request.headers.get('User-Agent') if request else None - - # Debug logging - app.logger.info(f"Audit log - IP address captured: {ip_address}, Action: {action}, User: {username}") - - # Konvertiere Dictionaries zu JSONB - old_json = Json(old_values) if old_values else None - new_json = Json(new_values) if new_values else None - - cur.execute(""" - INSERT INTO audit_log - (username, action, entity_type, entity_id, old_values, new_values, - ip_address, user_agent, additional_info) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) - """, (username, action, entity_type, entity_id, old_json, new_json, - ip_address, user_agent, additional_info)) - - conn.commit() - except Exception as e: - print(f"Audit log error: {e}") - conn.rollback() - finally: - cur.close() - conn.close() - -# Verschlüsselungs-Funktionen -def get_or_create_encryption_key(): - """Holt oder erstellt einen Verschlüsselungsschlüssel""" - key_file = BACKUP_DIR / ".backup_key" - - # Versuche Key aus Umgebungsvariable zu lesen - env_key = os.getenv("BACKUP_ENCRYPTION_KEY") - if env_key: - try: - # Validiere den Key - Fernet(env_key.encode()) - return env_key.encode() - except: - pass - - # Wenn kein gültiger Key in ENV, prüfe Datei - if key_file.exists(): - return key_file.read_bytes() - - # Erstelle neuen Key - key = Fernet.generate_key() - key_file.write_bytes(key) - logging.info("Neuer Backup-Verschlüsselungsschlüssel erstellt") - return key - -# Backup-Funktionen -def create_backup(backup_type="manual", created_by=None): - """Erstellt ein verschlüsseltes Backup der Datenbank""" - start_time = time.time() - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S") - filename = f"backup_v2docker_{timestamp}_encrypted.sql.gz.enc" - filepath = BACKUP_DIR / filename - - conn = get_connection() - cur = conn.cursor() - - # Backup-Eintrag erstellen - cur.execute(""" - INSERT INTO backup_history - (filename, filepath, backup_type, status, created_by, is_encrypted) - VALUES (%s, %s, %s, %s, %s, %s) - RETURNING id - """, (filename, str(filepath), backup_type, 'in_progress', - created_by or 'system', True)) - backup_id = cur.fetchone()[0] - conn.commit() - - try: - # PostgreSQL Dump erstellen - dump_command = [ - 'pg_dump', - '-h', os.getenv("POSTGRES_HOST", "postgres"), - '-p', os.getenv("POSTGRES_PORT", "5432"), - '-U', os.getenv("POSTGRES_USER"), - '-d', os.getenv("POSTGRES_DB"), - '--no-password', - '--verbose' - ] - - # PGPASSWORD setzen - env = os.environ.copy() - env['PGPASSWORD'] = os.getenv("POSTGRES_PASSWORD") - - # Dump ausführen - result = subprocess.run(dump_command, capture_output=True, text=True, env=env) - - if result.returncode != 0: - raise Exception(f"pg_dump failed: {result.stderr}") - - dump_data = result.stdout.encode('utf-8') - - # Komprimieren - compressed_data = gzip.compress(dump_data) - - # Verschlüsseln - key = get_or_create_encryption_key() - f = Fernet(key) - encrypted_data = f.encrypt(compressed_data) - - # Speichern - filepath.write_bytes(encrypted_data) - - # Statistiken sammeln - cur.execute("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public'") - tables_count = cur.fetchone()[0] - - cur.execute(""" - SELECT SUM(n_live_tup) - FROM pg_stat_user_tables - """) - records_count = cur.fetchone()[0] or 0 - - duration = time.time() - start_time - filesize = filepath.stat().st_size - - # Backup-Eintrag aktualisieren - cur.execute(""" - UPDATE backup_history - SET status = %s, filesize = %s, tables_count = %s, - records_count = %s, duration_seconds = %s - WHERE id = %s - """, ('success', filesize, tables_count, records_count, duration, backup_id)) - - conn.commit() - - # Audit-Log - log_audit('BACKUP', 'database', backup_id, - additional_info=f"Backup erstellt: {filename} ({filesize} bytes)") - - # E-Mail-Benachrichtigung (wenn konfiguriert) - send_backup_notification(True, filename, filesize, duration) - - logging.info(f"Backup erfolgreich erstellt: {filename}") - return True, filename - - except Exception as e: - # Fehler protokollieren - cur.execute(""" - UPDATE backup_history - SET status = %s, error_message = %s, duration_seconds = %s - WHERE id = %s - """, ('failed', str(e), time.time() - start_time, backup_id)) - conn.commit() - - logging.error(f"Backup fehlgeschlagen: {e}") - send_backup_notification(False, filename, error=str(e)) - - return False, str(e) - - finally: - cur.close() - conn.close() - -def restore_backup(backup_id, encryption_key=None): - """Stellt ein Backup wieder her""" - conn = get_connection() - cur = conn.cursor() - - try: - # Backup-Info abrufen - cur.execute(""" - SELECT filename, filepath, is_encrypted - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - if not backup_info: - raise Exception("Backup nicht gefunden") - - filename, filepath, is_encrypted = backup_info - filepath = Path(filepath) - - if not filepath.exists(): - raise Exception("Backup-Datei nicht gefunden") - - # Datei lesen - encrypted_data = filepath.read_bytes() - - # Entschlüsseln - if is_encrypted: - key = encryption_key.encode() if encryption_key else get_or_create_encryption_key() - try: - f = Fernet(key) - compressed_data = f.decrypt(encrypted_data) - except: - raise Exception("Entschlüsselung fehlgeschlagen. Falsches Passwort?") - else: - compressed_data = encrypted_data - - # Dekomprimieren - dump_data = gzip.decompress(compressed_data) - sql_commands = dump_data.decode('utf-8') - - # Bestehende Verbindungen schließen - cur.close() - conn.close() - - # Datenbank wiederherstellen - restore_command = [ - 'psql', - '-h', os.getenv("POSTGRES_HOST", "postgres"), - '-p', os.getenv("POSTGRES_PORT", "5432"), - '-U', os.getenv("POSTGRES_USER"), - '-d', os.getenv("POSTGRES_DB"), - '--no-password' - ] - - env = os.environ.copy() - env['PGPASSWORD'] = os.getenv("POSTGRES_PASSWORD") - - result = subprocess.run(restore_command, input=sql_commands, - capture_output=True, text=True, env=env) - - if result.returncode != 0: - raise Exception(f"Wiederherstellung fehlgeschlagen: {result.stderr}") - - # Audit-Log (neue Verbindung) - log_audit('RESTORE', 'database', backup_id, - additional_info=f"Backup wiederhergestellt: {filename}") - - return True, "Backup erfolgreich wiederhergestellt" - - except Exception as e: - logging.error(f"Wiederherstellung fehlgeschlagen: {e}") - return False, str(e) - -def send_backup_notification(success, filename, filesize=None, duration=None, error=None): - """Sendet E-Mail-Benachrichtigung (wenn konfiguriert)""" - if not os.getenv("EMAIL_ENABLED", "false").lower() == "true": - return - - # E-Mail-Funktion vorbereitet aber deaktiviert - # TODO: Implementieren wenn E-Mail-Server konfiguriert ist - logging.info(f"E-Mail-Benachrichtigung vorbereitet: Backup {'erfolgreich' if success else 'fehlgeschlagen'}") - -# Scheduled Backup Job -def scheduled_backup(): - """Führt ein geplantes Backup aus""" - logging.info("Starte geplantes Backup...") - create_backup(backup_type="scheduled", created_by="scheduler") - -# Scheduler konfigurieren - täglich um 3:00 Uhr -scheduler.add_job( - scheduled_backup, - 'cron', - hour=3, - minute=0, - id='daily_backup', - replace_existing=True -) - -# Rate-Limiting Funktionen -def get_client_ip(): - """Ermittelt die echte IP-Adresse des Clients""" - # Debug logging - app.logger.info(f"Headers - X-Real-IP: {request.headers.get('X-Real-IP')}, X-Forwarded-For: {request.headers.get('X-Forwarded-For')}, Remote-Addr: {request.remote_addr}") - - # Try X-Real-IP first (set by nginx) - if request.headers.get('X-Real-IP'): - return request.headers.get('X-Real-IP') - # Then X-Forwarded-For - elif request.headers.get('X-Forwarded-For'): - # X-Forwarded-For can contain multiple IPs, take the first one - return request.headers.get('X-Forwarded-For').split(',')[0].strip() - # Fallback to remote_addr - else: - return request.remote_addr - -def check_ip_blocked(ip_address): - """Prüft ob eine IP-Adresse gesperrt ist""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT blocked_until FROM login_attempts - WHERE ip_address = %s AND blocked_until IS NOT NULL - """, (ip_address,)) - - result = cur.fetchone() - cur.close() - conn.close() - - if result and result[0]: - if result[0] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None): - return True, result[0] - return False, None - -def record_failed_attempt(ip_address, username): - """Zeichnet einen fehlgeschlagenen Login-Versuch auf""" - conn = get_connection() - cur = conn.cursor() - - # Random Fehlermeldung - error_message = random.choice(FAIL_MESSAGES) - - try: - # Prüfen ob IP bereits existiert - cur.execute(""" - SELECT attempt_count FROM login_attempts - WHERE ip_address = %s - """, (ip_address,)) - - result = cur.fetchone() - - if result: - # Update bestehenden Eintrag - new_count = result[0] + 1 - blocked_until = None - - if new_count >= MAX_LOGIN_ATTEMPTS: - blocked_until = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) + timedelta(hours=BLOCK_DURATION_HOURS) - # E-Mail-Benachrichtigung (wenn aktiviert) - if os.getenv("EMAIL_ENABLED", "false").lower() == "true": - send_security_alert_email(ip_address, username, new_count) - - cur.execute(""" - UPDATE login_attempts - SET attempt_count = %s, - last_attempt = CURRENT_TIMESTAMP, - blocked_until = %s, - last_username_tried = %s, - last_error_message = %s - WHERE ip_address = %s - """, (new_count, blocked_until, username, error_message, ip_address)) - else: - # Neuen Eintrag erstellen - cur.execute(""" - INSERT INTO login_attempts - (ip_address, attempt_count, last_username_tried, last_error_message) - VALUES (%s, 1, %s, %s) - """, (ip_address, username, error_message)) - - conn.commit() - - # Audit-Log - log_audit('LOGIN_FAILED', 'user', - additional_info=f"IP: {ip_address}, User: {username}, Message: {error_message}") - - except Exception as e: - print(f"Rate limiting error: {e}") - conn.rollback() - finally: - cur.close() - conn.close() - - return error_message - -def reset_login_attempts(ip_address): - """Setzt die Login-Versuche für eine IP zurück""" - conn = get_connection() - cur = conn.cursor() - - try: - cur.execute(""" - DELETE FROM login_attempts - WHERE ip_address = %s - """, (ip_address,)) - conn.commit() - except Exception as e: - print(f"Reset attempts error: {e}") - conn.rollback() - finally: - cur.close() - conn.close() - -def get_login_attempts(ip_address): - """Gibt die Anzahl der Login-Versuche für eine IP zurück""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT attempt_count FROM login_attempts - WHERE ip_address = %s - """, (ip_address,)) - - result = cur.fetchone() - cur.close() - conn.close() - - return result[0] if result else 0 - -def send_security_alert_email(ip_address, username, attempt_count): - """Sendet eine Sicherheitswarnung per E-Mail""" - subject = f"⚠️ SICHERHEITSWARNUNG: {attempt_count} fehlgeschlagene Login-Versuche" - body = f""" - WARNUNG: Mehrere fehlgeschlagene Login-Versuche erkannt! - - IP-Adresse: {ip_address} - Versuchter Benutzername: {username} - Anzahl Versuche: {attempt_count} - Zeit: {datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y-%m-%d %H:%M:%S')} - - Die IP-Adresse wurde für 24 Stunden gesperrt. - - Dies ist eine automatische Nachricht vom v2-Docker Admin Panel. - """ - - # TODO: E-Mail-Versand implementieren wenn SMTP konfiguriert - logging.warning(f"Sicherheitswarnung: {attempt_count} fehlgeschlagene Versuche von IP {ip_address}") - print(f"E-Mail würde gesendet: {subject}") - -def verify_recaptcha(response): - """Verifiziert die reCAPTCHA v2 Response mit Google""" - secret_key = os.getenv('RECAPTCHA_SECRET_KEY') - - # Wenn kein Secret Key konfiguriert ist, CAPTCHA als bestanden werten (für PoC) - if not secret_key: - logging.warning("RECAPTCHA_SECRET_KEY nicht konfiguriert - CAPTCHA wird übersprungen") - return True - - # Verifizierung bei Google - try: - verify_url = 'https://www.google.com/recaptcha/api/siteverify' - data = { - 'secret': secret_key, - 'response': response - } - - # Timeout für Request setzen - r = requests.post(verify_url, data=data, timeout=5) - result = r.json() - - # Log für Debugging - if not result.get('success'): - logging.warning(f"reCAPTCHA Validierung fehlgeschlagen: {result.get('error-codes', [])}") - - return result.get('success', False) - - except requests.exceptions.RequestException as e: - logging.error(f"reCAPTCHA Verifizierung fehlgeschlagen: {str(e)}") - # Bei Netzwerkfehlern CAPTCHA als bestanden werten - return True - except Exception as e: - logging.error(f"Unerwarteter Fehler bei reCAPTCHA: {str(e)}") - return False - -def generate_license_key(license_type='full'): - """ - Generiert einen Lizenzschlüssel im Format: AF-F-YYYYMM-XXXX-YYYY-ZZZZ - - AF = Account Factory (Produktkennung) - F/T = F für Fullversion, T für Testversion - YYYY = Jahr - MM = Monat - XXXX-YYYY-ZZZZ = Zufällige alphanumerische Zeichen - """ - # Erlaubte Zeichen (ohne verwirrende wie 0/O, 1/I/l) - chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' - - # Datum-Teil - now = datetime.now(ZoneInfo("Europe/Berlin")) - date_part = now.strftime('%Y%m') - type_char = 'F' if license_type == 'full' else 'T' - - # Zufällige Teile generieren (3 Blöcke à 4 Zeichen) - parts = [] - for _ in range(3): - part = ''.join(secrets.choice(chars) for _ in range(4)) - parts.append(part) - - # Key zusammensetzen - key = f"AF-{type_char}-{date_part}-{parts[0]}-{parts[1]}-{parts[2]}" - - return key - -def validate_license_key(key): - """ - Validiert das License Key Format - Erwartet: AF-F-YYYYMM-XXXX-YYYY-ZZZZ oder AF-T-YYYYMM-XXXX-YYYY-ZZZZ - """ - if not key: - return False - - # Pattern für das neue Format - # AF- (fest) + F oder T + - + 6 Ziffern (YYYYMM) + - + 4 Zeichen + - + 4 Zeichen + - + 4 Zeichen - pattern = r'^AF-[FT]-\d{6}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$' - - # Großbuchstaben für Vergleich - return bool(re.match(pattern, key.upper())) - -@app.route("/login", methods=["GET", "POST"]) -def login(): - # Timing-Attack Schutz - Start Zeit merken - start_time = time.time() - - # IP-Adresse ermitteln - ip_address = get_client_ip() - - # Prüfen ob IP gesperrt ist - is_blocked, blocked_until = check_ip_blocked(ip_address) - if is_blocked: - time_remaining = (blocked_until - datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None)).total_seconds() / 3600 - error_msg = f"IP GESPERRT! Noch {time_remaining:.1f} Stunden warten." - return render_template("login.html", error=error_msg, error_type="blocked") - - # Anzahl bisheriger Versuche - attempt_count = get_login_attempts(ip_address) - - if request.method == "POST": - username = request.form.get("username") - password = request.form.get("password") - captcha_response = request.form.get("g-recaptcha-response") - - # CAPTCHA-Prüfung nur wenn Keys konfiguriert sind - recaptcha_site_key = os.getenv('RECAPTCHA_SITE_KEY') - if attempt_count >= CAPTCHA_AFTER_ATTEMPTS and recaptcha_site_key: - if not captcha_response: - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA ERFORDERLICH!", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # CAPTCHA validieren - if not verify_recaptcha(captcha_response): - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA UNGÜLTIG! Bitte erneut versuchen.", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # Check user in database first, fallback to env vars - user = get_user_by_username(username) - login_success = False - needs_2fa = False - - if user: - # Database user authentication - if verify_password(password, user['password_hash']): - login_success = True - needs_2fa = user['totp_enabled'] - else: - # Fallback to environment variables for backward compatibility - admin1_user = os.getenv("ADMIN1_USERNAME") - admin1_pass = os.getenv("ADMIN1_PASSWORD") - admin2_user = os.getenv("ADMIN2_USERNAME") - admin2_pass = os.getenv("ADMIN2_PASSWORD") - - if ((username == admin1_user and password == admin1_pass) or - (username == admin2_user and password == admin2_pass)): - login_success = True - - # Timing-Attack Schutz - Mindestens 1 Sekunde warten - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - - if login_success: - # Erfolgreicher Login - if needs_2fa: - # Store temporary session for 2FA verification - session['temp_username'] = username - session['temp_user_id'] = user['id'] - session['awaiting_2fa'] = True - return redirect(url_for('verify_2fa')) - else: - # Complete login without 2FA - session.permanent = True # Aktiviert das Timeout - session['logged_in'] = True - session['username'] = username - session['user_id'] = user['id'] if user else None - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - reset_login_attempts(ip_address) - log_audit('LOGIN_SUCCESS', 'user', - additional_info=f"Erfolgreiche Anmeldung von IP: {ip_address}") - return redirect(url_for('dashboard')) - else: - # Fehlgeschlagener Login - error_message = record_failed_attempt(ip_address, username) - new_attempt_count = get_login_attempts(ip_address) - - # Prüfen ob jetzt gesperrt - is_now_blocked, _ = check_ip_blocked(ip_address) - if is_now_blocked: - log_audit('LOGIN_BLOCKED', 'security', - additional_info=f"IP {ip_address} wurde nach {MAX_LOGIN_ATTEMPTS} Versuchen gesperrt") - - return render_template("login.html", - error=error_message, - show_captcha=(new_attempt_count >= CAPTCHA_AFTER_ATTEMPTS and os.getenv('RECAPTCHA_SITE_KEY')), - error_type="failed", - attempts_left=max(0, MAX_LOGIN_ATTEMPTS - new_attempt_count), - recaptcha_site_key=os.getenv('RECAPTCHA_SITE_KEY')) - - # GET Request - return render_template("login.html", - show_captcha=(attempt_count >= CAPTCHA_AFTER_ATTEMPTS and os.getenv('RECAPTCHA_SITE_KEY')), - attempts_left=max(0, MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=os.getenv('RECAPTCHA_SITE_KEY')) - -@app.route("/logout") -def logout(): - username = session.get('username', 'unknown') - log_audit('LOGOUT', 'user', additional_info=f"Abmeldung") - session.pop('logged_in', None) - session.pop('username', None) - session.pop('user_id', None) - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - return redirect(url_for('login')) - -@app.route("/verify-2fa", methods=["GET", "POST"]) -def verify_2fa(): - if not session.get('awaiting_2fa'): - return redirect(url_for('login')) - - if request.method == "POST": - token = request.form.get('token', '').replace(' ', '') - username = session.get('temp_username') - user_id = session.get('temp_user_id') - - if not username or not user_id: - flash('Session expired. Please login again.', 'error') - return redirect(url_for('login')) - - user = get_user_by_username(username) - if not user: - flash('User not found.', 'error') - return redirect(url_for('login')) - - # Check if it's a backup code - if len(token) == 8 and token.isupper(): - # Try backup code - backup_codes = json.loads(user['backup_codes']) if user['backup_codes'] else [] - if verify_backup_code(token, backup_codes): - # Remove used backup code - code_hash = hash_backup_code(token) - backup_codes.remove(code_hash) - - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET backup_codes = %s WHERE id = %s", - (json.dumps(backup_codes), user_id)) - conn.commit() - cur.close() - conn.close() - - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - flash('Login successful using backup code. Please generate new backup codes.', 'warning') - log_audit('LOGIN_2FA_BACKUP', 'user', additional_info=f"2FA login with backup code") - return redirect(url_for('dashboard')) - else: - # Try TOTP token - if verify_totp(user['totp_secret'], token): - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - log_audit('LOGIN_2FA_SUCCESS', 'user', additional_info=f"2FA login successful") - return redirect(url_for('dashboard')) - - # Failed verification - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET failed_2fa_attempts = failed_2fa_attempts + 1, last_failed_2fa = %s WHERE id = %s", - (datetime.now(), user_id)) - conn.commit() - cur.close() - conn.close() - - flash('Invalid authentication code. Please try again.', 'error') - log_audit('LOGIN_2FA_FAILED', 'user', additional_info=f"Failed 2FA attempt") - - return render_template('verify_2fa.html') - -@app.route("/profile") -@login_required -def profile(): - user = get_user_by_username(session['username']) - if not user: - # For environment-based users, redirect with message - flash('Bitte führen Sie das Migrations-Script aus, um Passwort-Änderung und 2FA zu aktivieren.', 'info') - return redirect(url_for('dashboard')) - return render_template('profile.html', user=user) - -@app.route("/profile/change-password", methods=["POST"]) -@login_required -def change_password(): - current_password = request.form.get('current_password') - new_password = request.form.get('new_password') - confirm_password = request.form.get('confirm_password') - - user = get_user_by_username(session['username']) - - # Verify current password - if not verify_password(current_password, user['password_hash']): - flash('Current password is incorrect.', 'error') - return redirect(url_for('profile')) - - # Check new password - if new_password != confirm_password: - flash('New passwords do not match.', 'error') - return redirect(url_for('profile')) - - if len(new_password) < 8: - flash('Password must be at least 8 characters long.', 'error') - return redirect(url_for('profile')) - - # Update password - new_hash = hash_password(new_password) - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET password_hash = %s, last_password_change = %s WHERE id = %s", - (new_hash, datetime.now(), user['id'])) - conn.commit() - cur.close() - conn.close() - - log_audit('PASSWORD_CHANGE', 'user', entity_id=user['id'], - additional_info="Password changed successfully") - flash('Password changed successfully.', 'success') - return redirect(url_for('profile')) - -@app.route("/profile/setup-2fa") -@login_required -def setup_2fa(): - user = get_user_by_username(session['username']) - - if user['totp_enabled']: - flash('2FA is already enabled for your account.', 'info') - return redirect(url_for('profile')) - - # Generate new TOTP secret - totp_secret = generate_totp_secret() - session['temp_totp_secret'] = totp_secret - - # Generate QR code - qr_code = generate_qr_code(user['username'], totp_secret) - - return render_template('setup_2fa.html', - totp_secret=totp_secret, - qr_code=qr_code) - -@app.route("/profile/enable-2fa", methods=["POST"]) -@login_required -def enable_2fa(): - token = request.form.get('token', '').replace(' ', '') - totp_secret = session.get('temp_totp_secret') - - if not totp_secret: - flash('2FA setup session expired. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Verify the token - if not verify_totp(totp_secret, token): - flash('Invalid authentication code. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Generate backup codes - backup_codes = generate_backup_codes() - hashed_codes = [hash_backup_code(code) for code in backup_codes] - - # Enable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_secret = %s, totp_enabled = TRUE, backup_codes = %s - WHERE username = %s - """, (totp_secret, json.dumps(hashed_codes), session['username'])) - conn.commit() - cur.close() - conn.close() - - session.pop('temp_totp_secret', None) - - log_audit('2FA_ENABLED', 'user', additional_info="2FA enabled successfully") - - # Show backup codes - return render_template('backup_codes.html', backup_codes=backup_codes) - -@app.route("/profile/disable-2fa", methods=["POST"]) -@login_required -def disable_2fa(): - password = request.form.get('password') - user = get_user_by_username(session['username']) - - # Verify password - if not verify_password(password, user['password_hash']): - flash('Incorrect password.', 'error') - return redirect(url_for('profile')) - - # Disable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_enabled = FALSE, totp_secret = NULL, backup_codes = NULL - WHERE username = %s - """, (session['username'],)) - conn.commit() - cur.close() - conn.close() - - log_audit('2FA_DISABLED', 'user', additional_info="2FA disabled") - flash('2FA has been disabled for your account.', 'success') - return redirect(url_for('profile')) - -@app.route("/heartbeat", methods=['POST']) -@login_required -def heartbeat(): - """Endpoint für Session Keep-Alive - aktualisiert last_activity""" - # Aktualisiere last_activity nur wenn explizit angefordert - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # Force session save - session.modified = True - - return jsonify({ - 'status': 'ok', - 'last_activity': session['last_activity'], - 'username': session.get('username') - }) - -@app.route("/api/generate-license-key", methods=['POST']) -@login_required -def api_generate_key(): - """API Endpoint zur Generierung eines neuen Lizenzschlüssels""" - try: - # Lizenztyp aus Request holen (default: full) - data = request.get_json() or {} - license_type = data.get('type', 'full') - - # Key generieren - key = generate_license_key(license_type) - - # Prüfen ob Key bereits existiert (sehr unwahrscheinlich aber sicher ist sicher) - conn = get_connection() - cur = conn.cursor() - - # Wiederhole bis eindeutiger Key gefunden - attempts = 0 - while attempts < 10: # Max 10 Versuche - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (key,)) - if not cur.fetchone(): - break # Key ist eindeutig - key = generate_license_key(license_type) - attempts += 1 - - cur.close() - conn.close() - - # Log für Audit - log_audit('GENERATE_KEY', 'license', - additional_info={'type': license_type, 'key': key}) - - return jsonify({ - 'success': True, - 'key': key, - 'type': license_type - }) - - except Exception as e: - logging.error(f"Fehler bei Key-Generierung: {str(e)}") - return jsonify({ - 'success': False, - 'error': 'Fehler bei der Key-Generierung' - }), 500 - -@app.route("/api/customers", methods=['GET']) -@login_required -def api_customers(): - """API Endpoint für die Kundensuche mit Select2""" - try: - # Suchparameter - search = request.args.get('q', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - customer_id = request.args.get('id', type=int) - - conn = get_connection() - cur = conn.cursor() - - # Einzelnen Kunden per ID abrufen - if customer_id: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.id = %s - GROUP BY c.id, c.name, c.email - """, (customer_id,)) - - customer = cur.fetchone() - results = [] - if customer: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} ({customer[2]})", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - cur.close() - conn.close() - - return jsonify({ - 'results': results, - 'pagination': {'more': False} - }) - - # SQL Query mit optionaler Suche - elif search: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE LOWER(c.name) LIKE LOWER(%s) - OR LOWER(c.email) LIKE LOWER(%s) - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (f'%{search}%', f'%{search}%', per_page, (page - 1) * per_page)) - else: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (per_page, (page - 1) * per_page)) - - customers = cur.fetchall() - - # Format für Select2 - results = [] - for customer in customers: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} - {customer[2]} ({customer[3]} Lizenzen)", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - # Gesamtanzahl für Pagination - if search: - cur.execute(""" - SELECT COUNT(*) FROM customers - WHERE LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - """, (f'%{search}%', f'%{search}%')) - else: - cur.execute("SELECT COUNT(*) FROM customers") - - total_count = cur.fetchone()[0] - - cur.close() - conn.close() - - # Select2 Response Format - return jsonify({ - 'results': results, - 'pagination': { - 'more': (page * per_page) < total_count - } - }) - - except Exception as e: - logging.error(f"Fehler bei Kundensuche: {str(e)}") - return jsonify({ - 'results': [], - 'error': 'Fehler bei der Kundensuche' - }), 500 - -@app.route("/") -@login_required -def dashboard(): - conn = get_connection() - cur = conn.cursor() - - # Statistiken abrufen - # Gesamtanzahl Kunden (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = FALSE") - total_customers = cur.fetchone()[0] - - # Gesamtanzahl Lizenzen (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = FALSE") - total_licenses = cur.fetchone()[0] - - # Aktive Lizenzen (nicht abgelaufen und is_active = true, ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE AND is_active = TRUE AND is_test = FALSE - """) - active_licenses = cur.fetchone()[0] - - # Aktive Sessions - cur.execute("SELECT COUNT(*) FROM sessions WHERE is_active = TRUE") - active_sessions_count = cur.fetchone()[0] - - # Abgelaufene Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until < CURRENT_DATE AND is_test = FALSE - """) - expired_licenses = cur.fetchone()[0] - - # Deaktivierte Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE is_active = FALSE AND is_test = FALSE - """) - inactive_licenses = cur.fetchone()[0] - - # Lizenzen die in den nächsten 30 Tagen ablaufen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE - AND valid_until < CURRENT_DATE + INTERVAL '30 days' - AND is_active = TRUE - AND is_test = FALSE - """) - expiring_soon = cur.fetchone()[0] - - # Testlizenzen vs Vollversionen (ohne Testdaten) - cur.execute(""" - SELECT license_type, COUNT(*) - FROM licenses - WHERE is_test = FALSE - GROUP BY license_type - """) - license_types = dict(cur.fetchall()) - - # Anzahl Testdaten - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = TRUE") - test_data_count = cur.fetchone()[0] - - # Anzahl Test-Kunden - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = TRUE") - test_customers_count = cur.fetchone()[0] - - # Anzahl Test-Ressourcen - cur.execute("SELECT COUNT(*) FROM resource_pools WHERE is_test = TRUE") - test_resources_count = cur.fetchone()[0] - - # Letzte 5 erstellten Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.is_test = FALSE - ORDER BY l.id DESC - LIMIT 5 - """) - recent_licenses = cur.fetchall() - - # Bald ablaufende Lizenzen (nächste 30 Tage, ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - l.valid_until - CURRENT_DATE as days_left - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.valid_until >= CURRENT_DATE - AND l.valid_until < CURRENT_DATE + INTERVAL '30 days' - AND l.is_active = TRUE - AND l.is_test = FALSE - ORDER BY l.valid_until - LIMIT 10 - """) - expiring_licenses = cur.fetchall() - - # Letztes Backup - cur.execute(""" - SELECT created_at, filesize, duration_seconds, backup_type, status - FROM backup_history - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup_info = cur.fetchone() - - # Sicherheitsstatistiken - # Gesperrte IPs - cur.execute(""" - SELECT COUNT(*) FROM login_attempts - WHERE blocked_until IS NOT NULL AND blocked_until > CURRENT_TIMESTAMP - """) - blocked_ips_count = cur.fetchone()[0] - - # Fehlversuche heute - cur.execute(""" - SELECT COALESCE(SUM(attempt_count), 0) FROM login_attempts - WHERE last_attempt::date = CURRENT_DATE - """) - failed_attempts_today = cur.fetchone()[0] - - # Letzte 5 Sicherheitsereignisse - cur.execute(""" - SELECT - la.ip_address, - la.attempt_count, - la.last_attempt, - la.blocked_until, - la.last_username_tried, - la.last_error_message - FROM login_attempts la - ORDER BY la.last_attempt DESC - LIMIT 5 - """) - recent_security_events = [] - for event in cur.fetchall(): - recent_security_events.append({ - 'ip_address': event[0], - 'attempt_count': event[1], - 'last_attempt': event[2].strftime('%d.%m %H:%M'), - 'blocked_until': event[3].strftime('%d.%m %H:%M') if event[3] and event[3] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) else None, - 'username_tried': event[4], - 'error_message': event[5] - }) - - # Sicherheitslevel berechnen - if blocked_ips_count > 5 or failed_attempts_today > 50: - security_level = 'danger' - security_level_text = 'KRITISCH' - elif blocked_ips_count > 2 or failed_attempts_today > 20: - security_level = 'warning' - security_level_text = 'ERHÖHT' - else: - security_level = 'success' - security_level_text = 'NORMAL' - - # Resource Pool Statistiken (nur Live-Daten, keine Testdaten) - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = FALSE - GROUP BY resource_type - """) - - resource_stats = {} - resource_warning = None - - for row in cur.fetchall(): - available_percent = round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - resource_stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': available_percent, - 'warning_level': 'danger' if row[1] < 50 else 'warning' if row[1] < 100 else 'success' - } - - # Warnung bei niedrigem Bestand - if row[1] < 50: - if not resource_warning: - resource_warning = f"Niedriger Bestand bei {row[0].upper()}: nur noch {row[1]} verfügbar!" - else: - resource_warning += f" | {row[0].upper()}: {row[1]}" - - cur.close() - conn.close() - - stats = { - 'total_customers': total_customers, - 'total_licenses': total_licenses, - 'active_licenses': active_licenses, - 'expired_licenses': expired_licenses, - 'inactive_licenses': inactive_licenses, - 'expiring_soon': expiring_soon, - 'full_licenses': license_types.get('full', 0), - 'test_licenses': license_types.get('test', 0), - 'test_data_count': test_data_count, - 'test_customers_count': test_customers_count, - 'test_resources_count': test_resources_count, - 'recent_licenses': recent_licenses, - 'expiring_licenses': expiring_licenses, - 'active_sessions': active_sessions_count, - 'last_backup': last_backup_info, - # Sicherheitsstatistiken - 'blocked_ips_count': blocked_ips_count, - 'failed_attempts_today': failed_attempts_today, - 'recent_security_events': recent_security_events, - 'security_level': security_level, - 'security_level_text': security_level_text, - 'resource_stats': resource_stats - } - - return render_template("dashboard.html", - stats=stats, - resource_stats=resource_stats, - resource_warning=resource_warning, - username=session.get('username')) - -@app.route("/create", methods=["GET", "POST"]) -@login_required -def create_license(): - if request.method == "POST": - customer_id = request.form.get("customer_id") - license_key = request.form["license_key"].upper() # Immer Großbuchstaben - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Validiere License Key Format - if not validate_license_key(license_key): - flash('Ungültiges License Key Format! Erwartet: AF-YYYYMMFT-XXXX-YYYY-ZZZZ', 'error') - return redirect(url_for('create_license')) - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('create_license')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('create_license')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - customer_info = {'name': name, 'email': email, 'is_test': is_test} - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos für Audit-Log - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('create_license')) - customer_info = {'name': customer_data[0], 'email': customer_data[1]} - - # Wenn Kunde Test-Kunde ist, Lizenz auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Lizenz hinzufügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit, is_test) - VALUES (%s, %s, %s, %s, %s, TRUE, %s, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit, is_test)) - license_id = cur.fetchone()[0] - - # Ressourcen zuweisen - try: - # Prüfe Verfügbarkeit - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {available[0]})") - if available[1] < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {ipv4_count}, verfügbar: {available[1]})") - if available[2] < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar (benötigt: {phone_count}, verfügbar: {available[2]})") - - # Domains zuweisen - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s zuweisen - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern zuweisen - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - except ValueError as e: - conn.rollback() - flash(str(e), 'error') - return redirect(url_for('create_license')) - - conn.commit() - - # Audit-Log - log_audit('CREATE', 'license', license_id, - new_values={ - 'license_key': license_key, - 'customer_name': customer_info['name'], - 'customer_email': customer_info['email'], - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'device_limit': device_limit, - 'is_test': is_test - }) - - flash(f'Lizenz {license_key} erfolgreich erstellt!', 'success') - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Erstellen der Lizenz: {str(e)}") - flash('Fehler beim Erstellen der Lizenz!', 'error') - finally: - cur.close() - conn.close() - - # Preserve show_test parameter if present - redirect_url = "/create" - if request.args.get('show_test') == 'true': - redirect_url += "?show_test=true" - return redirect(redirect_url) - - # Unterstützung für vorausgewählten Kunden - preselected_customer_id = request.args.get('customer_id', type=int) - return render_template("index.html", username=session.get('username'), preselected_customer_id=preselected_customer_id) - -@app.route("/batch", methods=["GET", "POST"]) -@login_required -def batch_licenses(): - """Batch-Generierung mehrerer Lizenzen für einen Kunden""" - if request.method == "POST": - # Formulardaten - customer_id = request.form.get("customer_id") - license_type = request.form["license_type"] - quantity = int(request.form["quantity"]) - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - # Sicherheitslimit - if quantity < 1 or quantity > 100: - flash('Anzahl muss zwischen 1 und 100 liegen!', 'error') - return redirect(url_for('batch_licenses')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('batch_licenses')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('batch_licenses')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('batch_licenses')) - name = customer_data[0] - email = customer_data[1] - - # Wenn Kunde Test-Kunde ist, Lizenzen auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Prüfe Ressourcen-Verfügbarkeit für gesamten Batch - total_domains_needed = domain_count * quantity - total_ipv4s_needed = ipv4_count * quantity - total_phones_needed = phone_count * quantity - - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < total_domains_needed: - flash(f"Nicht genügend Domains verfügbar (benötigt: {total_domains_needed}, verfügbar: {available[0]})", 'error') - return redirect(url_for('batch_licenses')) - if available[1] < total_ipv4s_needed: - flash(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {total_ipv4s_needed}, verfügbar: {available[1]})", 'error') - return redirect(url_for('batch_licenses')) - if available[2] < total_phones_needed: - flash(f"Nicht genügend Telefonnummern verfügbar (benötigt: {total_phones_needed}, verfügbar: {available[2]})", 'error') - return redirect(url_for('batch_licenses')) - - # Lizenzen generieren und speichern - generated_licenses = [] - for i in range(quantity): - # Eindeutigen Key generieren - attempts = 0 - while attempts < 10: - license_key = generate_license_key(license_type) - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (license_key,)) - if not cur.fetchone(): - break - attempts += 1 - - # Lizenz einfügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, is_test, - valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit) - VALUES (%s, %s, %s, %s, %s, %s, true, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, is_test, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit)) - license_id = cur.fetchone()[0] - - # Ressourcen für diese Lizenz zuweisen - # Domains - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - generated_licenses.append({ - 'id': license_id, - 'key': license_key, - 'type': license_type - }) - - conn.commit() - - # Audit-Log - log_audit('CREATE_BATCH', 'license', - new_values={'customer': name, 'quantity': quantity, 'type': license_type}, - additional_info=f"Batch-Generierung von {quantity} Lizenzen") - - # Session für Export speichern - session['batch_export'] = { - 'customer': name, - 'email': email, - 'licenses': generated_licenses, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'timestamp': datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - } - - flash(f'{quantity} Lizenzen erfolgreich generiert!', 'success') - return render_template("batch_result.html", - customer=name, - email=email, - licenses=generated_licenses, - valid_from=valid_from, - valid_until=valid_until) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler bei Batch-Generierung: {str(e)}") - flash('Fehler bei der Batch-Generierung!', 'error') - return redirect(url_for('batch_licenses')) - finally: - cur.close() - conn.close() - - # GET Request - return render_template("batch_form.html") - -@app.route("/batch/export") -@login_required -def export_batch(): - """Exportiert die zuletzt generierten Batch-Lizenzen""" - batch_data = session.get('batch_export') - if not batch_data: - flash('Keine Batch-Daten zum Exportieren vorhanden!', 'error') - return redirect(url_for('batch_licenses')) - - # CSV generieren - output = io.StringIO() - output.write('\ufeff') # UTF-8 BOM für Excel - - # Header - output.write(f"Kunde: {batch_data['customer']}\n") - output.write(f"E-Mail: {batch_data['email']}\n") - output.write(f"Generiert am: {datetime.fromisoformat(batch_data['timestamp']).strftime('%d.%m.%Y %H:%M')}\n") - output.write(f"Gültig von: {batch_data['valid_from']} bis {batch_data['valid_until']}\n") - output.write("\n") - output.write("Nr;Lizenzschlüssel;Typ\n") - - # Lizenzen - for i, license in enumerate(batch_data['licenses'], 1): - typ_text = "Vollversion" if license['type'] == 'full' else "Testversion" - output.write(f"{i};{license['key']};{typ_text}\n") - - output.seek(0) - - # Audit-Log - log_audit('EXPORT', 'batch_licenses', - additional_info=f"Export von {len(batch_data['licenses'])} Batch-Lizenzen") - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f"batch_licenses_{batch_data['customer'].replace(' ', '_')}_{datetime.now(ZoneInfo('Europe/Berlin')).strftime('%Y%m%d_%H%M%S')}.csv" - ) - -@app.route("/licenses") -@login_required -def licenses(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/license/edit/", methods=["GET", "POST"]) -@login_required -def edit_license(license_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute(""" - SELECT license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit - FROM licenses WHERE id = %s - """, (license_id,)) - old_license = cur.fetchone() - - # Update license - license_key = request.form["license_key"] - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - valid_until = request.form["valid_until"] - is_active = request.form.get("is_active") == "on" - is_test = request.form.get("is_test") == "on" - device_limit = int(request.form.get("device_limit", 3)) - - cur.execute(""" - UPDATE licenses - SET license_key = %s, license_type = %s, valid_from = %s, - valid_until = %s, is_active = %s, is_test = %s, device_limit = %s - WHERE id = %s - """, (license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit, license_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'license_key': old_license[0], - 'license_type': old_license[1], - 'valid_from': str(old_license[2]), - 'valid_until': str(old_license[3]), - 'is_active': old_license[4], - 'is_test': old_license[5], - 'device_limit': old_license[6] - }, - new_values={ - 'license_key': license_key, - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'is_active': is_active, - 'is_test': is_test, - 'device_limit': device_limit - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei wenn vorhanden - if request.referrer and 'customer_id=' in request.referrer: - import re - match = re.search(r'customer_id=(\d+)', request.referrer) - if match: - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={match.group(1)}" - - return redirect(redirect_url) - - # Get license data - cur.execute(""" - SELECT l.id, l.license_key, c.name, c.email, l.license_type, - l.valid_from, l.valid_until, l.is_active, c.id, l.is_test, l.device_limit - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - - license = cur.fetchone() - cur.close() - conn.close() - - if not license: - return redirect("/licenses") - - return render_template("edit_license.html", license=license, username=session.get('username')) - -@app.route("/license/delete/", methods=["POST"]) -@login_required -def delete_license(license_id): - conn = get_connection() - cur = conn.cursor() - - # Lizenzdetails für Audit-Log abrufen - cur.execute(""" - SELECT l.license_key, c.name, l.license_type - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - license_info = cur.fetchone() - - cur.execute("DELETE FROM licenses WHERE id = %s", (license_id,)) - - conn.commit() - - # Audit-Log - if license_info: - log_audit('DELETE', 'license', license_id, - old_values={ - 'license_key': license_info[0], - 'customer_name': license_info[1], - 'license_type': license_info[2] - }) - - cur.close() - conn.close() - - return redirect("/licenses") - -@app.route("/customers") -@login_required -def customers(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/customer/edit/", methods=["GET", "POST"]) -@login_required -def edit_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - old_customer = cur.fetchone() - - # Update customer - name = request.form["name"] - email = request.form["email"] - is_test = request.form.get("is_test") == "on" - - cur.execute(""" - UPDATE customers - SET name = %s, email = %s, is_test = %s - WHERE id = %s - """, (name, email, is_test, customer_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'customer', customer_id, - old_values={ - 'name': old_customer[0], - 'email': old_customer[1], - 'is_test': old_customer[2] - }, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei (immer der aktuelle Kunde) - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={customer_id}" - - return redirect(redirect_url) - - # Get customer data with licenses - cur.execute(""" - SELECT id, name, email, created_at, is_test FROM customers WHERE id = %s - """, (customer_id,)) - - customer = cur.fetchone() - if not customer: - cur.close() - conn.close() - return "Kunde nicht gefunden", 404 - - - # Get customer's licenses - cur.execute(""" - SELECT id, license_key, license_type, valid_from, valid_until, is_active - FROM licenses - WHERE customer_id = %s - ORDER BY valid_until DESC - """, (customer_id,)) - - licenses = cur.fetchall() - - cur.close() - conn.close() - - if not customer: - return redirect("/customers-licenses") - - return render_template("edit_customer.html", customer=customer, licenses=licenses, username=session.get('username')) - -@app.route("/customer/create", methods=["GET", "POST"]) -@login_required -def create_customer(): - """Erstellt einen neuen Kunden ohne Lizenz""" - if request.method == "POST": - name = request.form.get('name') - email = request.form.get('email') - is_test = request.form.get('is_test') == 'on' - - if not name or not email: - flash("Name und E-Mail sind Pflichtfelder!", "error") - return render_template("create_customer.html", username=session.get('username')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfen ob E-Mail bereits existiert - cur.execute("SELECT id, name FROM customers WHERE email = %s", (email,)) - existing = cur.fetchone() - if existing: - flash(f"Ein Kunde mit der E-Mail '{email}' existiert bereits: {existing[1]}", "error") - return render_template("create_customer.html", username=session.get('username')) - - # Kunde erstellen - cur.execute(""" - INSERT INTO customers (name, email, created_at, is_test) - VALUES (%s, %s, %s, %s) RETURNING id - """, (name, email, datetime.now(), is_test)) - - customer_id = cur.fetchone()[0] - conn.commit() - - # Audit-Log - log_audit('CREATE', 'customer', customer_id, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - flash(f"Kunde '{name}' wurde erfolgreich angelegt!", "success") - return redirect(f"/customer/edit/{customer_id}") - - except Exception as e: - conn.rollback() - flash(f"Fehler beim Anlegen des Kunden: {str(e)}", "error") - return render_template("create_customer.html", username=session.get('username')) - finally: - cur.close() - conn.close() - - # GET Request - Formular anzeigen - return render_template("create_customer.html", username=session.get('username')) - -@app.route("/customer/delete/", methods=["POST"]) -@login_required -def delete_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - # Prüfen ob Kunde Lizenzen hat - cur.execute("SELECT COUNT(*) FROM licenses WHERE customer_id = %s", (customer_id,)) - license_count = cur.fetchone()[0] - - if license_count > 0: - # Kunde hat Lizenzen - nicht löschen - cur.close() - conn.close() - return redirect("/customers") - - # Kundendetails für Audit-Log abrufen - cur.execute("SELECT name, email FROM customers WHERE id = %s", (customer_id,)) - customer_info = cur.fetchone() - - # Kunde löschen wenn keine Lizenzen vorhanden - cur.execute("DELETE FROM customers WHERE id = %s", (customer_id,)) - - conn.commit() - - # Audit-Log - if customer_info: - log_audit('DELETE', 'customer', customer_id, - old_values={ - 'name': customer_info[0], - 'email': customer_info[1] - }) - - cur.close() - conn.close() - - return redirect("/customers") - -@app.route("/customers-licenses") -@login_required -def customers_licenses(): - """Kombinierte Ansicht für Kunden und deren Lizenzen""" - conn = get_connection() - cur = conn.cursor() - - # Hole alle Kunden mit Lizenzstatistiken (inkl. Testkunden wenn gewünscht) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - query = """ - SELECT - c.id, - c.name, - c.email, - c.created_at, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - """ - - if not show_test: - query += " WHERE c.is_test = FALSE" - - query += """ - GROUP BY c.id, c.name, c.email, c.created_at - ORDER BY c.name - """ - - cur.execute(query) - customers = cur.fetchall() - - # Hole ausgewählten Kunden nur wenn explizit in URL angegeben - selected_customer_id = request.args.get('customer_id', type=int) - licenses = [] - selected_customer = None - - if customers and selected_customer_id: - # Hole Daten des ausgewählten Kunden - for customer in customers: - if customer[0] == selected_customer_id: - selected_customer = customer - break - - # Hole Lizenzen des ausgewählten Kunden - if selected_customer: - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (selected_customer_id,)) - licenses = cur.fetchall() - - cur.close() - conn.close() - - return render_template("customers_licenses.html", - customers=customers, - selected_customer=selected_customer, - selected_customer_id=selected_customer_id, - licenses=licenses, - show_test=show_test) - -@app.route("/api/customer//licenses") -@login_required -def api_customer_licenses(customer_id): - """API-Endpoint für AJAX-Abruf der Lizenzen eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Lizenzen des Kunden - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (customer_id,)) - - licenses = [] - for row in cur.fetchall(): - license_id = row[0] - - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for res_row in cur.fetchall(): - resource_info = { - 'id': res_row[0], - 'value': res_row[2], - 'assigned_at': res_row[3].strftime('%d.%m.%Y') if res_row[3] else '' - } - - if res_row[1] == 'domain': - resources['domains'].append(resource_info) - elif res_row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif res_row[1] == 'phone': - resources['phones'].append(resource_info) - - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'license_type': row[2], - 'valid_from': row[3].strftime('%d.%m.%Y') if row[3] else '', - 'valid_until': row[4].strftime('%d.%m.%Y') if row[4] else '', - 'is_active': row[5], - 'status': row[6], - 'domain_count': row[7], # limit - 'ipv4_count': row[8], # limit - 'phone_count': row[9], # limit - 'device_limit': row[10], - 'active_devices': row[11], - 'actual_domain_count': row[12], # actual count - 'actual_ipv4_count': row[13], # actual count - 'actual_phone_count': row[14], # actual count - 'resources': resources - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'licenses': licenses, - 'count': len(licenses) - }) - -@app.route("/api/customer//quick-stats") -@login_required -def api_customer_quick_stats(customer_id): - """API-Endpoint für Schnellstatistiken eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Kundenstatistiken - cur.execute(""" - SELECT - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' AND l.valid_until >= CURRENT_DATE THEN 1 END) as expiring_soon - FROM licenses l - WHERE l.customer_id = %s - """, (customer_id,)) - - stats = cur.fetchone() - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'stats': { - 'total': stats[0], - 'active': stats[1], - 'expired': stats[2], - 'expiring_soon': stats[3] - } - }) - -@app.route("/api/license//quick-edit", methods=['POST']) -@login_required -def api_license_quick_edit(license_id): - """API-Endpoint für schnelle Lizenz-Bearbeitung""" - conn = get_connection() - cur = conn.cursor() - - try: - data = request.get_json() - - # Hole alte Werte für Audit-Log - cur.execute(""" - SELECT is_active, valid_until, license_type - FROM licenses WHERE id = %s - """, (license_id,)) - old_values = cur.fetchone() - - if not old_values: - return jsonify({'success': False, 'error': 'Lizenz nicht gefunden'}), 404 - - # Update-Felder vorbereiten - updates = [] - params = [] - new_values = {} - - if 'is_active' in data: - updates.append("is_active = %s") - params.append(data['is_active']) - new_values['is_active'] = data['is_active'] - - if 'valid_until' in data: - updates.append("valid_until = %s") - params.append(data['valid_until']) - new_values['valid_until'] = data['valid_until'] - - if 'license_type' in data: - updates.append("license_type = %s") - params.append(data['license_type']) - new_values['license_type'] = data['license_type'] - - if updates: - params.append(license_id) - cur.execute(f""" - UPDATE licenses - SET {', '.join(updates)} - WHERE id = %s - """, params) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'is_active': old_values[0], - 'valid_until': old_values[1].isoformat() if old_values[1] else None, - 'license_type': old_values[2] - }, - new_values=new_values) - - cur.close() - conn.close() - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/api/license//resources") -@login_required -def api_license_resources(license_id): - """API-Endpoint für detaillierte Ressourcen-Informationen einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for row in cur.fetchall(): - resource_info = { - 'id': row[0], - 'value': row[2], - 'assigned_at': row[3].strftime('%d.%m.%Y') if row[3] else '' - } - - if row[1] == 'domain': - resources['domains'].append(resource_info) - elif row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif row[1] == 'phone': - resources['phones'].append(resource_info) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'resources': resources - }) - - except Exception as e: - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/sessions") -@login_required -def sessions(): - conn = get_connection() - cur = conn.cursor() - - # Sortierparameter - active_sort = request.args.get('active_sort', 'last_heartbeat') - active_order = request.args.get('active_order', 'desc') - ended_sort = request.args.get('ended_sort', 'ended_at') - ended_order = request.args.get('ended_order', 'desc') - - # Whitelist für erlaubte Sortierfelder - Aktive Sessions - active_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'last_heartbeat': 's.last_heartbeat', - 'inactive': 'minutes_inactive' - } - - # Whitelist für erlaubte Sortierfelder - Beendete Sessions - ended_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'ended_at': 's.ended_at', - 'duration': 'duration_minutes' - } - - # Validierung - if active_sort not in active_sort_fields: - active_sort = 'last_heartbeat' - if ended_sort not in ended_sort_fields: - ended_sort = 'ended_at' - if active_order not in ['asc', 'desc']: - active_order = 'desc' - if ended_order not in ['asc', 'desc']: - ended_order = 'desc' - - # Aktive Sessions abrufen - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.user_agent, s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.last_heartbeat))/60 as minutes_inactive - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = TRUE - ORDER BY {active_sort_fields[active_sort]} {active_order.upper()} - """) - active_sessions = cur.fetchall() - - # Inaktive Sessions der letzten 24 Stunden - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))/60 as duration_minutes - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = FALSE - AND s.ended_at > NOW() - INTERVAL '24 hours' - ORDER BY {ended_sort_fields[ended_sort]} {ended_order.upper()} - LIMIT 50 - """) - recent_sessions = cur.fetchall() - - cur.close() - conn.close() - - return render_template("sessions.html", - active_sessions=active_sessions, - recent_sessions=recent_sessions, - active_sort=active_sort, - active_order=active_order, - ended_sort=ended_sort, - ended_order=ended_order, - username=session.get('username')) - -@app.route("/session/end/", methods=["POST"]) -@login_required -def end_session(session_id): - conn = get_connection() - cur = conn.cursor() - - # Session beenden - cur.execute(""" - UPDATE sessions - SET is_active = FALSE, ended_at = NOW() - WHERE id = %s AND is_active = TRUE - """, (session_id,)) - - conn.commit() - cur.close() - conn.close() - - return redirect("/sessions") - -@app.route("/export/licenses") -@login_required -def export_licenses(): - conn = get_connection() - cur = conn.cursor() - - # Alle Lizenzen mit Kundeninformationen abrufen (ohne Testdaten, außer explizit gewünscht) - include_test = request.args.get('include_test', 'false').lower() == 'true' - customer_id = request.args.get('customer_id', type=int) - - query = """ - SELECT l.id, l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type, l.valid_from, l.valid_until, l.is_active, l.is_test, - CASE - WHEN l.is_active = FALSE THEN 'Deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'Abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'Läuft bald ab' - ELSE 'Aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - """ - - # Build WHERE clause - where_conditions = [] - params = [] - - if not include_test: - where_conditions.append("l.is_test = FALSE") - - if customer_id: - where_conditions.append("l.customer_id = %s") - params.append(customer_id) - - if where_conditions: - query += " WHERE " + " AND ".join(where_conditions) - - query += " ORDER BY l.id" - - cur.execute(query, params) - - # Spaltennamen - columns = ['ID', 'Lizenzschlüssel', 'Kunde', 'E-Mail', 'Typ', - 'Gültig von', 'Gültig bis', 'Aktiv', 'Testdaten', 'Status'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Gültig von'] = pd.to_datetime(df['Gültig von']).dt.strftime('%d.%m.%Y') - df['Gültig bis'] = pd.to_datetime(df['Gültig bis']).dt.strftime('%d.%m.%Y') - - # Typ und Aktiv Status anpassen - df['Typ'] = df['Typ'].replace({'full': 'Vollversion', 'test': 'Testversion'}) - df['Aktiv'] = df['Aktiv'].replace({True: 'Ja', False: 'Nein'}) - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'license', - additional_info=f"Export aller Lizenzen als {export_format.upper()}") - filename = f'lizenzen_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Lizenzen', index=False) - - # Formatierung - worksheet = writer.sheets['Lizenzen'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/audit") -@login_required -def export_audit(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_user = request.args.get('user', '') - filter_action = request.args.get('action', '') - filter_entity = request.args.get('entity', '') - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - params = [] - - if filter_user: - query += " AND username ILIKE %s" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - query += " ORDER BY timestamp DESC" - - cur.execute(query, params) - audit_logs = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for log in audit_logs: - action_text = { - 'CREATE': 'Erstellt', - 'UPDATE': 'Bearbeitet', - 'DELETE': 'Gelöscht', - 'LOGIN': 'Anmeldung', - 'LOGOUT': 'Abmeldung', - 'AUTO_LOGOUT': 'Auto-Logout', - 'EXPORT': 'Export', - 'GENERATE_KEY': 'Key generiert', - 'CREATE_BATCH': 'Batch erstellt', - 'BACKUP': 'Backup erstellt', - 'LOGIN_2FA_SUCCESS': '2FA-Anmeldung', - 'LOGIN_2FA_BACKUP': '2FA-Backup-Code', - 'LOGIN_2FA_FAILED': '2FA-Fehlgeschlagen', - 'LOGIN_BLOCKED': 'Login-Blockiert', - 'RESTORE': 'Wiederhergestellt', - 'PASSWORD_CHANGE': 'Passwort geändert', - '2FA_ENABLED': '2FA aktiviert', - '2FA_DISABLED': '2FA deaktiviert' - }.get(log[3], log[3]) - - data.append({ - 'ID': log[0], - 'Zeitstempel': log[1].strftime('%d.%m.%Y %H:%M:%S'), - 'Benutzer': log[2], - 'Aktion': action_text, - 'Entität': log[4], - 'Entität-ID': log[5] or '', - 'IP-Adresse': log[8] or '', - 'Zusatzinfo': log[10] or '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'audit_log_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'audit_log', - additional_info=f"{export_format.upper()} Export mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Audit Log') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Audit Log'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/customers") -@login_required -def export_customers(): - conn = get_connection() - cur = conn.cursor() - - # Check if test data should be included - include_test = request.args.get('include_test', 'false').lower() == 'true' - - # Build query based on test data filter - if include_test: - # Include all customers - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - else: - # Exclude test customers and test licenses - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(CASE WHEN l.is_test = FALSE THEN 1 END) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.is_test = FALSE - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - - cur.execute(query) - - # Spaltennamen - columns = ['ID', 'Name', 'E-Mail', 'Erstellt am', 'Testdaten', - 'Lizenzen gesamt', 'Aktive Lizenzen', 'Abgelaufene Lizenzen'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Erstellt am'] = pd.to_datetime(df['Erstellt am']).dt.strftime('%d.%m.%Y %H:%M') - - # Testdaten formatting - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'customer', - additional_info=f"Export aller Kunden als {export_format.upper()}") - filename = f'kunden_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Kunden', index=False) - - # Formatierung - worksheet = writer.sheets['Kunden'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/sessions") -@login_required -def export_sessions(): - conn = get_connection() - cur = conn.cursor() - - # Holen des Session-Typs (active oder ended) - session_type = request.args.get('type', 'active') - export_format = request.args.get('format', 'excel') - - # Daten je nach Typ abrufen - if session_type == 'active': - # Aktive Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = true - ORDER BY s.last_heartbeat DESC - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Letzte Aktivität': sess[5].strftime('%d.%m.%Y %H:%M:%S'), - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Aktive Sessions' - filename_prefix = 'aktive_sessions' - else: - # Beendete Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = false AND s.ended_at IS NOT NULL - ORDER BY s.ended_at DESC - LIMIT 1000 - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] if sess[6] else 0 - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Endzeit': sess[5].strftime('%d.%m.%Y %H:%M:%S') if sess[5] else '', - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Beendete Sessions' - filename_prefix = 'beendete_sessions' - - cur.close() - conn.close() - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'{filename_prefix}_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'sessions', - additional_info=f"{export_format.upper()} Export von {session_type} Sessions mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name=sheet_name) - - # Spaltenbreiten anpassen - worksheet = writer.sheets[sheet_name] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/resources") -@login_required -def export_resources(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_type = request.args.get('type', '') - filter_status = request.args.get('status', '') - search_query = request.args.get('search', '') - show_test = request.args.get('show_test', 'false').lower() == 'true' - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT r.id, r.resource_type, r.resource_value, r.status, r.allocated_to_license, - r.created_at, r.status_changed_at, - l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type - FROM resource_pools r - LEFT JOIN licenses l ON r.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE 1=1 - """ - params = [] - - # Filter für Testdaten - if not show_test: - query += " AND (r.is_test = false OR r.is_test IS NULL)" - - # Filter für Ressourcentyp - if filter_type: - query += " AND r.resource_type = %s" - params.append(filter_type) - - # Filter für Status - if filter_status: - query += " AND r.status = %s" - params.append(filter_status) - - # Suchfilter - if search_query: - query += " AND (r.resource_value ILIKE %s OR l.license_key ILIKE %s OR c.name ILIKE %s)" - params.extend([f'%{search_query}%', f'%{search_query}%', f'%{search_query}%']) - - query += " ORDER BY r.id DESC" - - cur.execute(query, params) - resources = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for res in resources: - status_text = { - 'available': 'Verfügbar', - 'allocated': 'Zugewiesen', - 'quarantine': 'Quarantäne' - }.get(res[3], res[3]) - - type_text = { - 'domain': 'Domain', - 'ipv4': 'IPv4', - 'phone': 'Telefon' - }.get(res[1], res[1]) - - data.append({ - 'ID': res[0], - 'Typ': type_text, - 'Ressource': res[2], - 'Status': status_text, - 'Lizenzschlüssel': res[7] or '', - 'Kunde': res[8] or '', - 'Kunden-Email': res[9] or '', - 'Lizenztyp': res[10] or '', - 'Erstellt am': res[5].strftime('%d.%m.%Y %H:%M:%S') if res[5] else '', - 'Zugewiesen am': res[6].strftime('%d.%m.%Y %H:%M:%S') if res[6] else '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'resources_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'resources', - additional_info=f"{export_format.upper()} Export mit {len(data)} Ressourcen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Resources') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Resources'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/audit") -@login_required -def audit_log(): - conn = get_connection() - cur = conn.cursor() - - # Parameter - filter_user = request.args.get('user', '').strip() - filter_action = request.args.get('action', '').strip() - filter_entity = request.args.get('entity', '').strip() - page = request.args.get('page', 1, type=int) - sort = request.args.get('sort', 'timestamp') - order = request.args.get('order', 'desc') - per_page = 50 - - # Whitelist für erlaubte Sortierfelder - allowed_sort_fields = { - 'timestamp': 'timestamp', - 'username': 'username', - 'action': 'action', - 'entity': 'entity_type', - 'ip': 'ip_address' - } - - # Validierung - if sort not in allowed_sort_fields: - sort = 'timestamp' - if order not in ['asc', 'desc']: - order = 'desc' - - sort_field = allowed_sort_fields[sort] - - # SQL Query mit optionalen Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - - params = [] - - # Filter - if filter_user: - query += " AND LOWER(username) LIKE LOWER(%s)" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - # Gesamtanzahl für Pagination - count_query = "SELECT COUNT(*) FROM (" + query + ") as count_table" - cur.execute(count_query, params) - total = cur.fetchone()[0] - - # Pagination - offset = (page - 1) * per_page - query += f" ORDER BY {sort_field} {order.upper()} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - logs = cur.fetchall() - - # JSON-Werte parsen - parsed_logs = [] - for log in logs: - parsed_log = list(log) - # old_values und new_values sind bereits Dictionaries (JSONB) - # Keine Konvertierung nötig - parsed_logs.append(parsed_log) - - # Pagination Info - total_pages = (total + per_page - 1) // per_page - - cur.close() - conn.close() - - return render_template("audit_log.html", - logs=parsed_logs, - filter_user=filter_user, - filter_action=filter_action, - filter_entity=filter_entity, - page=page, - total_pages=total_pages, - total=total, - sort=sort, - order=order, - username=session.get('username')) - -@app.route("/backups") -@login_required -def backups(): - """Zeigt die Backup-Historie an""" - conn = get_connection() - cur = conn.cursor() - - # Letztes erfolgreiches Backup für Dashboard - cur.execute(""" - SELECT created_at, filesize, duration_seconds - FROM backup_history - WHERE status = 'success' - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup = cur.fetchone() - - # Alle Backups abrufen - cur.execute(""" - SELECT id, filename, filesize, backup_type, status, error_message, - created_at, created_by, tables_count, records_count, - duration_seconds, is_encrypted - FROM backup_history - ORDER BY created_at DESC - """) - backups = cur.fetchall() - - cur.close() - conn.close() - - return render_template("backups.html", - backups=backups, - last_backup=last_backup, - username=session.get('username')) - -@app.route("/backup/create", methods=["POST"]) -@login_required -def create_backup_route(): - """Erstellt ein manuelles Backup""" - username = session.get('username') - success, result = create_backup(backup_type="manual", created_by=username) - - if success: - return jsonify({ - 'success': True, - 'message': f'Backup erfolgreich erstellt: {result}' - }) - else: - return jsonify({ - 'success': False, - 'message': f'Backup fehlgeschlagen: {result}' - }), 500 - -@app.route("/backup/restore/", methods=["POST"]) -@login_required -def restore_backup_route(backup_id): - """Stellt ein Backup wieder her""" - encryption_key = request.form.get('encryption_key') - - success, message = restore_backup(backup_id, encryption_key) - - if success: - return jsonify({ - 'success': True, - 'message': message - }) - else: - return jsonify({ - 'success': False, - 'message': message - }), 500 - -@app.route("/backup/download/") -@login_required -def download_backup(backup_id): - """Lädt eine Backup-Datei herunter""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - cur.close() - conn.close() - - if not backup_info: - return "Backup nicht gefunden", 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - if not filepath.exists(): - return "Backup-Datei nicht gefunden", 404 - - # Audit-Log - log_audit('DOWNLOAD', 'backup', backup_id, - additional_info=f"Backup heruntergeladen: {filename}") - - return send_file(filepath, as_attachment=True, download_name=filename) - -@app.route("/backup/delete/", methods=["DELETE"]) -@login_required -def delete_backup(backup_id): - """Löscht ein Backup""" - conn = get_connection() - cur = conn.cursor() - - try: - # Backup-Informationen abrufen - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - if not backup_info: - return jsonify({ - 'success': False, - 'message': 'Backup nicht gefunden' - }), 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - # Datei löschen, wenn sie existiert - if filepath.exists(): - filepath.unlink() - - # Aus Datenbank löschen - cur.execute(""" - DELETE FROM backup_history - WHERE id = %s - """, (backup_id,)) - - conn.commit() - - # Audit-Log - log_audit('DELETE', 'backup', backup_id, - additional_info=f"Backup gelöscht: {filename}") - - return jsonify({ - 'success': True, - 'message': f'Backup "{filename}" wurde erfolgreich gelöscht' - }) - - except Exception as e: - conn.rollback() - return jsonify({ - 'success': False, - 'message': f'Fehler beim Löschen des Backups: {str(e)}' - }), 500 - finally: - cur.close() - conn.close() - -@app.route("/security/blocked-ips") -@login_required -def blocked_ips(): - """Zeigt alle gesperrten IPs an""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT - ip_address, - attempt_count, - first_attempt, - last_attempt, - blocked_until, - last_username_tried, - last_error_message - FROM login_attempts - WHERE blocked_until IS NOT NULL - ORDER BY blocked_until DESC - """) - - blocked_ips_list = [] - for ip in cur.fetchall(): - blocked_ips_list.append({ - 'ip_address': ip[0], - 'attempt_count': ip[1], - 'first_attempt': ip[2].strftime('%d.%m.%Y %H:%M'), - 'last_attempt': ip[3].strftime('%d.%m.%Y %H:%M'), - 'blocked_until': ip[4].strftime('%d.%m.%Y %H:%M'), - 'is_active': ip[4] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None), - 'last_username': ip[5], - 'last_error': ip[6] - }) - - cur.close() - conn.close() - - return render_template("blocked_ips.html", - blocked_ips=blocked_ips_list, - username=session.get('username')) - -@app.route("/security/unblock-ip", methods=["POST"]) -@login_required -def unblock_ip(): - """Entsperrt eine IP-Adresse""" - ip_address = request.form.get('ip_address') - - if ip_address: - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - UPDATE login_attempts - SET blocked_until = NULL - WHERE ip_address = %s - """, (ip_address,)) - - conn.commit() - cur.close() - conn.close() - - # Audit-Log - log_audit('UNBLOCK_IP', 'security', - additional_info=f"IP {ip_address} manuell entsperrt") - - return redirect(url_for('blocked_ips')) - -@app.route("/security/clear-attempts", methods=["POST"]) -@login_required -def clear_attempts(): - """Löscht alle Login-Versuche für eine IP""" - ip_address = request.form.get('ip_address') - - if ip_address: - reset_login_attempts(ip_address) - - # Audit-Log - log_audit('CLEAR_ATTEMPTS', 'security', - additional_info=f"Login-Versuche für IP {ip_address} zurückgesetzt") - - return redirect(url_for('blocked_ips')) - -# API Endpoints for License Management -@app.route("/api/license//toggle", methods=["POST"]) -@login_required -def toggle_license_api(license_id): - """Toggle license active status via API""" - try: - data = request.get_json() - is_active = data.get('is_active', False) - - conn = get_connection() - cur = conn.cursor() - - # Update license status - cur.execute(""" - UPDATE licenses - SET is_active = %s - WHERE id = %s - """, (is_active, license_id)) - - conn.commit() - - # Log the action - log_audit('UPDATE', 'license', license_id, - new_values={'is_active': is_active}, - additional_info=f"Lizenz {'aktiviert' if is_active else 'deaktiviert'} via Toggle") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Status erfolgreich geändert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-activate", methods=["POST"]) -@login_required -def bulk_activate_licenses(): - """Activate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = TRUE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': True, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen aktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen aktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-deactivate", methods=["POST"]) -@login_required -def bulk_deactivate_licenses(): - """Deactivate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = FALSE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': False, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen deaktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen deaktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/license//devices") -@login_required -def get_license_devices(license_id): - """Hole alle registrierten Geräte einer Lizenz""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und hole device_limit - cur.execute(""" - SELECT device_limit FROM licenses WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit = license_data[0] - - # Hole alle Geräte für diese Lizenz - cur.execute(""" - SELECT id, hardware_id, device_name, operating_system, - first_seen, last_seen, is_active, ip_address - FROM device_registrations - WHERE license_id = %s - ORDER BY is_active DESC, last_seen DESC - """, (license_id,)) - - devices = [] - for row in cur.fetchall(): - devices.append({ - 'id': row[0], - 'hardware_id': row[1], - 'device_name': row[2] or 'Unbekanntes Gerät', - 'operating_system': row[3] or 'Unbekannt', - 'first_seen': row[4].strftime('%d.%m.%Y %H:%M') if row[4] else '', - 'last_seen': row[5].strftime('%d.%m.%Y %H:%M') if row[5] else '', - 'is_active': row[6], - 'ip_address': row[7] or '-' - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'devices': devices, - 'device_limit': device_limit, - 'active_count': sum(1 for d in devices if d['is_active']) - }) - - except Exception as e: - logging.error(f"Fehler beim Abrufen der Geräte: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Abrufen der Geräte'}), 500 - -@app.route("/api/license//register-device", methods=["POST"]) -def register_device(license_id): - """Registriere ein neues Gerät für eine Lizenz""" - try: - data = request.get_json() - hardware_id = data.get('hardware_id') - device_name = data.get('device_name', '') - operating_system = data.get('operating_system', '') - - if not hardware_id: - return jsonify({'success': False, 'message': 'Hardware-ID fehlt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und aktiv ist - cur.execute(""" - SELECT device_limit, is_active, valid_until - FROM licenses - WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit, is_active, valid_until = license_data - - # Prüfe ob Lizenz aktiv und gültig ist - if not is_active: - return jsonify({'success': False, 'message': 'Lizenz ist deaktiviert'}), 403 - - if valid_until < datetime.now(ZoneInfo("Europe/Berlin")).date(): - return jsonify({'success': False, 'message': 'Lizenz ist abgelaufen'}), 403 - - # Prüfe ob Gerät bereits registriert ist - cur.execute(""" - SELECT id, is_active FROM device_registrations - WHERE license_id = %s AND hardware_id = %s - """, (license_id, hardware_id)) - existing_device = cur.fetchone() - - if existing_device: - device_id, is_device_active = existing_device - if is_device_active: - # Gerät ist bereits aktiv, update last_seen - cur.execute(""" - UPDATE device_registrations - SET last_seen = CURRENT_TIMESTAMP, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät bereits registriert', 'device_id': device_id}) - else: - # Gerät war deaktiviert, prüfe ob wir es reaktivieren können - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Reaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = TRUE, - last_seen = CURRENT_TIMESTAMP, - deactivated_at = NULL, - deactivated_by = NULL, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät reaktiviert', 'device_id': device_id}) - - # Neues Gerät - prüfe Gerätelimit - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Registriere neues Gerät - cur.execute(""" - INSERT INTO device_registrations - (license_id, hardware_id, device_name, operating_system, ip_address, user_agent) - VALUES (%s, %s, %s, %s, %s, %s) - RETURNING id - """, (license_id, hardware_id, device_name, operating_system, - get_client_ip(), request.headers.get('User-Agent', ''))) - device_id = cur.fetchone()[0] - - conn.commit() - - # Audit Log - log_audit('DEVICE_REGISTER', 'device', device_id, - new_values={'license_id': license_id, 'hardware_id': hardware_id}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich registriert', 'device_id': device_id}) - - except Exception as e: - logging.error(f"Fehler bei Geräte-Registrierung: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler bei der Registrierung'}), 500 - -@app.route("/api/license//deactivate-device/", methods=["POST"]) -@login_required -def deactivate_device(license_id, device_id): - """Deaktiviere ein registriertes Gerät""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob das Gerät zu dieser Lizenz gehört - cur.execute(""" - SELECT id FROM device_registrations - WHERE id = %s AND license_id = %s AND is_active = TRUE - """, (device_id, license_id)) - - if not cur.fetchone(): - return jsonify({'success': False, 'message': 'Gerät nicht gefunden oder bereits deaktiviert'}), 404 - - # Deaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = FALSE, - deactivated_at = CURRENT_TIMESTAMP, - deactivated_by = %s - WHERE id = %s - """, (session['username'], device_id)) - - conn.commit() - - # Audit Log - log_audit('DEVICE_DEACTIVATE', 'device', device_id, - old_values={'is_active': True}, - new_values={'is_active': False}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich deaktiviert'}) - - except Exception as e: - logging.error(f"Fehler beim Deaktivieren des Geräts: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Deaktivieren'}), 500 - -@app.route("/api/licenses/bulk-delete", methods=["POST"]) -@login_required -def bulk_delete_licenses(): - """Delete multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Get license info for audit log (nur Live-Daten) - cur.execute(""" - SELECT license_key - FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - license_keys = [row[0] for row in cur.fetchall()] - - # Delete all selected licenses (nur Live-Daten) - cur.execute(""" - DELETE FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_DELETE', 'licenses', None, - old_values={'license_keys': license_keys, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen gelöscht") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen gelöscht'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# ===================== RESOURCE POOL MANAGEMENT ===================== - -@app.route('/resources') -@login_required -def resources(): - """Resource Pool Hauptübersicht""" - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Testdaten angezeigt werden sollen (gleiche Logik wie bei Kunden) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - # Statistiken abrufen - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = %s - GROUP BY resource_type - """, (show_test,)) - - stats = {} - for row in cur.fetchall(): - stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - } - - # Letzte Aktivitäten (gefiltert nach Test/Live) - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rp.resource_type, - rp.resource_value, - rh.details - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - WHERE rp.is_test = %s - ORDER BY rh.action_at DESC - LIMIT 10 - """, (show_test,)) - recent_activities = cur.fetchall() - - # Ressourcen-Liste mit Pagination - page = request.args.get('page', 1, type=int) - per_page = 50 - offset = (page - 1) * per_page - - resource_type = request.args.get('type', '') - status_filter = request.args.get('status', '') - search = request.args.get('search', '') - - # Sortierung - sort_by = request.args.get('sort', 'id') - sort_order = request.args.get('order', 'desc') - - # Base Query - query = """ - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - rp.allocated_to_license, - l.license_key, - c.name as customer_name, - rp.status_changed_at, - rp.quarantine_reason, - rp.quarantine_until, - c.id as customer_id - FROM resource_pools rp - LEFT JOIN licenses l ON rp.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rp.is_test = %s - """ - params = [show_test] - - if resource_type: - query += " AND rp.resource_type = %s" - params.append(resource_type) - - if status_filter: - query += " AND rp.status = %s" - params.append(status_filter) - - if search: - query += " AND rp.resource_value ILIKE %s" - params.append(f'%{search}%') - - # Count total - count_query = f"SELECT COUNT(*) FROM ({query}) as cnt" - cur.execute(count_query, params) - total = cur.fetchone()[0] - total_pages = (total + per_page - 1) // per_page - - # Get paginated results with dynamic sorting - sort_column_map = { - 'id': 'rp.id', - 'type': 'rp.resource_type', - 'resource': 'rp.resource_value', - 'status': 'rp.status', - 'assigned': 'c.name', - 'changed': 'rp.status_changed_at' - } - - sort_column = sort_column_map.get(sort_by, 'rp.id') - sort_direction = 'ASC' if sort_order == 'asc' else 'DESC' - - query += f" ORDER BY {sort_column} {sort_direction} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - resources = cur.fetchall() - - cur.close() - conn.close() - - return render_template('resources.html', - stats=stats, - resources=resources, - recent_activities=recent_activities, - page=page, - total_pages=total_pages, - total=total, - resource_type=resource_type, - status_filter=status_filter, - search=search, - show_test=show_test, - sort_by=sort_by, - sort_order=sort_order, - datetime=datetime, - timedelta=timedelta) - -@app.route('/resources/add', methods=['GET', 'POST']) -@login_required -def add_resources(): - """Ressourcen zum Pool hinzufügen""" - # Hole show_test Parameter für die Anzeige - show_test = request.args.get('show_test', 'false').lower() == 'true' - - if request.method == 'POST': - resource_type = request.form.get('resource_type') - resources_text = request.form.get('resources_text', '') - is_test = request.form.get('is_test') == 'on' # Checkbox für Testdaten - - # Parse resources (one per line) - resources = [r.strip() for r in resources_text.split('\n') if r.strip()] - - if not resources: - flash('Keine Ressourcen angegeben', 'error') - return redirect(url_for('add_resources', show_test=show_test)) - - conn = get_connection() - cur = conn.cursor() - - added = 0 - duplicates = 0 - - for resource_value in resources: - try: - cur.execute(""" - INSERT INTO resource_pools (resource_type, resource_value, status_changed_by, is_test) - VALUES (%s, %s, %s, %s) - ON CONFLICT (resource_type, resource_value) DO NOTHING - """, (resource_type, resource_value, session['username'], is_test)) - - if cur.rowcount > 0: - added += 1 - # Get the inserted ID - cur.execute("SELECT id FROM resource_pools WHERE resource_type = %s AND resource_value = %s", - (resource_type, resource_value)) - resource_id = cur.fetchone()[0] - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'created', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - else: - duplicates += 1 - - except Exception as e: - app.logger.error(f"Error adding resource {resource_value}: {e}") - - conn.commit() - cur.close() - conn.close() - - log_audit('CREATE', 'resource_pool', None, - new_values={'type': resource_type, 'added': added, 'duplicates': duplicates, 'is_test': is_test}, - additional_info=f"{added} {'Test-' if is_test else ''}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen") - - flash(f'{added} {"Test-" if is_test else ""}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen', 'success') - return redirect(url_for('resources', show_test=show_test)) - - return render_template('add_resources.html', show_test=show_test) - -@app.route('/resources/quarantine/', methods=['POST']) -@login_required -def quarantine_resource(resource_id): - """Ressource in Quarantäne setzen""" - reason = request.form.get('reason', 'review') - until_date = request.form.get('until_date') - notes = request.form.get('notes', '') - - conn = get_connection() - cur = conn.cursor() - - # Get current resource info - cur.execute("SELECT resource_type, resource_value, status FROM resource_pools WHERE id = %s", (resource_id,)) - resource = cur.fetchone() - - if not resource: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - old_status = resource[2] - - # Update resource - cur.execute(""" - UPDATE resource_pools - SET status = 'quarantine', - quarantine_reason = %s, - quarantine_until = %s, - notes = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (reason, until_date if until_date else None, notes, session['username'], resource_id)) - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address, details) - VALUES (%s, 'quarantined', %s, %s, %s) - """, (resource_id, session['username'], get_client_ip(), - Json({'reason': reason, 'until': until_date, 'notes': notes, 'old_status': old_status}))) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource', resource_id, - old_values={'status': old_status}, - new_values={'status': 'quarantine', 'reason': reason}, - additional_info=f"Ressource {resource[0]}: {resource[1]} in Quarantäne") - - flash('Ressource in Quarantäne gesetzt', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/resources/release', methods=['POST']) -@login_required -def release_resources(): - """Ressourcen aus Quarantäne freigeben""" - resource_ids = request.form.getlist('resource_ids') - - if not resource_ids: - flash('Keine Ressourcen ausgewählt', 'error') - return redirect(url_for('resources')) - - conn = get_connection() - cur = conn.cursor() - - released = 0 - for resource_id in resource_ids: - cur.execute(""" - UPDATE resource_pools - SET status = 'available', - quarantine_reason = NULL, - quarantine_until = NULL, - allocated_to_license = NULL, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s AND status = 'quarantine' - """, (session['username'], resource_id)) - - if cur.rowcount > 0: - released += 1 - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'released', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource_pool', None, - new_values={'released': released}, - additional_info=f"{released} Ressourcen aus Quarantäne freigegeben") - - flash(f'{released} Ressourcen freigegeben', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/api/resources/allocate', methods=['POST']) -@login_required -def allocate_resources_api(): - """API für Ressourcen-Zuweisung bei Lizenzerstellung""" - data = request.json - license_id = data.get('license_id') - domain_count = data.get('domain_count', 1) - ipv4_count = data.get('ipv4_count', 1) - phone_count = data.get('phone_count', 1) - - conn = get_connection() - cur = conn.cursor() - - try: - allocated = {'domains': [], 'ipv4s': [], 'phones': []} - - # Allocate domains - if domain_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' - LIMIT %s FOR UPDATE - """, (domain_count,)) - domains = cur.fetchall() - - if len(domains) < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {len(domains)})") - - for domain_id, domain_value in domains: - # Update resource status - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], domain_id)) - - # Create assignment - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, domain_id, session['username'])) - - # Log history - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (domain_id, license_id, session['username'], get_client_ip())) - - allocated['domains'].append(domain_value) - - # Allocate IPv4s (similar logic) - if ipv4_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' - LIMIT %s FOR UPDATE - """, (ipv4_count,)) - ipv4s = cur.fetchall() - - if len(ipv4s) < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar") - - for ipv4_id, ipv4_value in ipv4s: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], ipv4_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, ipv4_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (ipv4_id, license_id, session['username'], get_client_ip())) - - allocated['ipv4s'].append(ipv4_value) - - # Allocate phones (similar logic) - if phone_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' - LIMIT %s FOR UPDATE - """, (phone_count,)) - phones = cur.fetchall() - - if len(phones) < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar") - - for phone_id, phone_value in phones: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], phone_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, phone_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (phone_id, license_id, session['username'], get_client_ip())) - - allocated['phones'].append(phone_value) - - # Update license resource counts - cur.execute(""" - UPDATE licenses - SET domain_count = %s, - ipv4_count = %s, - phone_count = %s - WHERE id = %s - """, (domain_count, ipv4_count, phone_count, license_id)) - - conn.commit() - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'allocated': allocated - }) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({ - 'success': False, - 'error': str(e) - }), 400 - -@app.route('/api/resources/check-availability', methods=['GET']) -@login_required -def check_resource_availability(): - """Prüft verfügbare Ressourcen""" - resource_type = request.args.get('type', '') - count = request.args.get('count', 10, type=int) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - conn = get_connection() - cur = conn.cursor() - - if resource_type: - # Spezifische Ressourcen für einen Typ - cur.execute(""" - SELECT id, resource_value - FROM resource_pools - WHERE status = 'available' - AND resource_type = %s - AND is_test = %s - ORDER BY resource_value - LIMIT %s - """, (resource_type, show_test, count)) - - resources = [] - for row in cur.fetchall(): - resources.append({ - 'id': row[0], - 'value': row[1] - }) - - cur.close() - conn.close() - - return jsonify({ - 'available': resources, - 'type': resource_type, - 'count': len(resources) - }) - else: - # Zusammenfassung aller Typen - cur.execute(""" - SELECT - resource_type, - COUNT(*) as available - FROM resource_pools - WHERE status = 'available' - AND is_test = %s - GROUP BY resource_type - """, (show_test,)) - - availability = {} - for row in cur.fetchall(): - availability[row[0]] = row[1] - - cur.close() - conn.close() - - return jsonify(availability) - -@app.route('/api/global-search', methods=['GET']) -@login_required -def global_search(): - """Global search API endpoint for searching customers and licenses""" - query = request.args.get('q', '').strip() - - if not query or len(query) < 2: - return jsonify({'customers': [], 'licenses': []}) - - conn = get_connection() - cur = conn.cursor() - - # Search pattern with wildcards - search_pattern = f'%{query}%' - - # Search customers - cur.execute(""" - SELECT id, name, email, company_name - FROM customers - WHERE (LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - OR LOWER(company_name) LIKE LOWER(%s)) - AND is_test = FALSE - ORDER BY name - LIMIT 5 - """, (search_pattern, search_pattern, search_pattern)) - - customers = [] - for row in cur.fetchall(): - customers.append({ - 'id': row[0], - 'name': row[1], - 'email': row[2], - 'company_name': row[3] - }) - - # Search licenses - cur.execute(""" - SELECT l.id, l.license_key, c.name as customer_name - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE LOWER(l.license_key) LIKE LOWER(%s) - AND l.is_test = FALSE - ORDER BY l.created_at DESC - LIMIT 5 - """, (search_pattern,)) - - licenses = [] - for row in cur.fetchall(): - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'customer_name': row[2] - }) - - cur.close() - conn.close() - - return jsonify({ - 'customers': customers, - 'licenses': licenses - }) - -@app.route('/resources/history/') -@login_required -def resource_history(resource_id): - """Zeigt die komplette Historie einer Ressource""" - conn = get_connection() - cur = conn.cursor() - - # Get complete resource info using named columns - cur.execute(""" - SELECT id, resource_type, resource_value, status, allocated_to_license, - status_changed_at, status_changed_by, quarantine_reason, - quarantine_until, created_at, notes - FROM resource_pools - WHERE id = %s - """, (resource_id,)) - row = cur.fetchone() - - if not row: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - # Create resource object with named attributes - resource = { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'allocated_to_license': row[4], - 'status_changed_at': row[5], - 'status_changed_by': row[6], - 'quarantine_reason': row[7], - 'quarantine_until': row[8], - 'created_at': row[9], - 'notes': row[10] - } - - # Get license info if allocated - license_info = None - if resource['allocated_to_license']: - cur.execute("SELECT license_key FROM licenses WHERE id = %s", - (resource['allocated_to_license'],)) - lic = cur.fetchone() - if lic: - license_info = {'license_key': lic[0]} - - # Get history with named columns - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rh.details, - rh.license_id, - rh.ip_address - FROM resource_history rh - WHERE rh.resource_id = %s - ORDER BY rh.action_at DESC - """, (resource_id,)) - - history = [] - for row in cur.fetchall(): - history.append({ - 'action': row[0], - 'action_by': row[1], - 'action_at': row[2], - 'details': row[3], - 'license_id': row[4], - 'ip_address': row[5] - }) - - cur.close() - conn.close() - - # Convert to object-like for template - class ResourceObj: - def __init__(self, data): - for key, value in data.items(): - setattr(self, key, value) - - resource_obj = ResourceObj(resource) - history_objs = [ResourceObj(h) for h in history] - - return render_template('resource_history.html', - resource=resource_obj, - license_info=license_info, - history=history_objs) - -@app.route('/resources/metrics') -@login_required -def resources_metrics(): - """Dashboard für Resource Metrics und Reports""" - conn = get_connection() - cur = conn.cursor() - - # Overall stats with fallback values - cur.execute(""" - SELECT - COUNT(DISTINCT resource_id) as total_resources, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(cost), 0) as total_cost, - COALESCE(SUM(revenue), 0) as total_revenue, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - """) - row = cur.fetchone() - - # Calculate ROI - roi = 0 - if row[2] > 0: # if total_cost > 0 - roi = row[3] / row[2] # revenue / cost - - stats = { - 'total_resources': row[0] or 0, - 'avg_performance': row[1] or 0, - 'total_cost': row[2] or 0, - 'total_revenue': row[3] or 0, - 'total_issues': row[4] or 0, - 'roi': roi - } - - # Performance by type - cur.execute(""" - SELECT - rp.resource_type, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COUNT(DISTINCT rp.id) as resource_count - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY rp.resource_type - ORDER BY rp.resource_type - """) - performance_by_type = cur.fetchall() - - # Utilization data - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) as total, - ROUND(COUNT(*) FILTER (WHERE status = 'allocated') * 100.0 / COUNT(*), 1) as allocated_percent - FROM resource_pools - GROUP BY resource_type - """) - utilization_rows = cur.fetchall() - utilization_data = [ - { - 'type': row[0].upper(), - 'allocated': row[1], - 'total': row[2], - 'allocated_percent': row[3] - } - for row in utilization_rows - ] - - # Top performing resources - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COALESCE(SUM(rm.revenue), 0) as total_revenue, - COALESCE(SUM(rm.cost), 1) as total_cost, - CASE - WHEN COALESCE(SUM(rm.cost), 0) = 0 THEN 0 - ELSE COALESCE(SUM(rm.revenue), 0) / COALESCE(SUM(rm.cost), 1) - END as roi - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rp.status != 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value - HAVING AVG(rm.performance_score) IS NOT NULL - ORDER BY avg_score DESC - LIMIT 10 - """) - top_rows = cur.fetchall() - top_performers = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'avg_score': row[3], - 'roi': row[6] - } - for row in top_rows - ] - - # Resources with issues - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - COALESCE(SUM(rm.issues_count), 0) as total_issues - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rm.issues_count > 0 OR rp.status = 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - HAVING SUM(rm.issues_count) > 0 - ORDER BY total_issues DESC - LIMIT 10 - """) - problem_rows = cur.fetchall() - problem_resources = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'total_issues': row[4] - } - for row in problem_rows - ] - - # Daily metrics for trend chart (last 30 days) - cur.execute(""" - SELECT - metric_date, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY metric_date - ORDER BY metric_date - """) - daily_rows = cur.fetchall() - daily_metrics = [ - { - 'date': row[0].strftime('%d.%m'), - 'performance': float(row[1]), - 'issues': int(row[2]) - } - for row in daily_rows - ] - - cur.close() - conn.close() - - return render_template('resource_metrics.html', - stats=stats, - performance_by_type=performance_by_type, - utilization_data=utilization_data, - top_performers=top_performers, - problem_resources=problem_resources, - daily_metrics=daily_metrics) - -@app.route('/resources/report', methods=['GET']) -@login_required -def resources_report(): - """Generiert Ressourcen-Reports oder zeigt Report-Formular""" - # Prüfe ob Download angefordert wurde - if request.args.get('download') == 'true': - report_type = request.args.get('type', 'usage') - format_type = request.args.get('format', 'excel') - date_from = request.args.get('from', (datetime.now(ZoneInfo("Europe/Berlin")) - timedelta(days=30)).strftime('%Y-%m-%d')) - date_to = request.args.get('to', datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y-%m-%d')) - - conn = get_connection() - cur = conn.cursor() - - if report_type == 'usage': - # Auslastungsreport - query = """ - SELECT - rp.resource_type, - rp.resource_value, - rp.status, - COUNT(DISTINCT rh.license_id) as unique_licenses, - COUNT(rh.id) as total_allocations, - MIN(rh.action_at) as first_used, - MAX(rh.action_at) as last_used - FROM resource_pools rp - LEFT JOIN resource_history rh ON rp.id = rh.resource_id - AND rh.action = 'allocated' - AND rh.action_at BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - ORDER BY rp.resource_type, total_allocations DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Status', 'Unique Lizenzen', 'Gesamt Zuweisungen', 'Erste Nutzung', 'Letzte Nutzung'] - - elif report_type == 'performance': - # Performance-Report - query = """ - SELECT - rp.resource_type, - rp.resource_value, - AVG(rm.performance_score) as avg_performance, - SUM(rm.usage_count) as total_usage, - SUM(rm.revenue) as total_revenue, - SUM(rm.cost) as total_cost, - SUM(rm.revenue - rm.cost) as profit, - SUM(rm.issues_count) as total_issues - FROM resource_pools rp - JOIN resource_metrics rm ON rp.id = rm.resource_id - WHERE rm.metric_date BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value - ORDER BY profit DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Durchschn. Performance', 'Gesamt Nutzung', 'Umsatz', 'Kosten', 'Gewinn', 'Issues'] - - elif report_type == 'compliance': - # Compliance-Report - query = """ - SELECT - rh.action_at, - rh.action, - rh.action_by, - rp.resource_type, - rp.resource_value, - l.license_key, - c.name as customer_name, - rh.ip_address - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - LEFT JOIN licenses l ON rh.license_id = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rh.action_at BETWEEN %s AND %s - ORDER BY rh.action_at DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Zeit', 'Aktion', 'Von', 'Typ', 'Ressource', 'Lizenz', 'Kunde', 'IP-Adresse'] - - else: # inventory report - # Inventar-Report - query = """ - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - GROUP BY resource_type - ORDER BY resource_type - """ - cur.execute(query) - columns = ['Typ', 'Verfügbar', 'Zugeteilt', 'Quarantäne', 'Gesamt'] - - # Convert to DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - cur.close() - conn.close() - - # Generate file - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f"resource_report_{report_type}_{timestamp}" - - if format_type == 'excel': - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Report', index=False) - - # Auto-adjust columns width - worksheet = writer.sheets['Report'] - for column in worksheet.columns: - max_length = 0 - column = [cell for cell in column] - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = (max_length + 2) - worksheet.column_dimensions[column[0].column_letter].width = adjusted_width - - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'excel', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx') - - else: # CSV - output = io.StringIO() - df.to_csv(output, index=False, sep=';', encoding='utf-8-sig') - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'csv', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv') - - # Wenn kein Download, zeige Report-Formular - return render_template('resource_report.html', - datetime=datetime, - timedelta=timedelta, - username=session.get('username')) - -if __name__ == "__main__": - app.run(host="0.0.0.0", port=5000) diff --git a/v2_adminpanel/app.py.backup_20250616_233145 b/v2_adminpanel/app.py.backup_20250616_233145 deleted file mode 100644 index 0622714..0000000 --- a/v2_adminpanel/app.py.backup_20250616_233145 +++ /dev/null @@ -1,4461 +0,0 @@ -import os -import sys -import time -import json -import logging -import requests -import re -import random -import base64 -from io import BytesIO -from datetime import datetime, timedelta -from zoneinfo import ZoneInfo -from pathlib import Path - -# Add current directory to Python path to ensure modules can be imported -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from flask import Flask, render_template, request, redirect, session, url_for, send_file, jsonify, flash -from flask_session import Session -from werkzeug.middleware.proxy_fix import ProxyFix -from apscheduler.schedulers.background import BackgroundScheduler -import pandas as pd -from psycopg2.extras import Json - -# Import our new modules -import config -from db import get_connection, get_db_connection, get_db_cursor, execute_query -from auth.decorators import login_required -from auth.password import hash_password, verify_password -from auth.two_factor import ( - generate_totp_secret, generate_qr_code, verify_totp, - generate_backup_codes, hash_backup_code, verify_backup_code -) -from auth.rate_limiting import ( - check_ip_blocked, record_failed_attempt, - reset_login_attempts, get_login_attempts -) -from utils.network import get_client_ip -from utils.audit import log_audit -from utils.license import generate_license_key, validate_license_key -from utils.backup import create_backup, restore_backup, get_or_create_encryption_key -from utils.export import ( - create_excel_export, format_datetime_for_export, - prepare_license_export_data, prepare_customer_export_data, - prepare_session_export_data, prepare_audit_export_data -) -from models import get_user_by_username - -app = Flask(__name__) -# Load configuration from config module -app.config['SECRET_KEY'] = config.SECRET_KEY -app.config['SESSION_TYPE'] = config.SESSION_TYPE -app.config['JSON_AS_ASCII'] = config.JSON_AS_ASCII -app.config['JSONIFY_MIMETYPE'] = config.JSONIFY_MIMETYPE -app.config['PERMANENT_SESSION_LIFETIME'] = config.PERMANENT_SESSION_LIFETIME -app.config['SESSION_COOKIE_HTTPONLY'] = config.SESSION_COOKIE_HTTPONLY -app.config['SESSION_COOKIE_SECURE'] = config.SESSION_COOKIE_SECURE -app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE -app.config['SESSION_COOKIE_NAME'] = config.SESSION_COOKIE_NAME -app.config['SESSION_REFRESH_EACH_REQUEST'] = config.SESSION_REFRESH_EACH_REQUEST -Session(app) - -# ProxyFix für korrekte IP-Adressen hinter Nginx -app.wsgi_app = ProxyFix( - app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 -) - -# Configuration is now loaded from config module - -# Scheduler für automatische Backups -scheduler = BackgroundScheduler() -scheduler.start() - -# Logging konfigurieren -logging.basicConfig(level=logging.INFO) - -# Import and register blueprints -from routes.auth_routes import auth_bp -from routes.admin_routes import admin_bp - -# Temporarily comment out blueprints to avoid conflicts -# app.register_blueprint(auth_bp) -# app.register_blueprint(admin_bp) - - -# Scheduled Backup Job -def scheduled_backup(): - """Führt ein geplantes Backup aus""" - logging.info("Starte geplantes Backup...") - create_backup(backup_type="scheduled", created_by="scheduler") - -# Scheduler konfigurieren - täglich um 3:00 Uhr -scheduler.add_job( - scheduled_backup, - 'cron', - hour=config.SCHEDULER_CONFIG['backup_hour'], - minute=config.SCHEDULER_CONFIG['backup_minute'], - id='daily_backup', - replace_existing=True -) - - -def verify_recaptcha(response): - """Verifiziert die reCAPTCHA v2 Response mit Google""" - secret_key = config.RECAPTCHA_SECRET_KEY - - # Wenn kein Secret Key konfiguriert ist, CAPTCHA als bestanden werten (für PoC) - if not secret_key: - logging.warning("RECAPTCHA_SECRET_KEY nicht konfiguriert - CAPTCHA wird übersprungen") - return True - - # Verifizierung bei Google - try: - verify_url = 'https://www.google.com/recaptcha/api/siteverify' - data = { - 'secret': secret_key, - 'response': response - } - - # Timeout für Request setzen - r = requests.post(verify_url, data=data, timeout=5) - result = r.json() - - # Log für Debugging - if not result.get('success'): - logging.warning(f"reCAPTCHA Validierung fehlgeschlagen: {result.get('error-codes', [])}") - - return result.get('success', False) - - except requests.exceptions.RequestException as e: - logging.error(f"reCAPTCHA Verifizierung fehlgeschlagen: {str(e)}") - # Bei Netzwerkfehlern CAPTCHA als bestanden werten - return True - except Exception as e: - logging.error(f"Unerwarteter Fehler bei reCAPTCHA: {str(e)}") - return False - - -@app.route("/login", methods=["GET", "POST"]) -def login(): - # Timing-Attack Schutz - Start Zeit merken - start_time = time.time() - - # IP-Adresse ermitteln - ip_address = get_client_ip() - - # Prüfen ob IP gesperrt ist - is_blocked, blocked_until = check_ip_blocked(ip_address) - if is_blocked: - time_remaining = (blocked_until - datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None)).total_seconds() / 3600 - error_msg = f"IP GESPERRT! Noch {time_remaining:.1f} Stunden warten." - return render_template("login.html", error=error_msg, error_type="blocked") - - # Anzahl bisheriger Versuche - attempt_count = get_login_attempts(ip_address) - - if request.method == "POST": - username = request.form.get("username") - password = request.form.get("password") - captcha_response = request.form.get("g-recaptcha-response") - - # CAPTCHA-Prüfung nur wenn Keys konfiguriert sind - recaptcha_site_key = config.RECAPTCHA_SITE_KEY - if attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and recaptcha_site_key: - if not captcha_response: - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA ERFORDERLICH!", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # CAPTCHA validieren - if not verify_recaptcha(captcha_response): - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA UNGÜLTIG! Bitte erneut versuchen.", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # Check user in database first, fallback to env vars - user = get_user_by_username(username) - login_success = False - needs_2fa = False - - if user: - # Database user authentication - if verify_password(password, user['password_hash']): - login_success = True - needs_2fa = user['totp_enabled'] - else: - # Fallback to environment variables for backward compatibility - if username in config.ADMIN_USERS and password == config.ADMIN_USERS[username]: - login_success = True - - # Timing-Attack Schutz - Mindestens 1 Sekunde warten - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - - if login_success: - # Erfolgreicher Login - if needs_2fa: - # Store temporary session for 2FA verification - session['temp_username'] = username - session['temp_user_id'] = user['id'] - session['awaiting_2fa'] = True - return redirect(url_for('verify_2fa')) - else: - # Complete login without 2FA - session.permanent = True # Aktiviert das Timeout - session['logged_in'] = True - session['username'] = username - session['user_id'] = user['id'] if user else None - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - reset_login_attempts(ip_address) - log_audit('LOGIN_SUCCESS', 'user', - additional_info=f"Erfolgreiche Anmeldung von IP: {ip_address}") - return redirect(url_for('dashboard')) - else: - # Fehlgeschlagener Login - error_message = record_failed_attempt(ip_address, username) - new_attempt_count = get_login_attempts(ip_address) - - # Prüfen ob jetzt gesperrt - is_now_blocked, _ = check_ip_blocked(ip_address) - if is_now_blocked: - log_audit('LOGIN_BLOCKED', 'security', - additional_info=f"IP {ip_address} wurde nach {config.MAX_LOGIN_ATTEMPTS} Versuchen gesperrt") - - return render_template("login.html", - error=error_message, - show_captcha=(new_attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - error_type="failed", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - new_attempt_count), - recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - - # GET Request - return render_template("login.html", - show_captcha=(attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - -@app.route("/logout") -def logout(): - username = session.get('username', 'unknown') - log_audit('LOGOUT', 'user', additional_info=f"Abmeldung") - session.pop('logged_in', None) - session.pop('username', None) - session.pop('user_id', None) - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - return redirect(url_for('login')) - -@app.route("/verify-2fa", methods=["GET", "POST"]) -def verify_2fa(): - if not session.get('awaiting_2fa'): - return redirect(url_for('login')) - - if request.method == "POST": - token = request.form.get('token', '').replace(' ', '') - username = session.get('temp_username') - user_id = session.get('temp_user_id') - - if not username or not user_id: - flash('Session expired. Please login again.', 'error') - return redirect(url_for('login')) - - user = get_user_by_username(username) - if not user: - flash('User not found.', 'error') - return redirect(url_for('login')) - - # Check if it's a backup code - if len(token) == 8 and token.isupper(): - # Try backup code - backup_codes = json.loads(user['backup_codes']) if user['backup_codes'] else [] - if verify_backup_code(token, backup_codes): - # Remove used backup code - code_hash = hash_backup_code(token) - backup_codes.remove(code_hash) - - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET backup_codes = %s WHERE id = %s", - (json.dumps(backup_codes), user_id)) - conn.commit() - cur.close() - conn.close() - - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - flash('Login successful using backup code. Please generate new backup codes.', 'warning') - log_audit('LOGIN_2FA_BACKUP', 'user', additional_info=f"2FA login with backup code") - return redirect(url_for('dashboard')) - else: - # Try TOTP token - if verify_totp(user['totp_secret'], token): - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - log_audit('LOGIN_2FA_SUCCESS', 'user', additional_info=f"2FA login successful") - return redirect(url_for('dashboard')) - - # Failed verification - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET failed_2fa_attempts = failed_2fa_attempts + 1, last_failed_2fa = %s WHERE id = %s", - (datetime.now(), user_id)) - conn.commit() - cur.close() - conn.close() - - flash('Invalid authentication code. Please try again.', 'error') - log_audit('LOGIN_2FA_FAILED', 'user', additional_info=f"Failed 2FA attempt") - - return render_template('verify_2fa.html') - -@app.route("/profile") -@login_required -def profile(): - user = get_user_by_username(session['username']) - if not user: - # For environment-based users, redirect with message - flash('Bitte führen Sie das Migrations-Script aus, um Passwort-Änderung und 2FA zu aktivieren.', 'info') - return redirect(url_for('dashboard')) - return render_template('profile.html', user=user) - -@app.route("/profile/change-password", methods=["POST"]) -@login_required -def change_password(): - current_password = request.form.get('current_password') - new_password = request.form.get('new_password') - confirm_password = request.form.get('confirm_password') - - user = get_user_by_username(session['username']) - - # Verify current password - if not verify_password(current_password, user['password_hash']): - flash('Current password is incorrect.', 'error') - return redirect(url_for('profile')) - - # Check new password - if new_password != confirm_password: - flash('New passwords do not match.', 'error') - return redirect(url_for('profile')) - - if len(new_password) < 8: - flash('Password must be at least 8 characters long.', 'error') - return redirect(url_for('profile')) - - # Update password - new_hash = hash_password(new_password) - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET password_hash = %s, last_password_change = %s WHERE id = %s", - (new_hash, datetime.now(), user['id'])) - conn.commit() - cur.close() - conn.close() - - log_audit('PASSWORD_CHANGE', 'user', entity_id=user['id'], - additional_info="Password changed successfully") - flash('Password changed successfully.', 'success') - return redirect(url_for('profile')) - -@app.route("/profile/setup-2fa") -@login_required -def setup_2fa(): - user = get_user_by_username(session['username']) - - if user['totp_enabled']: - flash('2FA is already enabled for your account.', 'info') - return redirect(url_for('profile')) - - # Generate new TOTP secret - totp_secret = generate_totp_secret() - session['temp_totp_secret'] = totp_secret - - # Generate QR code - qr_code = generate_qr_code(user['username'], totp_secret) - - return render_template('setup_2fa.html', - totp_secret=totp_secret, - qr_code=qr_code) - -@app.route("/profile/enable-2fa", methods=["POST"]) -@login_required -def enable_2fa(): - token = request.form.get('token', '').replace(' ', '') - totp_secret = session.get('temp_totp_secret') - - if not totp_secret: - flash('2FA setup session expired. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Verify the token - if not verify_totp(totp_secret, token): - flash('Invalid authentication code. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Generate backup codes - backup_codes = generate_backup_codes() - hashed_codes = [hash_backup_code(code) for code in backup_codes] - - # Enable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_secret = %s, totp_enabled = TRUE, backup_codes = %s - WHERE username = %s - """, (totp_secret, json.dumps(hashed_codes), session['username'])) - conn.commit() - cur.close() - conn.close() - - session.pop('temp_totp_secret', None) - - log_audit('2FA_ENABLED', 'user', additional_info="2FA enabled successfully") - - # Show backup codes - return render_template('backup_codes.html', backup_codes=backup_codes) - -@app.route("/profile/disable-2fa", methods=["POST"]) -@login_required -def disable_2fa(): - password = request.form.get('password') - user = get_user_by_username(session['username']) - - # Verify password - if not verify_password(password, user['password_hash']): - flash('Incorrect password.', 'error') - return redirect(url_for('profile')) - - # Disable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_enabled = FALSE, totp_secret = NULL, backup_codes = NULL - WHERE username = %s - """, (session['username'],)) - conn.commit() - cur.close() - conn.close() - - log_audit('2FA_DISABLED', 'user', additional_info="2FA disabled") - flash('2FA has been disabled for your account.', 'success') - return redirect(url_for('profile')) - -@app.route("/heartbeat", methods=['POST']) -@login_required -def heartbeat(): - """Endpoint für Session Keep-Alive - aktualisiert last_activity""" - # Aktualisiere last_activity nur wenn explizit angefordert - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # Force session save - session.modified = True - - return jsonify({ - 'status': 'ok', - 'last_activity': session['last_activity'], - 'username': session.get('username') - }) - -@app.route("/api/generate-license-key", methods=['POST']) -@login_required -def api_generate_key(): - """API Endpoint zur Generierung eines neuen Lizenzschlüssels""" - try: - # Lizenztyp aus Request holen (default: full) - data = request.get_json() or {} - license_type = data.get('type', 'full') - - # Key generieren - key = generate_license_key(license_type) - - # Prüfen ob Key bereits existiert (sehr unwahrscheinlich aber sicher ist sicher) - conn = get_connection() - cur = conn.cursor() - - # Wiederhole bis eindeutiger Key gefunden - attempts = 0 - while attempts < 10: # Max 10 Versuche - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (key,)) - if not cur.fetchone(): - break # Key ist eindeutig - key = generate_license_key(license_type) - attempts += 1 - - cur.close() - conn.close() - - # Log für Audit - log_audit('GENERATE_KEY', 'license', - additional_info={'type': license_type, 'key': key}) - - return jsonify({ - 'success': True, - 'key': key, - 'type': license_type - }) - - except Exception as e: - logging.error(f"Fehler bei Key-Generierung: {str(e)}") - return jsonify({ - 'success': False, - 'error': 'Fehler bei der Key-Generierung' - }), 500 - -@app.route("/api/customers", methods=['GET']) -@login_required -def api_customers(): - """API Endpoint für die Kundensuche mit Select2""" - try: - # Suchparameter - search = request.args.get('q', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - customer_id = request.args.get('id', type=int) - - conn = get_connection() - cur = conn.cursor() - - # Einzelnen Kunden per ID abrufen - if customer_id: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.id = %s - GROUP BY c.id, c.name, c.email - """, (customer_id,)) - - customer = cur.fetchone() - results = [] - if customer: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} ({customer[2]})", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - cur.close() - conn.close() - - return jsonify({ - 'results': results, - 'pagination': {'more': False} - }) - - # SQL Query mit optionaler Suche - elif search: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE LOWER(c.name) LIKE LOWER(%s) - OR LOWER(c.email) LIKE LOWER(%s) - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (f'%{search}%', f'%{search}%', per_page, (page - 1) * per_page)) - else: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (per_page, (page - 1) * per_page)) - - customers = cur.fetchall() - - # Format für Select2 - results = [] - for customer in customers: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} - {customer[2]} ({customer[3]} Lizenzen)", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - # Gesamtanzahl für Pagination - if search: - cur.execute(""" - SELECT COUNT(*) FROM customers - WHERE LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - """, (f'%{search}%', f'%{search}%')) - else: - cur.execute("SELECT COUNT(*) FROM customers") - - total_count = cur.fetchone()[0] - - cur.close() - conn.close() - - # Select2 Response Format - return jsonify({ - 'results': results, - 'pagination': { - 'more': (page * per_page) < total_count - } - }) - - except Exception as e: - logging.error(f"Fehler bei Kundensuche: {str(e)}") - return jsonify({ - 'results': [], - 'error': 'Fehler bei der Kundensuche' - }), 500 - -@app.route("/") -@login_required -def dashboard(): - conn = get_connection() - cur = conn.cursor() - - # Statistiken abrufen - # Gesamtanzahl Kunden (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = FALSE") - total_customers = cur.fetchone()[0] - - # Gesamtanzahl Lizenzen (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = FALSE") - total_licenses = cur.fetchone()[0] - - # Aktive Lizenzen (nicht abgelaufen und is_active = true, ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE AND is_active = TRUE AND is_test = FALSE - """) - active_licenses = cur.fetchone()[0] - - # Aktive Sessions - cur.execute("SELECT COUNT(*) FROM sessions WHERE is_active = TRUE") - active_sessions_count = cur.fetchone()[0] - - # Abgelaufene Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until < CURRENT_DATE AND is_test = FALSE - """) - expired_licenses = cur.fetchone()[0] - - # Deaktivierte Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE is_active = FALSE AND is_test = FALSE - """) - inactive_licenses = cur.fetchone()[0] - - # Lizenzen die in den nächsten 30 Tagen ablaufen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE - AND valid_until < CURRENT_DATE + INTERVAL '30 days' - AND is_active = TRUE - AND is_test = FALSE - """) - expiring_soon = cur.fetchone()[0] - - # Testlizenzen vs Vollversionen (ohne Testdaten) - cur.execute(""" - SELECT license_type, COUNT(*) - FROM licenses - WHERE is_test = FALSE - GROUP BY license_type - """) - license_types = dict(cur.fetchall()) - - # Anzahl Testdaten - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = TRUE") - test_data_count = cur.fetchone()[0] - - # Anzahl Test-Kunden - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = TRUE") - test_customers_count = cur.fetchone()[0] - - # Anzahl Test-Ressourcen - cur.execute("SELECT COUNT(*) FROM resource_pools WHERE is_test = TRUE") - test_resources_count = cur.fetchone()[0] - - # Letzte 5 erstellten Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.is_test = FALSE - ORDER BY l.id DESC - LIMIT 5 - """) - recent_licenses = cur.fetchall() - - # Bald ablaufende Lizenzen (nächste 30 Tage, ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - l.valid_until - CURRENT_DATE as days_left - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.valid_until >= CURRENT_DATE - AND l.valid_until < CURRENT_DATE + INTERVAL '30 days' - AND l.is_active = TRUE - AND l.is_test = FALSE - ORDER BY l.valid_until - LIMIT 10 - """) - expiring_licenses = cur.fetchall() - - # Letztes Backup - cur.execute(""" - SELECT created_at, filesize, duration_seconds, backup_type, status - FROM backup_history - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup_info = cur.fetchone() - - # Sicherheitsstatistiken - # Gesperrte IPs - cur.execute(""" - SELECT COUNT(*) FROM login_attempts - WHERE blocked_until IS NOT NULL AND blocked_until > CURRENT_TIMESTAMP - """) - blocked_ips_count = cur.fetchone()[0] - - # Fehlversuche heute - cur.execute(""" - SELECT COALESCE(SUM(attempt_count), 0) FROM login_attempts - WHERE last_attempt::date = CURRENT_DATE - """) - failed_attempts_today = cur.fetchone()[0] - - # Letzte 5 Sicherheitsereignisse - cur.execute(""" - SELECT - la.ip_address, - la.attempt_count, - la.last_attempt, - la.blocked_until, - la.last_username_tried, - la.last_error_message - FROM login_attempts la - ORDER BY la.last_attempt DESC - LIMIT 5 - """) - recent_security_events = [] - for event in cur.fetchall(): - recent_security_events.append({ - 'ip_address': event[0], - 'attempt_count': event[1], - 'last_attempt': event[2].strftime('%d.%m %H:%M'), - 'blocked_until': event[3].strftime('%d.%m %H:%M') if event[3] and event[3] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) else None, - 'username_tried': event[4], - 'error_message': event[5] - }) - - # Sicherheitslevel berechnen - if blocked_ips_count > 5 or failed_attempts_today > 50: - security_level = 'danger' - security_level_text = 'KRITISCH' - elif blocked_ips_count > 2 or failed_attempts_today > 20: - security_level = 'warning' - security_level_text = 'ERHÖHT' - else: - security_level = 'success' - security_level_text = 'NORMAL' - - # Resource Pool Statistiken (nur Live-Daten, keine Testdaten) - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = FALSE - GROUP BY resource_type - """) - - resource_stats = {} - resource_warning = None - - for row in cur.fetchall(): - available_percent = round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - resource_stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': available_percent, - 'warning_level': 'danger' if row[1] < 50 else 'warning' if row[1] < 100 else 'success' - } - - # Warnung bei niedrigem Bestand - if row[1] < 50: - if not resource_warning: - resource_warning = f"Niedriger Bestand bei {row[0].upper()}: nur noch {row[1]} verfügbar!" - else: - resource_warning += f" | {row[0].upper()}: {row[1]}" - - cur.close() - conn.close() - - stats = { - 'total_customers': total_customers, - 'total_licenses': total_licenses, - 'active_licenses': active_licenses, - 'expired_licenses': expired_licenses, - 'inactive_licenses': inactive_licenses, - 'expiring_soon': expiring_soon, - 'full_licenses': license_types.get('full', 0), - 'test_licenses': license_types.get('test', 0), - 'test_data_count': test_data_count, - 'test_customers_count': test_customers_count, - 'test_resources_count': test_resources_count, - 'recent_licenses': recent_licenses, - 'expiring_licenses': expiring_licenses, - 'active_sessions': active_sessions_count, - 'last_backup': last_backup_info, - # Sicherheitsstatistiken - 'blocked_ips_count': blocked_ips_count, - 'failed_attempts_today': failed_attempts_today, - 'recent_security_events': recent_security_events, - 'security_level': security_level, - 'security_level_text': security_level_text, - 'resource_stats': resource_stats - } - - return render_template("dashboard.html", - stats=stats, - resource_stats=resource_stats, - resource_warning=resource_warning, - username=session.get('username')) - -@app.route("/create", methods=["GET", "POST"]) -@login_required -def create_license(): - if request.method == "POST": - customer_id = request.form.get("customer_id") - license_key = request.form["license_key"].upper() # Immer Großbuchstaben - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Validiere License Key Format - if not validate_license_key(license_key): - flash('Ungültiges License Key Format! Erwartet: AF-YYYYMMFT-XXXX-YYYY-ZZZZ', 'error') - return redirect(url_for('create_license')) - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('create_license')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('create_license')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - customer_info = {'name': name, 'email': email, 'is_test': is_test} - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos für Audit-Log - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('create_license')) - customer_info = {'name': customer_data[0], 'email': customer_data[1]} - - # Wenn Kunde Test-Kunde ist, Lizenz auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Lizenz hinzufügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit, is_test) - VALUES (%s, %s, %s, %s, %s, TRUE, %s, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit, is_test)) - license_id = cur.fetchone()[0] - - # Ressourcen zuweisen - try: - # Prüfe Verfügbarkeit - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {available[0]})") - if available[1] < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {ipv4_count}, verfügbar: {available[1]})") - if available[2] < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar (benötigt: {phone_count}, verfügbar: {available[2]})") - - # Domains zuweisen - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s zuweisen - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern zuweisen - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - except ValueError as e: - conn.rollback() - flash(str(e), 'error') - return redirect(url_for('create_license')) - - conn.commit() - - # Audit-Log - log_audit('CREATE', 'license', license_id, - new_values={ - 'license_key': license_key, - 'customer_name': customer_info['name'], - 'customer_email': customer_info['email'], - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'device_limit': device_limit, - 'is_test': is_test - }) - - flash(f'Lizenz {license_key} erfolgreich erstellt!', 'success') - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Erstellen der Lizenz: {str(e)}") - flash('Fehler beim Erstellen der Lizenz!', 'error') - finally: - cur.close() - conn.close() - - # Preserve show_test parameter if present - redirect_url = "/create" - if request.args.get('show_test') == 'true': - redirect_url += "?show_test=true" - return redirect(redirect_url) - - # Unterstützung für vorausgewählten Kunden - preselected_customer_id = request.args.get('customer_id', type=int) - return render_template("index.html", username=session.get('username'), preselected_customer_id=preselected_customer_id) - -@app.route("/batch", methods=["GET", "POST"]) -@login_required -def batch_licenses(): - """Batch-Generierung mehrerer Lizenzen für einen Kunden""" - if request.method == "POST": - # Formulardaten - customer_id = request.form.get("customer_id") - license_type = request.form["license_type"] - quantity = int(request.form["quantity"]) - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - # Sicherheitslimit - if quantity < 1 or quantity > 100: - flash('Anzahl muss zwischen 1 und 100 liegen!', 'error') - return redirect(url_for('batch_licenses')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('batch_licenses')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('batch_licenses')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('batch_licenses')) - name = customer_data[0] - email = customer_data[1] - - # Wenn Kunde Test-Kunde ist, Lizenzen auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Prüfe Ressourcen-Verfügbarkeit für gesamten Batch - total_domains_needed = domain_count * quantity - total_ipv4s_needed = ipv4_count * quantity - total_phones_needed = phone_count * quantity - - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < total_domains_needed: - flash(f"Nicht genügend Domains verfügbar (benötigt: {total_domains_needed}, verfügbar: {available[0]})", 'error') - return redirect(url_for('batch_licenses')) - if available[1] < total_ipv4s_needed: - flash(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {total_ipv4s_needed}, verfügbar: {available[1]})", 'error') - return redirect(url_for('batch_licenses')) - if available[2] < total_phones_needed: - flash(f"Nicht genügend Telefonnummern verfügbar (benötigt: {total_phones_needed}, verfügbar: {available[2]})", 'error') - return redirect(url_for('batch_licenses')) - - # Lizenzen generieren und speichern - generated_licenses = [] - for i in range(quantity): - # Eindeutigen Key generieren - attempts = 0 - while attempts < 10: - license_key = generate_license_key(license_type) - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (license_key,)) - if not cur.fetchone(): - break - attempts += 1 - - # Lizenz einfügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, is_test, - valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit) - VALUES (%s, %s, %s, %s, %s, %s, true, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, is_test, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit)) - license_id = cur.fetchone()[0] - - # Ressourcen für diese Lizenz zuweisen - # Domains - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - generated_licenses.append({ - 'id': license_id, - 'key': license_key, - 'type': license_type - }) - - conn.commit() - - # Audit-Log - log_audit('CREATE_BATCH', 'license', - new_values={'customer': name, 'quantity': quantity, 'type': license_type}, - additional_info=f"Batch-Generierung von {quantity} Lizenzen") - - # Session für Export speichern - session['batch_export'] = { - 'customer': name, - 'email': email, - 'licenses': generated_licenses, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'timestamp': datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - } - - flash(f'{quantity} Lizenzen erfolgreich generiert!', 'success') - return render_template("batch_result.html", - customer=name, - email=email, - licenses=generated_licenses, - valid_from=valid_from, - valid_until=valid_until) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler bei Batch-Generierung: {str(e)}") - flash('Fehler bei der Batch-Generierung!', 'error') - return redirect(url_for('batch_licenses')) - finally: - cur.close() - conn.close() - - # GET Request - return render_template("batch_form.html") - -@app.route("/batch/export") -@login_required -def export_batch(): - """Exportiert die zuletzt generierten Batch-Lizenzen""" - batch_data = session.get('batch_export') - if not batch_data: - flash('Keine Batch-Daten zum Exportieren vorhanden!', 'error') - return redirect(url_for('batch_licenses')) - - # CSV generieren - output = io.StringIO() - output.write('\ufeff') # UTF-8 BOM für Excel - - # Header - output.write(f"Kunde: {batch_data['customer']}\n") - output.write(f"E-Mail: {batch_data['email']}\n") - output.write(f"Generiert am: {datetime.fromisoformat(batch_data['timestamp']).strftime('%d.%m.%Y %H:%M')}\n") - output.write(f"Gültig von: {batch_data['valid_from']} bis {batch_data['valid_until']}\n") - output.write("\n") - output.write("Nr;Lizenzschlüssel;Typ\n") - - # Lizenzen - for i, license in enumerate(batch_data['licenses'], 1): - typ_text = "Vollversion" if license['type'] == 'full' else "Testversion" - output.write(f"{i};{license['key']};{typ_text}\n") - - output.seek(0) - - # Audit-Log - log_audit('EXPORT', 'batch_licenses', - additional_info=f"Export von {len(batch_data['licenses'])} Batch-Lizenzen") - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f"batch_licenses_{batch_data['customer'].replace(' ', '_')}_{datetime.now(ZoneInfo('Europe/Berlin')).strftime('%Y%m%d_%H%M%S')}.csv" - ) - -@app.route("/licenses") -@login_required -def licenses(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/license/edit/", methods=["GET", "POST"]) -@login_required -def edit_license(license_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute(""" - SELECT license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit - FROM licenses WHERE id = %s - """, (license_id,)) - old_license = cur.fetchone() - - # Update license - license_key = request.form["license_key"] - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - valid_until = request.form["valid_until"] - is_active = request.form.get("is_active") == "on" - is_test = request.form.get("is_test") == "on" - device_limit = int(request.form.get("device_limit", 3)) - - cur.execute(""" - UPDATE licenses - SET license_key = %s, license_type = %s, valid_from = %s, - valid_until = %s, is_active = %s, is_test = %s, device_limit = %s - WHERE id = %s - """, (license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit, license_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'license_key': old_license[0], - 'license_type': old_license[1], - 'valid_from': str(old_license[2]), - 'valid_until': str(old_license[3]), - 'is_active': old_license[4], - 'is_test': old_license[5], - 'device_limit': old_license[6] - }, - new_values={ - 'license_key': license_key, - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'is_active': is_active, - 'is_test': is_test, - 'device_limit': device_limit - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei wenn vorhanden - if request.referrer and 'customer_id=' in request.referrer: - import re - match = re.search(r'customer_id=(\d+)', request.referrer) - if match: - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={match.group(1)}" - - return redirect(redirect_url) - - # Get license data - cur.execute(""" - SELECT l.id, l.license_key, c.name, c.email, l.license_type, - l.valid_from, l.valid_until, l.is_active, c.id, l.is_test, l.device_limit - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - - license = cur.fetchone() - cur.close() - conn.close() - - if not license: - return redirect("/licenses") - - return render_template("edit_license.html", license=license, username=session.get('username')) - -@app.route("/license/delete/", methods=["POST"]) -@login_required -def delete_license(license_id): - conn = get_connection() - cur = conn.cursor() - - # Lizenzdetails für Audit-Log abrufen - cur.execute(""" - SELECT l.license_key, c.name, l.license_type - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - license_info = cur.fetchone() - - cur.execute("DELETE FROM licenses WHERE id = %s", (license_id,)) - - conn.commit() - - # Audit-Log - if license_info: - log_audit('DELETE', 'license', license_id, - old_values={ - 'license_key': license_info[0], - 'customer_name': license_info[1], - 'license_type': license_info[2] - }) - - cur.close() - conn.close() - - return redirect("/licenses") - -@app.route("/customers") -@login_required -def customers(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/customer/edit/", methods=["GET", "POST"]) -@login_required -def edit_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - old_customer = cur.fetchone() - - # Update customer - name = request.form["name"] - email = request.form["email"] - is_test = request.form.get("is_test") == "on" - - cur.execute(""" - UPDATE customers - SET name = %s, email = %s, is_test = %s - WHERE id = %s - """, (name, email, is_test, customer_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'customer', customer_id, - old_values={ - 'name': old_customer[0], - 'email': old_customer[1], - 'is_test': old_customer[2] - }, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei (immer der aktuelle Kunde) - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={customer_id}" - - return redirect(redirect_url) - - # Get customer data with licenses - cur.execute(""" - SELECT id, name, email, created_at, is_test FROM customers WHERE id = %s - """, (customer_id,)) - - customer = cur.fetchone() - if not customer: - cur.close() - conn.close() - return "Kunde nicht gefunden", 404 - - - # Get customer's licenses - cur.execute(""" - SELECT id, license_key, license_type, valid_from, valid_until, is_active - FROM licenses - WHERE customer_id = %s - ORDER BY valid_until DESC - """, (customer_id,)) - - licenses = cur.fetchall() - - cur.close() - conn.close() - - if not customer: - return redirect("/customers-licenses") - - return render_template("edit_customer.html", customer=customer, licenses=licenses, username=session.get('username')) - -@app.route("/customer/create", methods=["GET", "POST"]) -@login_required -def create_customer(): - """Erstellt einen neuen Kunden ohne Lizenz""" - if request.method == "POST": - name = request.form.get('name') - email = request.form.get('email') - is_test = request.form.get('is_test') == 'on' - - if not name or not email: - flash("Name und E-Mail sind Pflichtfelder!", "error") - return render_template("create_customer.html", username=session.get('username')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfen ob E-Mail bereits existiert - cur.execute("SELECT id, name FROM customers WHERE email = %s", (email,)) - existing = cur.fetchone() - if existing: - flash(f"Ein Kunde mit der E-Mail '{email}' existiert bereits: {existing[1]}", "error") - return render_template("create_customer.html", username=session.get('username')) - - # Kunde erstellen - cur.execute(""" - INSERT INTO customers (name, email, created_at, is_test) - VALUES (%s, %s, %s, %s) RETURNING id - """, (name, email, datetime.now(), is_test)) - - customer_id = cur.fetchone()[0] - conn.commit() - - # Audit-Log - log_audit('CREATE', 'customer', customer_id, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - flash(f"Kunde '{name}' wurde erfolgreich angelegt!", "success") - return redirect(f"/customer/edit/{customer_id}") - - except Exception as e: - conn.rollback() - flash(f"Fehler beim Anlegen des Kunden: {str(e)}", "error") - return render_template("create_customer.html", username=session.get('username')) - finally: - cur.close() - conn.close() - - # GET Request - Formular anzeigen - return render_template("create_customer.html", username=session.get('username')) - -@app.route("/customer/delete/", methods=["POST"]) -@login_required -def delete_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - # Prüfen ob Kunde Lizenzen hat - cur.execute("SELECT COUNT(*) FROM licenses WHERE customer_id = %s", (customer_id,)) - license_count = cur.fetchone()[0] - - if license_count > 0: - # Kunde hat Lizenzen - nicht löschen - cur.close() - conn.close() - return redirect("/customers") - - # Kundendetails für Audit-Log abrufen - cur.execute("SELECT name, email FROM customers WHERE id = %s", (customer_id,)) - customer_info = cur.fetchone() - - # Kunde löschen wenn keine Lizenzen vorhanden - cur.execute("DELETE FROM customers WHERE id = %s", (customer_id,)) - - conn.commit() - - # Audit-Log - if customer_info: - log_audit('DELETE', 'customer', customer_id, - old_values={ - 'name': customer_info[0], - 'email': customer_info[1] - }) - - cur.close() - conn.close() - - return redirect("/customers") - -@app.route("/customers-licenses") -@login_required -def customers_licenses(): - """Kombinierte Ansicht für Kunden und deren Lizenzen""" - conn = get_connection() - cur = conn.cursor() - - # Hole alle Kunden mit Lizenzstatistiken (inkl. Testkunden wenn gewünscht) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - query = """ - SELECT - c.id, - c.name, - c.email, - c.created_at, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - """ - - if not show_test: - query += " WHERE c.is_test = FALSE" - - query += """ - GROUP BY c.id, c.name, c.email, c.created_at - ORDER BY c.name - """ - - cur.execute(query) - customers = cur.fetchall() - - # Hole ausgewählten Kunden nur wenn explizit in URL angegeben - selected_customer_id = request.args.get('customer_id', type=int) - licenses = [] - selected_customer = None - - if customers and selected_customer_id: - # Hole Daten des ausgewählten Kunden - for customer in customers: - if customer[0] == selected_customer_id: - selected_customer = customer - break - - # Hole Lizenzen des ausgewählten Kunden - if selected_customer: - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (selected_customer_id,)) - licenses = cur.fetchall() - - cur.close() - conn.close() - - return render_template("customers_licenses.html", - customers=customers, - selected_customer=selected_customer, - selected_customer_id=selected_customer_id, - licenses=licenses, - show_test=show_test) - -@app.route("/api/customer//licenses") -@login_required -def api_customer_licenses(customer_id): - """API-Endpoint für AJAX-Abruf der Lizenzen eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Lizenzen des Kunden - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (customer_id,)) - - licenses = [] - for row in cur.fetchall(): - license_id = row[0] - - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for res_row in cur.fetchall(): - resource_info = { - 'id': res_row[0], - 'value': res_row[2], - 'assigned_at': res_row[3].strftime('%d.%m.%Y') if res_row[3] else '' - } - - if res_row[1] == 'domain': - resources['domains'].append(resource_info) - elif res_row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif res_row[1] == 'phone': - resources['phones'].append(resource_info) - - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'license_type': row[2], - 'valid_from': row[3].strftime('%d.%m.%Y') if row[3] else '', - 'valid_until': row[4].strftime('%d.%m.%Y') if row[4] else '', - 'is_active': row[5], - 'status': row[6], - 'domain_count': row[7], # limit - 'ipv4_count': row[8], # limit - 'phone_count': row[9], # limit - 'device_limit': row[10], - 'active_devices': row[11], - 'actual_domain_count': row[12], # actual count - 'actual_ipv4_count': row[13], # actual count - 'actual_phone_count': row[14], # actual count - 'resources': resources - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'licenses': licenses, - 'count': len(licenses) - }) - -@app.route("/api/customer//quick-stats") -@login_required -def api_customer_quick_stats(customer_id): - """API-Endpoint für Schnellstatistiken eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Kundenstatistiken - cur.execute(""" - SELECT - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' AND l.valid_until >= CURRENT_DATE THEN 1 END) as expiring_soon - FROM licenses l - WHERE l.customer_id = %s - """, (customer_id,)) - - stats = cur.fetchone() - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'stats': { - 'total': stats[0], - 'active': stats[1], - 'expired': stats[2], - 'expiring_soon': stats[3] - } - }) - -@app.route("/api/license//quick-edit", methods=['POST']) -@login_required -def api_license_quick_edit(license_id): - """API-Endpoint für schnelle Lizenz-Bearbeitung""" - conn = get_connection() - cur = conn.cursor() - - try: - data = request.get_json() - - # Hole alte Werte für Audit-Log - cur.execute(""" - SELECT is_active, valid_until, license_type - FROM licenses WHERE id = %s - """, (license_id,)) - old_values = cur.fetchone() - - if not old_values: - return jsonify({'success': False, 'error': 'Lizenz nicht gefunden'}), 404 - - # Update-Felder vorbereiten - updates = [] - params = [] - new_values = {} - - if 'is_active' in data: - updates.append("is_active = %s") - params.append(data['is_active']) - new_values['is_active'] = data['is_active'] - - if 'valid_until' in data: - updates.append("valid_until = %s") - params.append(data['valid_until']) - new_values['valid_until'] = data['valid_until'] - - if 'license_type' in data: - updates.append("license_type = %s") - params.append(data['license_type']) - new_values['license_type'] = data['license_type'] - - if updates: - params.append(license_id) - cur.execute(f""" - UPDATE licenses - SET {', '.join(updates)} - WHERE id = %s - """, params) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'is_active': old_values[0], - 'valid_until': old_values[1].isoformat() if old_values[1] else None, - 'license_type': old_values[2] - }, - new_values=new_values) - - cur.close() - conn.close() - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/api/license//resources") -@login_required -def api_license_resources(license_id): - """API-Endpoint für detaillierte Ressourcen-Informationen einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for row in cur.fetchall(): - resource_info = { - 'id': row[0], - 'value': row[2], - 'assigned_at': row[3].strftime('%d.%m.%Y') if row[3] else '' - } - - if row[1] == 'domain': - resources['domains'].append(resource_info) - elif row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif row[1] == 'phone': - resources['phones'].append(resource_info) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'resources': resources - }) - - except Exception as e: - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/sessions") -@login_required -def sessions(): - conn = get_connection() - cur = conn.cursor() - - # Sortierparameter - active_sort = request.args.get('active_sort', 'last_heartbeat') - active_order = request.args.get('active_order', 'desc') - ended_sort = request.args.get('ended_sort', 'ended_at') - ended_order = request.args.get('ended_order', 'desc') - - # Whitelist für erlaubte Sortierfelder - Aktive Sessions - active_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'last_heartbeat': 's.last_heartbeat', - 'inactive': 'minutes_inactive' - } - - # Whitelist für erlaubte Sortierfelder - Beendete Sessions - ended_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'ended_at': 's.ended_at', - 'duration': 'duration_minutes' - } - - # Validierung - if active_sort not in active_sort_fields: - active_sort = 'last_heartbeat' - if ended_sort not in ended_sort_fields: - ended_sort = 'ended_at' - if active_order not in ['asc', 'desc']: - active_order = 'desc' - if ended_order not in ['asc', 'desc']: - ended_order = 'desc' - - # Aktive Sessions abrufen - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.user_agent, s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.last_heartbeat))/60 as minutes_inactive - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = TRUE - ORDER BY {active_sort_fields[active_sort]} {active_order.upper()} - """) - active_sessions = cur.fetchall() - - # Inaktive Sessions der letzten 24 Stunden - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))/60 as duration_minutes - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = FALSE - AND s.ended_at > NOW() - INTERVAL '24 hours' - ORDER BY {ended_sort_fields[ended_sort]} {ended_order.upper()} - LIMIT 50 - """) - recent_sessions = cur.fetchall() - - cur.close() - conn.close() - - return render_template("sessions.html", - active_sessions=active_sessions, - recent_sessions=recent_sessions, - active_sort=active_sort, - active_order=active_order, - ended_sort=ended_sort, - ended_order=ended_order, - username=session.get('username')) - -@app.route("/session/end/", methods=["POST"]) -@login_required -def end_session(session_id): - conn = get_connection() - cur = conn.cursor() - - # Session beenden - cur.execute(""" - UPDATE sessions - SET is_active = FALSE, ended_at = NOW() - WHERE id = %s AND is_active = TRUE - """, (session_id,)) - - conn.commit() - cur.close() - conn.close() - - return redirect("/sessions") - -@app.route("/export/licenses") -@login_required -def export_licenses(): - conn = get_connection() - cur = conn.cursor() - - # Alle Lizenzen mit Kundeninformationen abrufen (ohne Testdaten, außer explizit gewünscht) - include_test = request.args.get('include_test', 'false').lower() == 'true' - customer_id = request.args.get('customer_id', type=int) - - query = """ - SELECT l.id, l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type, l.valid_from, l.valid_until, l.is_active, l.is_test, - CASE - WHEN l.is_active = FALSE THEN 'Deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'Abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'Läuft bald ab' - ELSE 'Aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - """ - - # Build WHERE clause - where_conditions = [] - params = [] - - if not include_test: - where_conditions.append("l.is_test = FALSE") - - if customer_id: - where_conditions.append("l.customer_id = %s") - params.append(customer_id) - - if where_conditions: - query += " WHERE " + " AND ".join(where_conditions) - - query += " ORDER BY l.id" - - cur.execute(query, params) - - # Spaltennamen - columns = ['ID', 'Lizenzschlüssel', 'Kunde', 'E-Mail', 'Typ', - 'Gültig von', 'Gültig bis', 'Aktiv', 'Testdaten', 'Status'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Gültig von'] = pd.to_datetime(df['Gültig von']).dt.strftime('%d.%m.%Y') - df['Gültig bis'] = pd.to_datetime(df['Gültig bis']).dt.strftime('%d.%m.%Y') - - # Typ und Aktiv Status anpassen - df['Typ'] = df['Typ'].replace({'full': 'Vollversion', 'test': 'Testversion'}) - df['Aktiv'] = df['Aktiv'].replace({True: 'Ja', False: 'Nein'}) - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'license', - additional_info=f"Export aller Lizenzen als {export_format.upper()}") - filename = f'lizenzen_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Lizenzen', index=False) - - # Formatierung - worksheet = writer.sheets['Lizenzen'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/audit") -@login_required -def export_audit(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_user = request.args.get('user', '') - filter_action = request.args.get('action', '') - filter_entity = request.args.get('entity', '') - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - params = [] - - if filter_user: - query += " AND username ILIKE %s" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - query += " ORDER BY timestamp DESC" - - cur.execute(query, params) - audit_logs = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for log in audit_logs: - action_text = { - 'CREATE': 'Erstellt', - 'UPDATE': 'Bearbeitet', - 'DELETE': 'Gelöscht', - 'LOGIN': 'Anmeldung', - 'LOGOUT': 'Abmeldung', - 'AUTO_LOGOUT': 'Auto-Logout', - 'EXPORT': 'Export', - 'GENERATE_KEY': 'Key generiert', - 'CREATE_BATCH': 'Batch erstellt', - 'BACKUP': 'Backup erstellt', - 'LOGIN_2FA_SUCCESS': '2FA-Anmeldung', - 'LOGIN_2FA_BACKUP': '2FA-Backup-Code', - 'LOGIN_2FA_FAILED': '2FA-Fehlgeschlagen', - 'LOGIN_BLOCKED': 'Login-Blockiert', - 'RESTORE': 'Wiederhergestellt', - 'PASSWORD_CHANGE': 'Passwort geändert', - '2FA_ENABLED': '2FA aktiviert', - '2FA_DISABLED': '2FA deaktiviert' - }.get(log[3], log[3]) - - data.append({ - 'ID': log[0], - 'Zeitstempel': log[1].strftime('%d.%m.%Y %H:%M:%S'), - 'Benutzer': log[2], - 'Aktion': action_text, - 'Entität': log[4], - 'Entität-ID': log[5] or '', - 'IP-Adresse': log[8] or '', - 'Zusatzinfo': log[10] or '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'audit_log_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'audit_log', - additional_info=f"{export_format.upper()} Export mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Audit Log') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Audit Log'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/customers") -@login_required -def export_customers(): - conn = get_connection() - cur = conn.cursor() - - # Check if test data should be included - include_test = request.args.get('include_test', 'false').lower() == 'true' - - # Build query based on test data filter - if include_test: - # Include all customers - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - else: - # Exclude test customers and test licenses - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(CASE WHEN l.is_test = FALSE THEN 1 END) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.is_test = FALSE - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - - cur.execute(query) - - # Spaltennamen - columns = ['ID', 'Name', 'E-Mail', 'Erstellt am', 'Testdaten', - 'Lizenzen gesamt', 'Aktive Lizenzen', 'Abgelaufene Lizenzen'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Erstellt am'] = pd.to_datetime(df['Erstellt am']).dt.strftime('%d.%m.%Y %H:%M') - - # Testdaten formatting - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'customer', - additional_info=f"Export aller Kunden als {export_format.upper()}") - filename = f'kunden_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Kunden', index=False) - - # Formatierung - worksheet = writer.sheets['Kunden'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/sessions") -@login_required -def export_sessions(): - conn = get_connection() - cur = conn.cursor() - - # Holen des Session-Typs (active oder ended) - session_type = request.args.get('type', 'active') - export_format = request.args.get('format', 'excel') - - # Daten je nach Typ abrufen - if session_type == 'active': - # Aktive Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = true - ORDER BY s.last_heartbeat DESC - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Letzte Aktivität': sess[5].strftime('%d.%m.%Y %H:%M:%S'), - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Aktive Sessions' - filename_prefix = 'aktive_sessions' - else: - # Beendete Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = false AND s.ended_at IS NOT NULL - ORDER BY s.ended_at DESC - LIMIT 1000 - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] if sess[6] else 0 - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Endzeit': sess[5].strftime('%d.%m.%Y %H:%M:%S') if sess[5] else '', - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Beendete Sessions' - filename_prefix = 'beendete_sessions' - - cur.close() - conn.close() - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'{filename_prefix}_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'sessions', - additional_info=f"{export_format.upper()} Export von {session_type} Sessions mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name=sheet_name) - - # Spaltenbreiten anpassen - worksheet = writer.sheets[sheet_name] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/resources") -@login_required -def export_resources(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_type = request.args.get('type', '') - filter_status = request.args.get('status', '') - search_query = request.args.get('search', '') - show_test = request.args.get('show_test', 'false').lower() == 'true' - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT r.id, r.resource_type, r.resource_value, r.status, r.allocated_to_license, - r.created_at, r.status_changed_at, - l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type - FROM resource_pools r - LEFT JOIN licenses l ON r.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE 1=1 - """ - params = [] - - # Filter für Testdaten - if not show_test: - query += " AND (r.is_test = false OR r.is_test IS NULL)" - - # Filter für Ressourcentyp - if filter_type: - query += " AND r.resource_type = %s" - params.append(filter_type) - - # Filter für Status - if filter_status: - query += " AND r.status = %s" - params.append(filter_status) - - # Suchfilter - if search_query: - query += " AND (r.resource_value ILIKE %s OR l.license_key ILIKE %s OR c.name ILIKE %s)" - params.extend([f'%{search_query}%', f'%{search_query}%', f'%{search_query}%']) - - query += " ORDER BY r.id DESC" - - cur.execute(query, params) - resources = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for res in resources: - status_text = { - 'available': 'Verfügbar', - 'allocated': 'Zugewiesen', - 'quarantine': 'Quarantäne' - }.get(res[3], res[3]) - - type_text = { - 'domain': 'Domain', - 'ipv4': 'IPv4', - 'phone': 'Telefon' - }.get(res[1], res[1]) - - data.append({ - 'ID': res[0], - 'Typ': type_text, - 'Ressource': res[2], - 'Status': status_text, - 'Lizenzschlüssel': res[7] or '', - 'Kunde': res[8] or '', - 'Kunden-Email': res[9] or '', - 'Lizenztyp': res[10] or '', - 'Erstellt am': res[5].strftime('%d.%m.%Y %H:%M:%S') if res[5] else '', - 'Zugewiesen am': res[6].strftime('%d.%m.%Y %H:%M:%S') if res[6] else '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'resources_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'resources', - additional_info=f"{export_format.upper()} Export mit {len(data)} Ressourcen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Resources') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Resources'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/audit") -@login_required -def audit_log(): - conn = get_connection() - cur = conn.cursor() - - # Parameter - filter_user = request.args.get('user', '').strip() - filter_action = request.args.get('action', '').strip() - filter_entity = request.args.get('entity', '').strip() - page = request.args.get('page', 1, type=int) - sort = request.args.get('sort', 'timestamp') - order = request.args.get('order', 'desc') - per_page = 50 - - # Whitelist für erlaubte Sortierfelder - allowed_sort_fields = { - 'timestamp': 'timestamp', - 'username': 'username', - 'action': 'action', - 'entity': 'entity_type', - 'ip': 'ip_address' - } - - # Validierung - if sort not in allowed_sort_fields: - sort = 'timestamp' - if order not in ['asc', 'desc']: - order = 'desc' - - sort_field = allowed_sort_fields[sort] - - # SQL Query mit optionalen Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - - params = [] - - # Filter - if filter_user: - query += " AND LOWER(username) LIKE LOWER(%s)" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - # Gesamtanzahl für Pagination - count_query = "SELECT COUNT(*) FROM (" + query + ") as count_table" - cur.execute(count_query, params) - total = cur.fetchone()[0] - - # Pagination - offset = (page - 1) * per_page - query += f" ORDER BY {sort_field} {order.upper()} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - logs = cur.fetchall() - - # JSON-Werte parsen - parsed_logs = [] - for log in logs: - parsed_log = list(log) - # old_values und new_values sind bereits Dictionaries (JSONB) - # Keine Konvertierung nötig - parsed_logs.append(parsed_log) - - # Pagination Info - total_pages = (total + per_page - 1) // per_page - - cur.close() - conn.close() - - return render_template("audit_log.html", - logs=parsed_logs, - filter_user=filter_user, - filter_action=filter_action, - filter_entity=filter_entity, - page=page, - total_pages=total_pages, - total=total, - sort=sort, - order=order, - username=session.get('username')) - -@app.route("/backups") -@login_required -def backups(): - """Zeigt die Backup-Historie an""" - conn = get_connection() - cur = conn.cursor() - - # Letztes erfolgreiches Backup für Dashboard - cur.execute(""" - SELECT created_at, filesize, duration_seconds - FROM backup_history - WHERE status = 'success' - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup = cur.fetchone() - - # Alle Backups abrufen - cur.execute(""" - SELECT id, filename, filesize, backup_type, status, error_message, - created_at, created_by, tables_count, records_count, - duration_seconds, is_encrypted - FROM backup_history - ORDER BY created_at DESC - """) - backups = cur.fetchall() - - cur.close() - conn.close() - - return render_template("backups.html", - backups=backups, - last_backup=last_backup, - username=session.get('username')) - -@app.route("/backup/create", methods=["POST"]) -@login_required -def create_backup_route(): - """Erstellt ein manuelles Backup""" - username = session.get('username') - success, result = create_backup(backup_type="manual", created_by=username) - - if success: - return jsonify({ - 'success': True, - 'message': f'Backup erfolgreich erstellt: {result}' - }) - else: - return jsonify({ - 'success': False, - 'message': f'Backup fehlgeschlagen: {result}' - }), 500 - -@app.route("/backup/restore/", methods=["POST"]) -@login_required -def restore_backup_route(backup_id): - """Stellt ein Backup wieder her""" - encryption_key = request.form.get('encryption_key') - - success, message = restore_backup(backup_id, encryption_key) - - if success: - return jsonify({ - 'success': True, - 'message': message - }) - else: - return jsonify({ - 'success': False, - 'message': message - }), 500 - -@app.route("/backup/download/") -@login_required -def download_backup(backup_id): - """Lädt eine Backup-Datei herunter""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - cur.close() - conn.close() - - if not backup_info: - return "Backup nicht gefunden", 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - if not filepath.exists(): - return "Backup-Datei nicht gefunden", 404 - - # Audit-Log - log_audit('DOWNLOAD', 'backup', backup_id, - additional_info=f"Backup heruntergeladen: {filename}") - - return send_file(filepath, as_attachment=True, download_name=filename) - -@app.route("/backup/delete/", methods=["DELETE"]) -@login_required -def delete_backup(backup_id): - """Löscht ein Backup""" - conn = get_connection() - cur = conn.cursor() - - try: - # Backup-Informationen abrufen - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - if not backup_info: - return jsonify({ - 'success': False, - 'message': 'Backup nicht gefunden' - }), 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - # Datei löschen, wenn sie existiert - if filepath.exists(): - filepath.unlink() - - # Aus Datenbank löschen - cur.execute(""" - DELETE FROM backup_history - WHERE id = %s - """, (backup_id,)) - - conn.commit() - - # Audit-Log - log_audit('DELETE', 'backup', backup_id, - additional_info=f"Backup gelöscht: {filename}") - - return jsonify({ - 'success': True, - 'message': f'Backup "{filename}" wurde erfolgreich gelöscht' - }) - - except Exception as e: - conn.rollback() - return jsonify({ - 'success': False, - 'message': f'Fehler beim Löschen des Backups: {str(e)}' - }), 500 - finally: - cur.close() - conn.close() - -@app.route("/security/blocked-ips") -@login_required -def blocked_ips(): - """Zeigt alle gesperrten IPs an""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT - ip_address, - attempt_count, - first_attempt, - last_attempt, - blocked_until, - last_username_tried, - last_error_message - FROM login_attempts - WHERE blocked_until IS NOT NULL - ORDER BY blocked_until DESC - """) - - blocked_ips_list = [] - for ip in cur.fetchall(): - blocked_ips_list.append({ - 'ip_address': ip[0], - 'attempt_count': ip[1], - 'first_attempt': ip[2].strftime('%d.%m.%Y %H:%M'), - 'last_attempt': ip[3].strftime('%d.%m.%Y %H:%M'), - 'blocked_until': ip[4].strftime('%d.%m.%Y %H:%M'), - 'is_active': ip[4] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None), - 'last_username': ip[5], - 'last_error': ip[6] - }) - - cur.close() - conn.close() - - return render_template("blocked_ips.html", - blocked_ips=blocked_ips_list, - username=session.get('username')) - -@app.route("/security/unblock-ip", methods=["POST"]) -@login_required -def unblock_ip(): - """Entsperrt eine IP-Adresse""" - ip_address = request.form.get('ip_address') - - if ip_address: - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - UPDATE login_attempts - SET blocked_until = NULL - WHERE ip_address = %s - """, (ip_address,)) - - conn.commit() - cur.close() - conn.close() - - # Audit-Log - log_audit('UNBLOCK_IP', 'security', - additional_info=f"IP {ip_address} manuell entsperrt") - - return redirect(url_for('blocked_ips')) - -@app.route("/security/clear-attempts", methods=["POST"]) -@login_required -def clear_attempts(): - """Löscht alle Login-Versuche für eine IP""" - ip_address = request.form.get('ip_address') - - if ip_address: - reset_login_attempts(ip_address) - - # Audit-Log - log_audit('CLEAR_ATTEMPTS', 'security', - additional_info=f"Login-Versuche für IP {ip_address} zurückgesetzt") - - return redirect(url_for('blocked_ips')) - -# API Endpoints for License Management -@app.route("/api/license//toggle", methods=["POST"]) -@login_required -def toggle_license_api(license_id): - """Toggle license active status via API""" - try: - data = request.get_json() - is_active = data.get('is_active', False) - - conn = get_connection() - cur = conn.cursor() - - # Update license status - cur.execute(""" - UPDATE licenses - SET is_active = %s - WHERE id = %s - """, (is_active, license_id)) - - conn.commit() - - # Log the action - log_audit('UPDATE', 'license', license_id, - new_values={'is_active': is_active}, - additional_info=f"Lizenz {'aktiviert' if is_active else 'deaktiviert'} via Toggle") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Status erfolgreich geändert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-activate", methods=["POST"]) -@login_required -def bulk_activate_licenses(): - """Activate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = TRUE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': True, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen aktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen aktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-deactivate", methods=["POST"]) -@login_required -def bulk_deactivate_licenses(): - """Deactivate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = FALSE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': False, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen deaktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen deaktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/license//devices") -@login_required -def get_license_devices(license_id): - """Hole alle registrierten Geräte einer Lizenz""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und hole device_limit - cur.execute(""" - SELECT device_limit FROM licenses WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit = license_data[0] - - # Hole alle Geräte für diese Lizenz - cur.execute(""" - SELECT id, hardware_id, device_name, operating_system, - first_seen, last_seen, is_active, ip_address - FROM device_registrations - WHERE license_id = %s - ORDER BY is_active DESC, last_seen DESC - """, (license_id,)) - - devices = [] - for row in cur.fetchall(): - devices.append({ - 'id': row[0], - 'hardware_id': row[1], - 'device_name': row[2] or 'Unbekanntes Gerät', - 'operating_system': row[3] or 'Unbekannt', - 'first_seen': row[4].strftime('%d.%m.%Y %H:%M') if row[4] else '', - 'last_seen': row[5].strftime('%d.%m.%Y %H:%M') if row[5] else '', - 'is_active': row[6], - 'ip_address': row[7] or '-' - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'devices': devices, - 'device_limit': device_limit, - 'active_count': sum(1 for d in devices if d['is_active']) - }) - - except Exception as e: - logging.error(f"Fehler beim Abrufen der Geräte: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Abrufen der Geräte'}), 500 - -@app.route("/api/license//register-device", methods=["POST"]) -def register_device(license_id): - """Registriere ein neues Gerät für eine Lizenz""" - try: - data = request.get_json() - hardware_id = data.get('hardware_id') - device_name = data.get('device_name', '') - operating_system = data.get('operating_system', '') - - if not hardware_id: - return jsonify({'success': False, 'message': 'Hardware-ID fehlt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und aktiv ist - cur.execute(""" - SELECT device_limit, is_active, valid_until - FROM licenses - WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit, is_active, valid_until = license_data - - # Prüfe ob Lizenz aktiv und gültig ist - if not is_active: - return jsonify({'success': False, 'message': 'Lizenz ist deaktiviert'}), 403 - - if valid_until < datetime.now(ZoneInfo("Europe/Berlin")).date(): - return jsonify({'success': False, 'message': 'Lizenz ist abgelaufen'}), 403 - - # Prüfe ob Gerät bereits registriert ist - cur.execute(""" - SELECT id, is_active FROM device_registrations - WHERE license_id = %s AND hardware_id = %s - """, (license_id, hardware_id)) - existing_device = cur.fetchone() - - if existing_device: - device_id, is_device_active = existing_device - if is_device_active: - # Gerät ist bereits aktiv, update last_seen - cur.execute(""" - UPDATE device_registrations - SET last_seen = CURRENT_TIMESTAMP, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät bereits registriert', 'device_id': device_id}) - else: - # Gerät war deaktiviert, prüfe ob wir es reaktivieren können - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Reaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = TRUE, - last_seen = CURRENT_TIMESTAMP, - deactivated_at = NULL, - deactivated_by = NULL, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät reaktiviert', 'device_id': device_id}) - - # Neues Gerät - prüfe Gerätelimit - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Registriere neues Gerät - cur.execute(""" - INSERT INTO device_registrations - (license_id, hardware_id, device_name, operating_system, ip_address, user_agent) - VALUES (%s, %s, %s, %s, %s, %s) - RETURNING id - """, (license_id, hardware_id, device_name, operating_system, - get_client_ip(), request.headers.get('User-Agent', ''))) - device_id = cur.fetchone()[0] - - conn.commit() - - # Audit Log - log_audit('DEVICE_REGISTER', 'device', device_id, - new_values={'license_id': license_id, 'hardware_id': hardware_id}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich registriert', 'device_id': device_id}) - - except Exception as e: - logging.error(f"Fehler bei Geräte-Registrierung: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler bei der Registrierung'}), 500 - -@app.route("/api/license//deactivate-device/", methods=["POST"]) -@login_required -def deactivate_device(license_id, device_id): - """Deaktiviere ein registriertes Gerät""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob das Gerät zu dieser Lizenz gehört - cur.execute(""" - SELECT id FROM device_registrations - WHERE id = %s AND license_id = %s AND is_active = TRUE - """, (device_id, license_id)) - - if not cur.fetchone(): - return jsonify({'success': False, 'message': 'Gerät nicht gefunden oder bereits deaktiviert'}), 404 - - # Deaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = FALSE, - deactivated_at = CURRENT_TIMESTAMP, - deactivated_by = %s - WHERE id = %s - """, (session['username'], device_id)) - - conn.commit() - - # Audit Log - log_audit('DEVICE_DEACTIVATE', 'device', device_id, - old_values={'is_active': True}, - new_values={'is_active': False}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich deaktiviert'}) - - except Exception as e: - logging.error(f"Fehler beim Deaktivieren des Geräts: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Deaktivieren'}), 500 - -@app.route("/api/licenses/bulk-delete", methods=["POST"]) -@login_required -def bulk_delete_licenses(): - """Delete multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Get license info for audit log (nur Live-Daten) - cur.execute(""" - SELECT license_key - FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - license_keys = [row[0] for row in cur.fetchall()] - - # Delete all selected licenses (nur Live-Daten) - cur.execute(""" - DELETE FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_DELETE', 'licenses', None, - old_values={'license_keys': license_keys, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen gelöscht") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen gelöscht'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# ===================== RESOURCE POOL MANAGEMENT ===================== - -@app.route('/resources') -@login_required -def resources(): - """Resource Pool Hauptübersicht""" - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Testdaten angezeigt werden sollen (gleiche Logik wie bei Kunden) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - # Statistiken abrufen - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = %s - GROUP BY resource_type - """, (show_test,)) - - stats = {} - for row in cur.fetchall(): - stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - } - - # Letzte Aktivitäten (gefiltert nach Test/Live) - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rp.resource_type, - rp.resource_value, - rh.details - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - WHERE rp.is_test = %s - ORDER BY rh.action_at DESC - LIMIT 10 - """, (show_test,)) - recent_activities = cur.fetchall() - - # Ressourcen-Liste mit Pagination - page = request.args.get('page', 1, type=int) - per_page = 50 - offset = (page - 1) * per_page - - resource_type = request.args.get('type', '') - status_filter = request.args.get('status', '') - search = request.args.get('search', '') - - # Sortierung - sort_by = request.args.get('sort', 'id') - sort_order = request.args.get('order', 'desc') - - # Base Query - query = """ - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - rp.allocated_to_license, - l.license_key, - c.name as customer_name, - rp.status_changed_at, - rp.quarantine_reason, - rp.quarantine_until, - c.id as customer_id - FROM resource_pools rp - LEFT JOIN licenses l ON rp.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rp.is_test = %s - """ - params = [show_test] - - if resource_type: - query += " AND rp.resource_type = %s" - params.append(resource_type) - - if status_filter: - query += " AND rp.status = %s" - params.append(status_filter) - - if search: - query += " AND rp.resource_value ILIKE %s" - params.append(f'%{search}%') - - # Count total - count_query = f"SELECT COUNT(*) FROM ({query}) as cnt" - cur.execute(count_query, params) - total = cur.fetchone()[0] - total_pages = (total + per_page - 1) // per_page - - # Get paginated results with dynamic sorting - sort_column_map = { - 'id': 'rp.id', - 'type': 'rp.resource_type', - 'resource': 'rp.resource_value', - 'status': 'rp.status', - 'assigned': 'c.name', - 'changed': 'rp.status_changed_at' - } - - sort_column = sort_column_map.get(sort_by, 'rp.id') - sort_direction = 'ASC' if sort_order == 'asc' else 'DESC' - - query += f" ORDER BY {sort_column} {sort_direction} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - resources = cur.fetchall() - - cur.close() - conn.close() - - return render_template('resources.html', - stats=stats, - resources=resources, - recent_activities=recent_activities, - page=page, - total_pages=total_pages, - total=total, - resource_type=resource_type, - status_filter=status_filter, - search=search, - show_test=show_test, - sort_by=sort_by, - sort_order=sort_order, - datetime=datetime, - timedelta=timedelta) - -@app.route('/resources/add', methods=['GET', 'POST']) -@login_required -def add_resources(): - """Ressourcen zum Pool hinzufügen""" - # Hole show_test Parameter für die Anzeige - show_test = request.args.get('show_test', 'false').lower() == 'true' - - if request.method == 'POST': - resource_type = request.form.get('resource_type') - resources_text = request.form.get('resources_text', '') - is_test = request.form.get('is_test') == 'on' # Checkbox für Testdaten - - # Parse resources (one per line) - resources = [r.strip() for r in resources_text.split('\n') if r.strip()] - - if not resources: - flash('Keine Ressourcen angegeben', 'error') - return redirect(url_for('add_resources', show_test=show_test)) - - conn = get_connection() - cur = conn.cursor() - - added = 0 - duplicates = 0 - - for resource_value in resources: - try: - cur.execute(""" - INSERT INTO resource_pools (resource_type, resource_value, status_changed_by, is_test) - VALUES (%s, %s, %s, %s) - ON CONFLICT (resource_type, resource_value) DO NOTHING - """, (resource_type, resource_value, session['username'], is_test)) - - if cur.rowcount > 0: - added += 1 - # Get the inserted ID - cur.execute("SELECT id FROM resource_pools WHERE resource_type = %s AND resource_value = %s", - (resource_type, resource_value)) - resource_id = cur.fetchone()[0] - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'created', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - else: - duplicates += 1 - - except Exception as e: - app.logger.error(f"Error adding resource {resource_value}: {e}") - - conn.commit() - cur.close() - conn.close() - - log_audit('CREATE', 'resource_pool', None, - new_values={'type': resource_type, 'added': added, 'duplicates': duplicates, 'is_test': is_test}, - additional_info=f"{added} {'Test-' if is_test else ''}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen") - - flash(f'{added} {"Test-" if is_test else ""}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen', 'success') - return redirect(url_for('resources', show_test=show_test)) - - return render_template('add_resources.html', show_test=show_test) - -@app.route('/resources/quarantine/', methods=['POST']) -@login_required -def quarantine_resource(resource_id): - """Ressource in Quarantäne setzen""" - reason = request.form.get('reason', 'review') - until_date = request.form.get('until_date') - notes = request.form.get('notes', '') - - conn = get_connection() - cur = conn.cursor() - - # Get current resource info - cur.execute("SELECT resource_type, resource_value, status FROM resource_pools WHERE id = %s", (resource_id,)) - resource = cur.fetchone() - - if not resource: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - old_status = resource[2] - - # Update resource - cur.execute(""" - UPDATE resource_pools - SET status = 'quarantine', - quarantine_reason = %s, - quarantine_until = %s, - notes = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (reason, until_date if until_date else None, notes, session['username'], resource_id)) - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address, details) - VALUES (%s, 'quarantined', %s, %s, %s) - """, (resource_id, session['username'], get_client_ip(), - Json({'reason': reason, 'until': until_date, 'notes': notes, 'old_status': old_status}))) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource', resource_id, - old_values={'status': old_status}, - new_values={'status': 'quarantine', 'reason': reason}, - additional_info=f"Ressource {resource[0]}: {resource[1]} in Quarantäne") - - flash('Ressource in Quarantäne gesetzt', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/resources/release', methods=['POST']) -@login_required -def release_resources(): - """Ressourcen aus Quarantäne freigeben""" - resource_ids = request.form.getlist('resource_ids') - - if not resource_ids: - flash('Keine Ressourcen ausgewählt', 'error') - return redirect(url_for('resources')) - - conn = get_connection() - cur = conn.cursor() - - released = 0 - for resource_id in resource_ids: - cur.execute(""" - UPDATE resource_pools - SET status = 'available', - quarantine_reason = NULL, - quarantine_until = NULL, - allocated_to_license = NULL, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s AND status = 'quarantine' - """, (session['username'], resource_id)) - - if cur.rowcount > 0: - released += 1 - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'released', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource_pool', None, - new_values={'released': released}, - additional_info=f"{released} Ressourcen aus Quarantäne freigegeben") - - flash(f'{released} Ressourcen freigegeben', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/api/resources/allocate', methods=['POST']) -@login_required -def allocate_resources_api(): - """API für Ressourcen-Zuweisung bei Lizenzerstellung""" - data = request.json - license_id = data.get('license_id') - domain_count = data.get('domain_count', 1) - ipv4_count = data.get('ipv4_count', 1) - phone_count = data.get('phone_count', 1) - - conn = get_connection() - cur = conn.cursor() - - try: - allocated = {'domains': [], 'ipv4s': [], 'phones': []} - - # Allocate domains - if domain_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' - LIMIT %s FOR UPDATE - """, (domain_count,)) - domains = cur.fetchall() - - if len(domains) < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {len(domains)})") - - for domain_id, domain_value in domains: - # Update resource status - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], domain_id)) - - # Create assignment - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, domain_id, session['username'])) - - # Log history - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (domain_id, license_id, session['username'], get_client_ip())) - - allocated['domains'].append(domain_value) - - # Allocate IPv4s (similar logic) - if ipv4_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' - LIMIT %s FOR UPDATE - """, (ipv4_count,)) - ipv4s = cur.fetchall() - - if len(ipv4s) < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar") - - for ipv4_id, ipv4_value in ipv4s: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], ipv4_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, ipv4_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (ipv4_id, license_id, session['username'], get_client_ip())) - - allocated['ipv4s'].append(ipv4_value) - - # Allocate phones (similar logic) - if phone_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' - LIMIT %s FOR UPDATE - """, (phone_count,)) - phones = cur.fetchall() - - if len(phones) < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar") - - for phone_id, phone_value in phones: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], phone_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, phone_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (phone_id, license_id, session['username'], get_client_ip())) - - allocated['phones'].append(phone_value) - - # Update license resource counts - cur.execute(""" - UPDATE licenses - SET domain_count = %s, - ipv4_count = %s, - phone_count = %s - WHERE id = %s - """, (domain_count, ipv4_count, phone_count, license_id)) - - conn.commit() - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'allocated': allocated - }) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({ - 'success': False, - 'error': str(e) - }), 400 - -@app.route('/api/resources/check-availability', methods=['GET']) -@login_required -def check_resource_availability(): - """Prüft verfügbare Ressourcen""" - resource_type = request.args.get('type', '') - count = request.args.get('count', 10, type=int) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - conn = get_connection() - cur = conn.cursor() - - if resource_type: - # Spezifische Ressourcen für einen Typ - cur.execute(""" - SELECT id, resource_value - FROM resource_pools - WHERE status = 'available' - AND resource_type = %s - AND is_test = %s - ORDER BY resource_value - LIMIT %s - """, (resource_type, show_test, count)) - - resources = [] - for row in cur.fetchall(): - resources.append({ - 'id': row[0], - 'value': row[1] - }) - - cur.close() - conn.close() - - return jsonify({ - 'available': resources, - 'type': resource_type, - 'count': len(resources) - }) - else: - # Zusammenfassung aller Typen - cur.execute(""" - SELECT - resource_type, - COUNT(*) as available - FROM resource_pools - WHERE status = 'available' - AND is_test = %s - GROUP BY resource_type - """, (show_test,)) - - availability = {} - for row in cur.fetchall(): - availability[row[0]] = row[1] - - cur.close() - conn.close() - - return jsonify(availability) - -@app.route('/api/global-search', methods=['GET']) -@login_required -def global_search(): - """Global search API endpoint for searching customers and licenses""" - query = request.args.get('q', '').strip() - - if not query or len(query) < 2: - return jsonify({'customers': [], 'licenses': []}) - - conn = get_connection() - cur = conn.cursor() - - # Search pattern with wildcards - search_pattern = f'%{query}%' - - # Search customers - cur.execute(""" - SELECT id, name, email, company_name - FROM customers - WHERE (LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - OR LOWER(company_name) LIKE LOWER(%s)) - AND is_test = FALSE - ORDER BY name - LIMIT 5 - """, (search_pattern, search_pattern, search_pattern)) - - customers = [] - for row in cur.fetchall(): - customers.append({ - 'id': row[0], - 'name': row[1], - 'email': row[2], - 'company_name': row[3] - }) - - # Search licenses - cur.execute(""" - SELECT l.id, l.license_key, c.name as customer_name - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE LOWER(l.license_key) LIKE LOWER(%s) - AND l.is_test = FALSE - ORDER BY l.created_at DESC - LIMIT 5 - """, (search_pattern,)) - - licenses = [] - for row in cur.fetchall(): - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'customer_name': row[2] - }) - - cur.close() - conn.close() - - return jsonify({ - 'customers': customers, - 'licenses': licenses - }) - -@app.route('/resources/history/') -@login_required -def resource_history(resource_id): - """Zeigt die komplette Historie einer Ressource""" - conn = get_connection() - cur = conn.cursor() - - # Get complete resource info using named columns - cur.execute(""" - SELECT id, resource_type, resource_value, status, allocated_to_license, - status_changed_at, status_changed_by, quarantine_reason, - quarantine_until, created_at, notes - FROM resource_pools - WHERE id = %s - """, (resource_id,)) - row = cur.fetchone() - - if not row: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - # Create resource object with named attributes - resource = { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'allocated_to_license': row[4], - 'status_changed_at': row[5], - 'status_changed_by': row[6], - 'quarantine_reason': row[7], - 'quarantine_until': row[8], - 'created_at': row[9], - 'notes': row[10] - } - - # Get license info if allocated - license_info = None - if resource['allocated_to_license']: - cur.execute("SELECT license_key FROM licenses WHERE id = %s", - (resource['allocated_to_license'],)) - lic = cur.fetchone() - if lic: - license_info = {'license_key': lic[0]} - - # Get history with named columns - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rh.details, - rh.license_id, - rh.ip_address - FROM resource_history rh - WHERE rh.resource_id = %s - ORDER BY rh.action_at DESC - """, (resource_id,)) - - history = [] - for row in cur.fetchall(): - history.append({ - 'action': row[0], - 'action_by': row[1], - 'action_at': row[2], - 'details': row[3], - 'license_id': row[4], - 'ip_address': row[5] - }) - - cur.close() - conn.close() - - # Convert to object-like for template - class ResourceObj: - def __init__(self, data): - for key, value in data.items(): - setattr(self, key, value) - - resource_obj = ResourceObj(resource) - history_objs = [ResourceObj(h) for h in history] - - return render_template('resource_history.html', - resource=resource_obj, - license_info=license_info, - history=history_objs) - -@app.route('/resources/metrics') -@login_required -def resources_metrics(): - """Dashboard für Resource Metrics und Reports""" - conn = get_connection() - cur = conn.cursor() - - # Overall stats with fallback values - cur.execute(""" - SELECT - COUNT(DISTINCT resource_id) as total_resources, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(cost), 0) as total_cost, - COALESCE(SUM(revenue), 0) as total_revenue, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - """) - row = cur.fetchone() - - # Calculate ROI - roi = 0 - if row[2] > 0: # if total_cost > 0 - roi = row[3] / row[2] # revenue / cost - - stats = { - 'total_resources': row[0] or 0, - 'avg_performance': row[1] or 0, - 'total_cost': row[2] or 0, - 'total_revenue': row[3] or 0, - 'total_issues': row[4] or 0, - 'roi': roi - } - - # Performance by type - cur.execute(""" - SELECT - rp.resource_type, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COUNT(DISTINCT rp.id) as resource_count - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY rp.resource_type - ORDER BY rp.resource_type - """) - performance_by_type = cur.fetchall() - - # Utilization data - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) as total, - ROUND(COUNT(*) FILTER (WHERE status = 'allocated') * 100.0 / COUNT(*), 1) as allocated_percent - FROM resource_pools - GROUP BY resource_type - """) - utilization_rows = cur.fetchall() - utilization_data = [ - { - 'type': row[0].upper(), - 'allocated': row[1], - 'total': row[2], - 'allocated_percent': row[3] - } - for row in utilization_rows - ] - - # Top performing resources - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COALESCE(SUM(rm.revenue), 0) as total_revenue, - COALESCE(SUM(rm.cost), 1) as total_cost, - CASE - WHEN COALESCE(SUM(rm.cost), 0) = 0 THEN 0 - ELSE COALESCE(SUM(rm.revenue), 0) / COALESCE(SUM(rm.cost), 1) - END as roi - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rp.status != 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value - HAVING AVG(rm.performance_score) IS NOT NULL - ORDER BY avg_score DESC - LIMIT 10 - """) - top_rows = cur.fetchall() - top_performers = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'avg_score': row[3], - 'roi': row[6] - } - for row in top_rows - ] - - # Resources with issues - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - COALESCE(SUM(rm.issues_count), 0) as total_issues - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rm.issues_count > 0 OR rp.status = 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - HAVING SUM(rm.issues_count) > 0 - ORDER BY total_issues DESC - LIMIT 10 - """) - problem_rows = cur.fetchall() - problem_resources = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'total_issues': row[4] - } - for row in problem_rows - ] - - # Daily metrics for trend chart (last 30 days) - cur.execute(""" - SELECT - metric_date, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY metric_date - ORDER BY metric_date - """) - daily_rows = cur.fetchall() - daily_metrics = [ - { - 'date': row[0].strftime('%d.%m'), - 'performance': float(row[1]), - 'issues': int(row[2]) - } - for row in daily_rows - ] - - cur.close() - conn.close() - - return render_template('resource_metrics.html', - stats=stats, - performance_by_type=performance_by_type, - utilization_data=utilization_data, - top_performers=top_performers, - problem_resources=problem_resources, - daily_metrics=daily_metrics) - -@app.route('/resources/report', methods=['GET']) -@login_required -def resources_report(): - """Generiert Ressourcen-Reports oder zeigt Report-Formular""" - # Prüfe ob Download angefordert wurde - if request.args.get('download') == 'true': - report_type = request.args.get('type', 'usage') - format_type = request.args.get('format', 'excel') - date_from = request.args.get('from', (datetime.now(ZoneInfo("Europe/Berlin")) - timedelta(days=30)).strftime('%Y-%m-%d')) - date_to = request.args.get('to', datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y-%m-%d')) - - conn = get_connection() - cur = conn.cursor() - - if report_type == 'usage': - # Auslastungsreport - query = """ - SELECT - rp.resource_type, - rp.resource_value, - rp.status, - COUNT(DISTINCT rh.license_id) as unique_licenses, - COUNT(rh.id) as total_allocations, - MIN(rh.action_at) as first_used, - MAX(rh.action_at) as last_used - FROM resource_pools rp - LEFT JOIN resource_history rh ON rp.id = rh.resource_id - AND rh.action = 'allocated' - AND rh.action_at BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - ORDER BY rp.resource_type, total_allocations DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Status', 'Unique Lizenzen', 'Gesamt Zuweisungen', 'Erste Nutzung', 'Letzte Nutzung'] - - elif report_type == 'performance': - # Performance-Report - query = """ - SELECT - rp.resource_type, - rp.resource_value, - AVG(rm.performance_score) as avg_performance, - SUM(rm.usage_count) as total_usage, - SUM(rm.revenue) as total_revenue, - SUM(rm.cost) as total_cost, - SUM(rm.revenue - rm.cost) as profit, - SUM(rm.issues_count) as total_issues - FROM resource_pools rp - JOIN resource_metrics rm ON rp.id = rm.resource_id - WHERE rm.metric_date BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value - ORDER BY profit DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Durchschn. Performance', 'Gesamt Nutzung', 'Umsatz', 'Kosten', 'Gewinn', 'Issues'] - - elif report_type == 'compliance': - # Compliance-Report - query = """ - SELECT - rh.action_at, - rh.action, - rh.action_by, - rp.resource_type, - rp.resource_value, - l.license_key, - c.name as customer_name, - rh.ip_address - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - LEFT JOIN licenses l ON rh.license_id = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rh.action_at BETWEEN %s AND %s - ORDER BY rh.action_at DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Zeit', 'Aktion', 'Von', 'Typ', 'Ressource', 'Lizenz', 'Kunde', 'IP-Adresse'] - - else: # inventory report - # Inventar-Report - query = """ - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - GROUP BY resource_type - ORDER BY resource_type - """ - cur.execute(query) - columns = ['Typ', 'Verfügbar', 'Zugeteilt', 'Quarantäne', 'Gesamt'] - - # Convert to DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - cur.close() - conn.close() - - # Generate file - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f"resource_report_{report_type}_{timestamp}" - - if format_type == 'excel': - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Report', index=False) - - # Auto-adjust columns width - worksheet = writer.sheets['Report'] - for column in worksheet.columns: - max_length = 0 - column = [cell for cell in column] - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = (max_length + 2) - worksheet.column_dimensions[column[0].column_letter].width = adjusted_width - - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'excel', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx') - - else: # CSV - output = io.StringIO() - df.to_csv(output, index=False, sep=';', encoding='utf-8-sig') - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'csv', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv') - - # Wenn kein Download, zeige Report-Formular - return render_template('resource_report.html', - datetime=datetime, - timedelta=timedelta, - username=session.get('username')) - -if __name__ == "__main__": - app.run(host="0.0.0.0", port=5000) diff --git a/v2_adminpanel/app.py.backup_before_blueprint_migration b/v2_adminpanel/app.py.backup_before_blueprint_migration deleted file mode 100644 index 0622714..0000000 --- a/v2_adminpanel/app.py.backup_before_blueprint_migration +++ /dev/null @@ -1,4461 +0,0 @@ -import os -import sys -import time -import json -import logging -import requests -import re -import random -import base64 -from io import BytesIO -from datetime import datetime, timedelta -from zoneinfo import ZoneInfo -from pathlib import Path - -# Add current directory to Python path to ensure modules can be imported -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from flask import Flask, render_template, request, redirect, session, url_for, send_file, jsonify, flash -from flask_session import Session -from werkzeug.middleware.proxy_fix import ProxyFix -from apscheduler.schedulers.background import BackgroundScheduler -import pandas as pd -from psycopg2.extras import Json - -# Import our new modules -import config -from db import get_connection, get_db_connection, get_db_cursor, execute_query -from auth.decorators import login_required -from auth.password import hash_password, verify_password -from auth.two_factor import ( - generate_totp_secret, generate_qr_code, verify_totp, - generate_backup_codes, hash_backup_code, verify_backup_code -) -from auth.rate_limiting import ( - check_ip_blocked, record_failed_attempt, - reset_login_attempts, get_login_attempts -) -from utils.network import get_client_ip -from utils.audit import log_audit -from utils.license import generate_license_key, validate_license_key -from utils.backup import create_backup, restore_backup, get_or_create_encryption_key -from utils.export import ( - create_excel_export, format_datetime_for_export, - prepare_license_export_data, prepare_customer_export_data, - prepare_session_export_data, prepare_audit_export_data -) -from models import get_user_by_username - -app = Flask(__name__) -# Load configuration from config module -app.config['SECRET_KEY'] = config.SECRET_KEY -app.config['SESSION_TYPE'] = config.SESSION_TYPE -app.config['JSON_AS_ASCII'] = config.JSON_AS_ASCII -app.config['JSONIFY_MIMETYPE'] = config.JSONIFY_MIMETYPE -app.config['PERMANENT_SESSION_LIFETIME'] = config.PERMANENT_SESSION_LIFETIME -app.config['SESSION_COOKIE_HTTPONLY'] = config.SESSION_COOKIE_HTTPONLY -app.config['SESSION_COOKIE_SECURE'] = config.SESSION_COOKIE_SECURE -app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE -app.config['SESSION_COOKIE_NAME'] = config.SESSION_COOKIE_NAME -app.config['SESSION_REFRESH_EACH_REQUEST'] = config.SESSION_REFRESH_EACH_REQUEST -Session(app) - -# ProxyFix für korrekte IP-Adressen hinter Nginx -app.wsgi_app = ProxyFix( - app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 -) - -# Configuration is now loaded from config module - -# Scheduler für automatische Backups -scheduler = BackgroundScheduler() -scheduler.start() - -# Logging konfigurieren -logging.basicConfig(level=logging.INFO) - -# Import and register blueprints -from routes.auth_routes import auth_bp -from routes.admin_routes import admin_bp - -# Temporarily comment out blueprints to avoid conflicts -# app.register_blueprint(auth_bp) -# app.register_blueprint(admin_bp) - - -# Scheduled Backup Job -def scheduled_backup(): - """Führt ein geplantes Backup aus""" - logging.info("Starte geplantes Backup...") - create_backup(backup_type="scheduled", created_by="scheduler") - -# Scheduler konfigurieren - täglich um 3:00 Uhr -scheduler.add_job( - scheduled_backup, - 'cron', - hour=config.SCHEDULER_CONFIG['backup_hour'], - minute=config.SCHEDULER_CONFIG['backup_minute'], - id='daily_backup', - replace_existing=True -) - - -def verify_recaptcha(response): - """Verifiziert die reCAPTCHA v2 Response mit Google""" - secret_key = config.RECAPTCHA_SECRET_KEY - - # Wenn kein Secret Key konfiguriert ist, CAPTCHA als bestanden werten (für PoC) - if not secret_key: - logging.warning("RECAPTCHA_SECRET_KEY nicht konfiguriert - CAPTCHA wird übersprungen") - return True - - # Verifizierung bei Google - try: - verify_url = 'https://www.google.com/recaptcha/api/siteverify' - data = { - 'secret': secret_key, - 'response': response - } - - # Timeout für Request setzen - r = requests.post(verify_url, data=data, timeout=5) - result = r.json() - - # Log für Debugging - if not result.get('success'): - logging.warning(f"reCAPTCHA Validierung fehlgeschlagen: {result.get('error-codes', [])}") - - return result.get('success', False) - - except requests.exceptions.RequestException as e: - logging.error(f"reCAPTCHA Verifizierung fehlgeschlagen: {str(e)}") - # Bei Netzwerkfehlern CAPTCHA als bestanden werten - return True - except Exception as e: - logging.error(f"Unerwarteter Fehler bei reCAPTCHA: {str(e)}") - return False - - -@app.route("/login", methods=["GET", "POST"]) -def login(): - # Timing-Attack Schutz - Start Zeit merken - start_time = time.time() - - # IP-Adresse ermitteln - ip_address = get_client_ip() - - # Prüfen ob IP gesperrt ist - is_blocked, blocked_until = check_ip_blocked(ip_address) - if is_blocked: - time_remaining = (blocked_until - datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None)).total_seconds() / 3600 - error_msg = f"IP GESPERRT! Noch {time_remaining:.1f} Stunden warten." - return render_template("login.html", error=error_msg, error_type="blocked") - - # Anzahl bisheriger Versuche - attempt_count = get_login_attempts(ip_address) - - if request.method == "POST": - username = request.form.get("username") - password = request.form.get("password") - captcha_response = request.form.get("g-recaptcha-response") - - # CAPTCHA-Prüfung nur wenn Keys konfiguriert sind - recaptcha_site_key = config.RECAPTCHA_SITE_KEY - if attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and recaptcha_site_key: - if not captcha_response: - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA ERFORDERLICH!", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # CAPTCHA validieren - if not verify_recaptcha(captcha_response): - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA UNGÜLTIG! Bitte erneut versuchen.", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # Check user in database first, fallback to env vars - user = get_user_by_username(username) - login_success = False - needs_2fa = False - - if user: - # Database user authentication - if verify_password(password, user['password_hash']): - login_success = True - needs_2fa = user['totp_enabled'] - else: - # Fallback to environment variables for backward compatibility - if username in config.ADMIN_USERS and password == config.ADMIN_USERS[username]: - login_success = True - - # Timing-Attack Schutz - Mindestens 1 Sekunde warten - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - - if login_success: - # Erfolgreicher Login - if needs_2fa: - # Store temporary session for 2FA verification - session['temp_username'] = username - session['temp_user_id'] = user['id'] - session['awaiting_2fa'] = True - return redirect(url_for('verify_2fa')) - else: - # Complete login without 2FA - session.permanent = True # Aktiviert das Timeout - session['logged_in'] = True - session['username'] = username - session['user_id'] = user['id'] if user else None - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - reset_login_attempts(ip_address) - log_audit('LOGIN_SUCCESS', 'user', - additional_info=f"Erfolgreiche Anmeldung von IP: {ip_address}") - return redirect(url_for('dashboard')) - else: - # Fehlgeschlagener Login - error_message = record_failed_attempt(ip_address, username) - new_attempt_count = get_login_attempts(ip_address) - - # Prüfen ob jetzt gesperrt - is_now_blocked, _ = check_ip_blocked(ip_address) - if is_now_blocked: - log_audit('LOGIN_BLOCKED', 'security', - additional_info=f"IP {ip_address} wurde nach {config.MAX_LOGIN_ATTEMPTS} Versuchen gesperrt") - - return render_template("login.html", - error=error_message, - show_captcha=(new_attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - error_type="failed", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - new_attempt_count), - recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - - # GET Request - return render_template("login.html", - show_captcha=(attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - -@app.route("/logout") -def logout(): - username = session.get('username', 'unknown') - log_audit('LOGOUT', 'user', additional_info=f"Abmeldung") - session.pop('logged_in', None) - session.pop('username', None) - session.pop('user_id', None) - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - return redirect(url_for('login')) - -@app.route("/verify-2fa", methods=["GET", "POST"]) -def verify_2fa(): - if not session.get('awaiting_2fa'): - return redirect(url_for('login')) - - if request.method == "POST": - token = request.form.get('token', '').replace(' ', '') - username = session.get('temp_username') - user_id = session.get('temp_user_id') - - if not username or not user_id: - flash('Session expired. Please login again.', 'error') - return redirect(url_for('login')) - - user = get_user_by_username(username) - if not user: - flash('User not found.', 'error') - return redirect(url_for('login')) - - # Check if it's a backup code - if len(token) == 8 and token.isupper(): - # Try backup code - backup_codes = json.loads(user['backup_codes']) if user['backup_codes'] else [] - if verify_backup_code(token, backup_codes): - # Remove used backup code - code_hash = hash_backup_code(token) - backup_codes.remove(code_hash) - - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET backup_codes = %s WHERE id = %s", - (json.dumps(backup_codes), user_id)) - conn.commit() - cur.close() - conn.close() - - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - flash('Login successful using backup code. Please generate new backup codes.', 'warning') - log_audit('LOGIN_2FA_BACKUP', 'user', additional_info=f"2FA login with backup code") - return redirect(url_for('dashboard')) - else: - # Try TOTP token - if verify_totp(user['totp_secret'], token): - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - log_audit('LOGIN_2FA_SUCCESS', 'user', additional_info=f"2FA login successful") - return redirect(url_for('dashboard')) - - # Failed verification - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET failed_2fa_attempts = failed_2fa_attempts + 1, last_failed_2fa = %s WHERE id = %s", - (datetime.now(), user_id)) - conn.commit() - cur.close() - conn.close() - - flash('Invalid authentication code. Please try again.', 'error') - log_audit('LOGIN_2FA_FAILED', 'user', additional_info=f"Failed 2FA attempt") - - return render_template('verify_2fa.html') - -@app.route("/profile") -@login_required -def profile(): - user = get_user_by_username(session['username']) - if not user: - # For environment-based users, redirect with message - flash('Bitte führen Sie das Migrations-Script aus, um Passwort-Änderung und 2FA zu aktivieren.', 'info') - return redirect(url_for('dashboard')) - return render_template('profile.html', user=user) - -@app.route("/profile/change-password", methods=["POST"]) -@login_required -def change_password(): - current_password = request.form.get('current_password') - new_password = request.form.get('new_password') - confirm_password = request.form.get('confirm_password') - - user = get_user_by_username(session['username']) - - # Verify current password - if not verify_password(current_password, user['password_hash']): - flash('Current password is incorrect.', 'error') - return redirect(url_for('profile')) - - # Check new password - if new_password != confirm_password: - flash('New passwords do not match.', 'error') - return redirect(url_for('profile')) - - if len(new_password) < 8: - flash('Password must be at least 8 characters long.', 'error') - return redirect(url_for('profile')) - - # Update password - new_hash = hash_password(new_password) - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET password_hash = %s, last_password_change = %s WHERE id = %s", - (new_hash, datetime.now(), user['id'])) - conn.commit() - cur.close() - conn.close() - - log_audit('PASSWORD_CHANGE', 'user', entity_id=user['id'], - additional_info="Password changed successfully") - flash('Password changed successfully.', 'success') - return redirect(url_for('profile')) - -@app.route("/profile/setup-2fa") -@login_required -def setup_2fa(): - user = get_user_by_username(session['username']) - - if user['totp_enabled']: - flash('2FA is already enabled for your account.', 'info') - return redirect(url_for('profile')) - - # Generate new TOTP secret - totp_secret = generate_totp_secret() - session['temp_totp_secret'] = totp_secret - - # Generate QR code - qr_code = generate_qr_code(user['username'], totp_secret) - - return render_template('setup_2fa.html', - totp_secret=totp_secret, - qr_code=qr_code) - -@app.route("/profile/enable-2fa", methods=["POST"]) -@login_required -def enable_2fa(): - token = request.form.get('token', '').replace(' ', '') - totp_secret = session.get('temp_totp_secret') - - if not totp_secret: - flash('2FA setup session expired. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Verify the token - if not verify_totp(totp_secret, token): - flash('Invalid authentication code. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Generate backup codes - backup_codes = generate_backup_codes() - hashed_codes = [hash_backup_code(code) for code in backup_codes] - - # Enable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_secret = %s, totp_enabled = TRUE, backup_codes = %s - WHERE username = %s - """, (totp_secret, json.dumps(hashed_codes), session['username'])) - conn.commit() - cur.close() - conn.close() - - session.pop('temp_totp_secret', None) - - log_audit('2FA_ENABLED', 'user', additional_info="2FA enabled successfully") - - # Show backup codes - return render_template('backup_codes.html', backup_codes=backup_codes) - -@app.route("/profile/disable-2fa", methods=["POST"]) -@login_required -def disable_2fa(): - password = request.form.get('password') - user = get_user_by_username(session['username']) - - # Verify password - if not verify_password(password, user['password_hash']): - flash('Incorrect password.', 'error') - return redirect(url_for('profile')) - - # Disable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_enabled = FALSE, totp_secret = NULL, backup_codes = NULL - WHERE username = %s - """, (session['username'],)) - conn.commit() - cur.close() - conn.close() - - log_audit('2FA_DISABLED', 'user', additional_info="2FA disabled") - flash('2FA has been disabled for your account.', 'success') - return redirect(url_for('profile')) - -@app.route("/heartbeat", methods=['POST']) -@login_required -def heartbeat(): - """Endpoint für Session Keep-Alive - aktualisiert last_activity""" - # Aktualisiere last_activity nur wenn explizit angefordert - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # Force session save - session.modified = True - - return jsonify({ - 'status': 'ok', - 'last_activity': session['last_activity'], - 'username': session.get('username') - }) - -@app.route("/api/generate-license-key", methods=['POST']) -@login_required -def api_generate_key(): - """API Endpoint zur Generierung eines neuen Lizenzschlüssels""" - try: - # Lizenztyp aus Request holen (default: full) - data = request.get_json() or {} - license_type = data.get('type', 'full') - - # Key generieren - key = generate_license_key(license_type) - - # Prüfen ob Key bereits existiert (sehr unwahrscheinlich aber sicher ist sicher) - conn = get_connection() - cur = conn.cursor() - - # Wiederhole bis eindeutiger Key gefunden - attempts = 0 - while attempts < 10: # Max 10 Versuche - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (key,)) - if not cur.fetchone(): - break # Key ist eindeutig - key = generate_license_key(license_type) - attempts += 1 - - cur.close() - conn.close() - - # Log für Audit - log_audit('GENERATE_KEY', 'license', - additional_info={'type': license_type, 'key': key}) - - return jsonify({ - 'success': True, - 'key': key, - 'type': license_type - }) - - except Exception as e: - logging.error(f"Fehler bei Key-Generierung: {str(e)}") - return jsonify({ - 'success': False, - 'error': 'Fehler bei der Key-Generierung' - }), 500 - -@app.route("/api/customers", methods=['GET']) -@login_required -def api_customers(): - """API Endpoint für die Kundensuche mit Select2""" - try: - # Suchparameter - search = request.args.get('q', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - customer_id = request.args.get('id', type=int) - - conn = get_connection() - cur = conn.cursor() - - # Einzelnen Kunden per ID abrufen - if customer_id: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.id = %s - GROUP BY c.id, c.name, c.email - """, (customer_id,)) - - customer = cur.fetchone() - results = [] - if customer: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} ({customer[2]})", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - cur.close() - conn.close() - - return jsonify({ - 'results': results, - 'pagination': {'more': False} - }) - - # SQL Query mit optionaler Suche - elif search: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE LOWER(c.name) LIKE LOWER(%s) - OR LOWER(c.email) LIKE LOWER(%s) - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (f'%{search}%', f'%{search}%', per_page, (page - 1) * per_page)) - else: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (per_page, (page - 1) * per_page)) - - customers = cur.fetchall() - - # Format für Select2 - results = [] - for customer in customers: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} - {customer[2]} ({customer[3]} Lizenzen)", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - # Gesamtanzahl für Pagination - if search: - cur.execute(""" - SELECT COUNT(*) FROM customers - WHERE LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - """, (f'%{search}%', f'%{search}%')) - else: - cur.execute("SELECT COUNT(*) FROM customers") - - total_count = cur.fetchone()[0] - - cur.close() - conn.close() - - # Select2 Response Format - return jsonify({ - 'results': results, - 'pagination': { - 'more': (page * per_page) < total_count - } - }) - - except Exception as e: - logging.error(f"Fehler bei Kundensuche: {str(e)}") - return jsonify({ - 'results': [], - 'error': 'Fehler bei der Kundensuche' - }), 500 - -@app.route("/") -@login_required -def dashboard(): - conn = get_connection() - cur = conn.cursor() - - # Statistiken abrufen - # Gesamtanzahl Kunden (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = FALSE") - total_customers = cur.fetchone()[0] - - # Gesamtanzahl Lizenzen (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = FALSE") - total_licenses = cur.fetchone()[0] - - # Aktive Lizenzen (nicht abgelaufen und is_active = true, ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE AND is_active = TRUE AND is_test = FALSE - """) - active_licenses = cur.fetchone()[0] - - # Aktive Sessions - cur.execute("SELECT COUNT(*) FROM sessions WHERE is_active = TRUE") - active_sessions_count = cur.fetchone()[0] - - # Abgelaufene Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until < CURRENT_DATE AND is_test = FALSE - """) - expired_licenses = cur.fetchone()[0] - - # Deaktivierte Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE is_active = FALSE AND is_test = FALSE - """) - inactive_licenses = cur.fetchone()[0] - - # Lizenzen die in den nächsten 30 Tagen ablaufen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE - AND valid_until < CURRENT_DATE + INTERVAL '30 days' - AND is_active = TRUE - AND is_test = FALSE - """) - expiring_soon = cur.fetchone()[0] - - # Testlizenzen vs Vollversionen (ohne Testdaten) - cur.execute(""" - SELECT license_type, COUNT(*) - FROM licenses - WHERE is_test = FALSE - GROUP BY license_type - """) - license_types = dict(cur.fetchall()) - - # Anzahl Testdaten - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = TRUE") - test_data_count = cur.fetchone()[0] - - # Anzahl Test-Kunden - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = TRUE") - test_customers_count = cur.fetchone()[0] - - # Anzahl Test-Ressourcen - cur.execute("SELECT COUNT(*) FROM resource_pools WHERE is_test = TRUE") - test_resources_count = cur.fetchone()[0] - - # Letzte 5 erstellten Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.is_test = FALSE - ORDER BY l.id DESC - LIMIT 5 - """) - recent_licenses = cur.fetchall() - - # Bald ablaufende Lizenzen (nächste 30 Tage, ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - l.valid_until - CURRENT_DATE as days_left - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.valid_until >= CURRENT_DATE - AND l.valid_until < CURRENT_DATE + INTERVAL '30 days' - AND l.is_active = TRUE - AND l.is_test = FALSE - ORDER BY l.valid_until - LIMIT 10 - """) - expiring_licenses = cur.fetchall() - - # Letztes Backup - cur.execute(""" - SELECT created_at, filesize, duration_seconds, backup_type, status - FROM backup_history - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup_info = cur.fetchone() - - # Sicherheitsstatistiken - # Gesperrte IPs - cur.execute(""" - SELECT COUNT(*) FROM login_attempts - WHERE blocked_until IS NOT NULL AND blocked_until > CURRENT_TIMESTAMP - """) - blocked_ips_count = cur.fetchone()[0] - - # Fehlversuche heute - cur.execute(""" - SELECT COALESCE(SUM(attempt_count), 0) FROM login_attempts - WHERE last_attempt::date = CURRENT_DATE - """) - failed_attempts_today = cur.fetchone()[0] - - # Letzte 5 Sicherheitsereignisse - cur.execute(""" - SELECT - la.ip_address, - la.attempt_count, - la.last_attempt, - la.blocked_until, - la.last_username_tried, - la.last_error_message - FROM login_attempts la - ORDER BY la.last_attempt DESC - LIMIT 5 - """) - recent_security_events = [] - for event in cur.fetchall(): - recent_security_events.append({ - 'ip_address': event[0], - 'attempt_count': event[1], - 'last_attempt': event[2].strftime('%d.%m %H:%M'), - 'blocked_until': event[3].strftime('%d.%m %H:%M') if event[3] and event[3] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) else None, - 'username_tried': event[4], - 'error_message': event[5] - }) - - # Sicherheitslevel berechnen - if blocked_ips_count > 5 or failed_attempts_today > 50: - security_level = 'danger' - security_level_text = 'KRITISCH' - elif blocked_ips_count > 2 or failed_attempts_today > 20: - security_level = 'warning' - security_level_text = 'ERHÖHT' - else: - security_level = 'success' - security_level_text = 'NORMAL' - - # Resource Pool Statistiken (nur Live-Daten, keine Testdaten) - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = FALSE - GROUP BY resource_type - """) - - resource_stats = {} - resource_warning = None - - for row in cur.fetchall(): - available_percent = round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - resource_stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': available_percent, - 'warning_level': 'danger' if row[1] < 50 else 'warning' if row[1] < 100 else 'success' - } - - # Warnung bei niedrigem Bestand - if row[1] < 50: - if not resource_warning: - resource_warning = f"Niedriger Bestand bei {row[0].upper()}: nur noch {row[1]} verfügbar!" - else: - resource_warning += f" | {row[0].upper()}: {row[1]}" - - cur.close() - conn.close() - - stats = { - 'total_customers': total_customers, - 'total_licenses': total_licenses, - 'active_licenses': active_licenses, - 'expired_licenses': expired_licenses, - 'inactive_licenses': inactive_licenses, - 'expiring_soon': expiring_soon, - 'full_licenses': license_types.get('full', 0), - 'test_licenses': license_types.get('test', 0), - 'test_data_count': test_data_count, - 'test_customers_count': test_customers_count, - 'test_resources_count': test_resources_count, - 'recent_licenses': recent_licenses, - 'expiring_licenses': expiring_licenses, - 'active_sessions': active_sessions_count, - 'last_backup': last_backup_info, - # Sicherheitsstatistiken - 'blocked_ips_count': blocked_ips_count, - 'failed_attempts_today': failed_attempts_today, - 'recent_security_events': recent_security_events, - 'security_level': security_level, - 'security_level_text': security_level_text, - 'resource_stats': resource_stats - } - - return render_template("dashboard.html", - stats=stats, - resource_stats=resource_stats, - resource_warning=resource_warning, - username=session.get('username')) - -@app.route("/create", methods=["GET", "POST"]) -@login_required -def create_license(): - if request.method == "POST": - customer_id = request.form.get("customer_id") - license_key = request.form["license_key"].upper() # Immer Großbuchstaben - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Validiere License Key Format - if not validate_license_key(license_key): - flash('Ungültiges License Key Format! Erwartet: AF-YYYYMMFT-XXXX-YYYY-ZZZZ', 'error') - return redirect(url_for('create_license')) - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('create_license')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('create_license')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - customer_info = {'name': name, 'email': email, 'is_test': is_test} - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos für Audit-Log - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('create_license')) - customer_info = {'name': customer_data[0], 'email': customer_data[1]} - - # Wenn Kunde Test-Kunde ist, Lizenz auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Lizenz hinzufügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit, is_test) - VALUES (%s, %s, %s, %s, %s, TRUE, %s, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit, is_test)) - license_id = cur.fetchone()[0] - - # Ressourcen zuweisen - try: - # Prüfe Verfügbarkeit - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {available[0]})") - if available[1] < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {ipv4_count}, verfügbar: {available[1]})") - if available[2] < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar (benötigt: {phone_count}, verfügbar: {available[2]})") - - # Domains zuweisen - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s zuweisen - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern zuweisen - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - except ValueError as e: - conn.rollback() - flash(str(e), 'error') - return redirect(url_for('create_license')) - - conn.commit() - - # Audit-Log - log_audit('CREATE', 'license', license_id, - new_values={ - 'license_key': license_key, - 'customer_name': customer_info['name'], - 'customer_email': customer_info['email'], - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'device_limit': device_limit, - 'is_test': is_test - }) - - flash(f'Lizenz {license_key} erfolgreich erstellt!', 'success') - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Erstellen der Lizenz: {str(e)}") - flash('Fehler beim Erstellen der Lizenz!', 'error') - finally: - cur.close() - conn.close() - - # Preserve show_test parameter if present - redirect_url = "/create" - if request.args.get('show_test') == 'true': - redirect_url += "?show_test=true" - return redirect(redirect_url) - - # Unterstützung für vorausgewählten Kunden - preselected_customer_id = request.args.get('customer_id', type=int) - return render_template("index.html", username=session.get('username'), preselected_customer_id=preselected_customer_id) - -@app.route("/batch", methods=["GET", "POST"]) -@login_required -def batch_licenses(): - """Batch-Generierung mehrerer Lizenzen für einen Kunden""" - if request.method == "POST": - # Formulardaten - customer_id = request.form.get("customer_id") - license_type = request.form["license_type"] - quantity = int(request.form["quantity"]) - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - # Sicherheitslimit - if quantity < 1 or quantity > 100: - flash('Anzahl muss zwischen 1 und 100 liegen!', 'error') - return redirect(url_for('batch_licenses')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('batch_licenses')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('batch_licenses')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('batch_licenses')) - name = customer_data[0] - email = customer_data[1] - - # Wenn Kunde Test-Kunde ist, Lizenzen auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Prüfe Ressourcen-Verfügbarkeit für gesamten Batch - total_domains_needed = domain_count * quantity - total_ipv4s_needed = ipv4_count * quantity - total_phones_needed = phone_count * quantity - - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < total_domains_needed: - flash(f"Nicht genügend Domains verfügbar (benötigt: {total_domains_needed}, verfügbar: {available[0]})", 'error') - return redirect(url_for('batch_licenses')) - if available[1] < total_ipv4s_needed: - flash(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {total_ipv4s_needed}, verfügbar: {available[1]})", 'error') - return redirect(url_for('batch_licenses')) - if available[2] < total_phones_needed: - flash(f"Nicht genügend Telefonnummern verfügbar (benötigt: {total_phones_needed}, verfügbar: {available[2]})", 'error') - return redirect(url_for('batch_licenses')) - - # Lizenzen generieren und speichern - generated_licenses = [] - for i in range(quantity): - # Eindeutigen Key generieren - attempts = 0 - while attempts < 10: - license_key = generate_license_key(license_type) - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (license_key,)) - if not cur.fetchone(): - break - attempts += 1 - - # Lizenz einfügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, is_test, - valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit) - VALUES (%s, %s, %s, %s, %s, %s, true, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, is_test, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit)) - license_id = cur.fetchone()[0] - - # Ressourcen für diese Lizenz zuweisen - # Domains - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - generated_licenses.append({ - 'id': license_id, - 'key': license_key, - 'type': license_type - }) - - conn.commit() - - # Audit-Log - log_audit('CREATE_BATCH', 'license', - new_values={'customer': name, 'quantity': quantity, 'type': license_type}, - additional_info=f"Batch-Generierung von {quantity} Lizenzen") - - # Session für Export speichern - session['batch_export'] = { - 'customer': name, - 'email': email, - 'licenses': generated_licenses, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'timestamp': datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - } - - flash(f'{quantity} Lizenzen erfolgreich generiert!', 'success') - return render_template("batch_result.html", - customer=name, - email=email, - licenses=generated_licenses, - valid_from=valid_from, - valid_until=valid_until) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler bei Batch-Generierung: {str(e)}") - flash('Fehler bei der Batch-Generierung!', 'error') - return redirect(url_for('batch_licenses')) - finally: - cur.close() - conn.close() - - # GET Request - return render_template("batch_form.html") - -@app.route("/batch/export") -@login_required -def export_batch(): - """Exportiert die zuletzt generierten Batch-Lizenzen""" - batch_data = session.get('batch_export') - if not batch_data: - flash('Keine Batch-Daten zum Exportieren vorhanden!', 'error') - return redirect(url_for('batch_licenses')) - - # CSV generieren - output = io.StringIO() - output.write('\ufeff') # UTF-8 BOM für Excel - - # Header - output.write(f"Kunde: {batch_data['customer']}\n") - output.write(f"E-Mail: {batch_data['email']}\n") - output.write(f"Generiert am: {datetime.fromisoformat(batch_data['timestamp']).strftime('%d.%m.%Y %H:%M')}\n") - output.write(f"Gültig von: {batch_data['valid_from']} bis {batch_data['valid_until']}\n") - output.write("\n") - output.write("Nr;Lizenzschlüssel;Typ\n") - - # Lizenzen - for i, license in enumerate(batch_data['licenses'], 1): - typ_text = "Vollversion" if license['type'] == 'full' else "Testversion" - output.write(f"{i};{license['key']};{typ_text}\n") - - output.seek(0) - - # Audit-Log - log_audit('EXPORT', 'batch_licenses', - additional_info=f"Export von {len(batch_data['licenses'])} Batch-Lizenzen") - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f"batch_licenses_{batch_data['customer'].replace(' ', '_')}_{datetime.now(ZoneInfo('Europe/Berlin')).strftime('%Y%m%d_%H%M%S')}.csv" - ) - -@app.route("/licenses") -@login_required -def licenses(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/license/edit/", methods=["GET", "POST"]) -@login_required -def edit_license(license_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute(""" - SELECT license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit - FROM licenses WHERE id = %s - """, (license_id,)) - old_license = cur.fetchone() - - # Update license - license_key = request.form["license_key"] - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - valid_until = request.form["valid_until"] - is_active = request.form.get("is_active") == "on" - is_test = request.form.get("is_test") == "on" - device_limit = int(request.form.get("device_limit", 3)) - - cur.execute(""" - UPDATE licenses - SET license_key = %s, license_type = %s, valid_from = %s, - valid_until = %s, is_active = %s, is_test = %s, device_limit = %s - WHERE id = %s - """, (license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit, license_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'license_key': old_license[0], - 'license_type': old_license[1], - 'valid_from': str(old_license[2]), - 'valid_until': str(old_license[3]), - 'is_active': old_license[4], - 'is_test': old_license[5], - 'device_limit': old_license[6] - }, - new_values={ - 'license_key': license_key, - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'is_active': is_active, - 'is_test': is_test, - 'device_limit': device_limit - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei wenn vorhanden - if request.referrer and 'customer_id=' in request.referrer: - import re - match = re.search(r'customer_id=(\d+)', request.referrer) - if match: - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={match.group(1)}" - - return redirect(redirect_url) - - # Get license data - cur.execute(""" - SELECT l.id, l.license_key, c.name, c.email, l.license_type, - l.valid_from, l.valid_until, l.is_active, c.id, l.is_test, l.device_limit - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - - license = cur.fetchone() - cur.close() - conn.close() - - if not license: - return redirect("/licenses") - - return render_template("edit_license.html", license=license, username=session.get('username')) - -@app.route("/license/delete/", methods=["POST"]) -@login_required -def delete_license(license_id): - conn = get_connection() - cur = conn.cursor() - - # Lizenzdetails für Audit-Log abrufen - cur.execute(""" - SELECT l.license_key, c.name, l.license_type - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - license_info = cur.fetchone() - - cur.execute("DELETE FROM licenses WHERE id = %s", (license_id,)) - - conn.commit() - - # Audit-Log - if license_info: - log_audit('DELETE', 'license', license_id, - old_values={ - 'license_key': license_info[0], - 'customer_name': license_info[1], - 'license_type': license_info[2] - }) - - cur.close() - conn.close() - - return redirect("/licenses") - -@app.route("/customers") -@login_required -def customers(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/customer/edit/", methods=["GET", "POST"]) -@login_required -def edit_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - old_customer = cur.fetchone() - - # Update customer - name = request.form["name"] - email = request.form["email"] - is_test = request.form.get("is_test") == "on" - - cur.execute(""" - UPDATE customers - SET name = %s, email = %s, is_test = %s - WHERE id = %s - """, (name, email, is_test, customer_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'customer', customer_id, - old_values={ - 'name': old_customer[0], - 'email': old_customer[1], - 'is_test': old_customer[2] - }, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei (immer der aktuelle Kunde) - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={customer_id}" - - return redirect(redirect_url) - - # Get customer data with licenses - cur.execute(""" - SELECT id, name, email, created_at, is_test FROM customers WHERE id = %s - """, (customer_id,)) - - customer = cur.fetchone() - if not customer: - cur.close() - conn.close() - return "Kunde nicht gefunden", 404 - - - # Get customer's licenses - cur.execute(""" - SELECT id, license_key, license_type, valid_from, valid_until, is_active - FROM licenses - WHERE customer_id = %s - ORDER BY valid_until DESC - """, (customer_id,)) - - licenses = cur.fetchall() - - cur.close() - conn.close() - - if not customer: - return redirect("/customers-licenses") - - return render_template("edit_customer.html", customer=customer, licenses=licenses, username=session.get('username')) - -@app.route("/customer/create", methods=["GET", "POST"]) -@login_required -def create_customer(): - """Erstellt einen neuen Kunden ohne Lizenz""" - if request.method == "POST": - name = request.form.get('name') - email = request.form.get('email') - is_test = request.form.get('is_test') == 'on' - - if not name or not email: - flash("Name und E-Mail sind Pflichtfelder!", "error") - return render_template("create_customer.html", username=session.get('username')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfen ob E-Mail bereits existiert - cur.execute("SELECT id, name FROM customers WHERE email = %s", (email,)) - existing = cur.fetchone() - if existing: - flash(f"Ein Kunde mit der E-Mail '{email}' existiert bereits: {existing[1]}", "error") - return render_template("create_customer.html", username=session.get('username')) - - # Kunde erstellen - cur.execute(""" - INSERT INTO customers (name, email, created_at, is_test) - VALUES (%s, %s, %s, %s) RETURNING id - """, (name, email, datetime.now(), is_test)) - - customer_id = cur.fetchone()[0] - conn.commit() - - # Audit-Log - log_audit('CREATE', 'customer', customer_id, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - flash(f"Kunde '{name}' wurde erfolgreich angelegt!", "success") - return redirect(f"/customer/edit/{customer_id}") - - except Exception as e: - conn.rollback() - flash(f"Fehler beim Anlegen des Kunden: {str(e)}", "error") - return render_template("create_customer.html", username=session.get('username')) - finally: - cur.close() - conn.close() - - # GET Request - Formular anzeigen - return render_template("create_customer.html", username=session.get('username')) - -@app.route("/customer/delete/", methods=["POST"]) -@login_required -def delete_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - # Prüfen ob Kunde Lizenzen hat - cur.execute("SELECT COUNT(*) FROM licenses WHERE customer_id = %s", (customer_id,)) - license_count = cur.fetchone()[0] - - if license_count > 0: - # Kunde hat Lizenzen - nicht löschen - cur.close() - conn.close() - return redirect("/customers") - - # Kundendetails für Audit-Log abrufen - cur.execute("SELECT name, email FROM customers WHERE id = %s", (customer_id,)) - customer_info = cur.fetchone() - - # Kunde löschen wenn keine Lizenzen vorhanden - cur.execute("DELETE FROM customers WHERE id = %s", (customer_id,)) - - conn.commit() - - # Audit-Log - if customer_info: - log_audit('DELETE', 'customer', customer_id, - old_values={ - 'name': customer_info[0], - 'email': customer_info[1] - }) - - cur.close() - conn.close() - - return redirect("/customers") - -@app.route("/customers-licenses") -@login_required -def customers_licenses(): - """Kombinierte Ansicht für Kunden und deren Lizenzen""" - conn = get_connection() - cur = conn.cursor() - - # Hole alle Kunden mit Lizenzstatistiken (inkl. Testkunden wenn gewünscht) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - query = """ - SELECT - c.id, - c.name, - c.email, - c.created_at, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - """ - - if not show_test: - query += " WHERE c.is_test = FALSE" - - query += """ - GROUP BY c.id, c.name, c.email, c.created_at - ORDER BY c.name - """ - - cur.execute(query) - customers = cur.fetchall() - - # Hole ausgewählten Kunden nur wenn explizit in URL angegeben - selected_customer_id = request.args.get('customer_id', type=int) - licenses = [] - selected_customer = None - - if customers and selected_customer_id: - # Hole Daten des ausgewählten Kunden - for customer in customers: - if customer[0] == selected_customer_id: - selected_customer = customer - break - - # Hole Lizenzen des ausgewählten Kunden - if selected_customer: - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (selected_customer_id,)) - licenses = cur.fetchall() - - cur.close() - conn.close() - - return render_template("customers_licenses.html", - customers=customers, - selected_customer=selected_customer, - selected_customer_id=selected_customer_id, - licenses=licenses, - show_test=show_test) - -@app.route("/api/customer//licenses") -@login_required -def api_customer_licenses(customer_id): - """API-Endpoint für AJAX-Abruf der Lizenzen eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Lizenzen des Kunden - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (customer_id,)) - - licenses = [] - for row in cur.fetchall(): - license_id = row[0] - - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for res_row in cur.fetchall(): - resource_info = { - 'id': res_row[0], - 'value': res_row[2], - 'assigned_at': res_row[3].strftime('%d.%m.%Y') if res_row[3] else '' - } - - if res_row[1] == 'domain': - resources['domains'].append(resource_info) - elif res_row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif res_row[1] == 'phone': - resources['phones'].append(resource_info) - - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'license_type': row[2], - 'valid_from': row[3].strftime('%d.%m.%Y') if row[3] else '', - 'valid_until': row[4].strftime('%d.%m.%Y') if row[4] else '', - 'is_active': row[5], - 'status': row[6], - 'domain_count': row[7], # limit - 'ipv4_count': row[8], # limit - 'phone_count': row[9], # limit - 'device_limit': row[10], - 'active_devices': row[11], - 'actual_domain_count': row[12], # actual count - 'actual_ipv4_count': row[13], # actual count - 'actual_phone_count': row[14], # actual count - 'resources': resources - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'licenses': licenses, - 'count': len(licenses) - }) - -@app.route("/api/customer//quick-stats") -@login_required -def api_customer_quick_stats(customer_id): - """API-Endpoint für Schnellstatistiken eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Kundenstatistiken - cur.execute(""" - SELECT - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' AND l.valid_until >= CURRENT_DATE THEN 1 END) as expiring_soon - FROM licenses l - WHERE l.customer_id = %s - """, (customer_id,)) - - stats = cur.fetchone() - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'stats': { - 'total': stats[0], - 'active': stats[1], - 'expired': stats[2], - 'expiring_soon': stats[3] - } - }) - -@app.route("/api/license//quick-edit", methods=['POST']) -@login_required -def api_license_quick_edit(license_id): - """API-Endpoint für schnelle Lizenz-Bearbeitung""" - conn = get_connection() - cur = conn.cursor() - - try: - data = request.get_json() - - # Hole alte Werte für Audit-Log - cur.execute(""" - SELECT is_active, valid_until, license_type - FROM licenses WHERE id = %s - """, (license_id,)) - old_values = cur.fetchone() - - if not old_values: - return jsonify({'success': False, 'error': 'Lizenz nicht gefunden'}), 404 - - # Update-Felder vorbereiten - updates = [] - params = [] - new_values = {} - - if 'is_active' in data: - updates.append("is_active = %s") - params.append(data['is_active']) - new_values['is_active'] = data['is_active'] - - if 'valid_until' in data: - updates.append("valid_until = %s") - params.append(data['valid_until']) - new_values['valid_until'] = data['valid_until'] - - if 'license_type' in data: - updates.append("license_type = %s") - params.append(data['license_type']) - new_values['license_type'] = data['license_type'] - - if updates: - params.append(license_id) - cur.execute(f""" - UPDATE licenses - SET {', '.join(updates)} - WHERE id = %s - """, params) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'is_active': old_values[0], - 'valid_until': old_values[1].isoformat() if old_values[1] else None, - 'license_type': old_values[2] - }, - new_values=new_values) - - cur.close() - conn.close() - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/api/license//resources") -@login_required -def api_license_resources(license_id): - """API-Endpoint für detaillierte Ressourcen-Informationen einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for row in cur.fetchall(): - resource_info = { - 'id': row[0], - 'value': row[2], - 'assigned_at': row[3].strftime('%d.%m.%Y') if row[3] else '' - } - - if row[1] == 'domain': - resources['domains'].append(resource_info) - elif row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif row[1] == 'phone': - resources['phones'].append(resource_info) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'resources': resources - }) - - except Exception as e: - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/sessions") -@login_required -def sessions(): - conn = get_connection() - cur = conn.cursor() - - # Sortierparameter - active_sort = request.args.get('active_sort', 'last_heartbeat') - active_order = request.args.get('active_order', 'desc') - ended_sort = request.args.get('ended_sort', 'ended_at') - ended_order = request.args.get('ended_order', 'desc') - - # Whitelist für erlaubte Sortierfelder - Aktive Sessions - active_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'last_heartbeat': 's.last_heartbeat', - 'inactive': 'minutes_inactive' - } - - # Whitelist für erlaubte Sortierfelder - Beendete Sessions - ended_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'ended_at': 's.ended_at', - 'duration': 'duration_minutes' - } - - # Validierung - if active_sort not in active_sort_fields: - active_sort = 'last_heartbeat' - if ended_sort not in ended_sort_fields: - ended_sort = 'ended_at' - if active_order not in ['asc', 'desc']: - active_order = 'desc' - if ended_order not in ['asc', 'desc']: - ended_order = 'desc' - - # Aktive Sessions abrufen - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.user_agent, s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.last_heartbeat))/60 as minutes_inactive - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = TRUE - ORDER BY {active_sort_fields[active_sort]} {active_order.upper()} - """) - active_sessions = cur.fetchall() - - # Inaktive Sessions der letzten 24 Stunden - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))/60 as duration_minutes - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = FALSE - AND s.ended_at > NOW() - INTERVAL '24 hours' - ORDER BY {ended_sort_fields[ended_sort]} {ended_order.upper()} - LIMIT 50 - """) - recent_sessions = cur.fetchall() - - cur.close() - conn.close() - - return render_template("sessions.html", - active_sessions=active_sessions, - recent_sessions=recent_sessions, - active_sort=active_sort, - active_order=active_order, - ended_sort=ended_sort, - ended_order=ended_order, - username=session.get('username')) - -@app.route("/session/end/", methods=["POST"]) -@login_required -def end_session(session_id): - conn = get_connection() - cur = conn.cursor() - - # Session beenden - cur.execute(""" - UPDATE sessions - SET is_active = FALSE, ended_at = NOW() - WHERE id = %s AND is_active = TRUE - """, (session_id,)) - - conn.commit() - cur.close() - conn.close() - - return redirect("/sessions") - -@app.route("/export/licenses") -@login_required -def export_licenses(): - conn = get_connection() - cur = conn.cursor() - - # Alle Lizenzen mit Kundeninformationen abrufen (ohne Testdaten, außer explizit gewünscht) - include_test = request.args.get('include_test', 'false').lower() == 'true' - customer_id = request.args.get('customer_id', type=int) - - query = """ - SELECT l.id, l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type, l.valid_from, l.valid_until, l.is_active, l.is_test, - CASE - WHEN l.is_active = FALSE THEN 'Deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'Abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'Läuft bald ab' - ELSE 'Aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - """ - - # Build WHERE clause - where_conditions = [] - params = [] - - if not include_test: - where_conditions.append("l.is_test = FALSE") - - if customer_id: - where_conditions.append("l.customer_id = %s") - params.append(customer_id) - - if where_conditions: - query += " WHERE " + " AND ".join(where_conditions) - - query += " ORDER BY l.id" - - cur.execute(query, params) - - # Spaltennamen - columns = ['ID', 'Lizenzschlüssel', 'Kunde', 'E-Mail', 'Typ', - 'Gültig von', 'Gültig bis', 'Aktiv', 'Testdaten', 'Status'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Gültig von'] = pd.to_datetime(df['Gültig von']).dt.strftime('%d.%m.%Y') - df['Gültig bis'] = pd.to_datetime(df['Gültig bis']).dt.strftime('%d.%m.%Y') - - # Typ und Aktiv Status anpassen - df['Typ'] = df['Typ'].replace({'full': 'Vollversion', 'test': 'Testversion'}) - df['Aktiv'] = df['Aktiv'].replace({True: 'Ja', False: 'Nein'}) - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'license', - additional_info=f"Export aller Lizenzen als {export_format.upper()}") - filename = f'lizenzen_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Lizenzen', index=False) - - # Formatierung - worksheet = writer.sheets['Lizenzen'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/audit") -@login_required -def export_audit(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_user = request.args.get('user', '') - filter_action = request.args.get('action', '') - filter_entity = request.args.get('entity', '') - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - params = [] - - if filter_user: - query += " AND username ILIKE %s" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - query += " ORDER BY timestamp DESC" - - cur.execute(query, params) - audit_logs = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for log in audit_logs: - action_text = { - 'CREATE': 'Erstellt', - 'UPDATE': 'Bearbeitet', - 'DELETE': 'Gelöscht', - 'LOGIN': 'Anmeldung', - 'LOGOUT': 'Abmeldung', - 'AUTO_LOGOUT': 'Auto-Logout', - 'EXPORT': 'Export', - 'GENERATE_KEY': 'Key generiert', - 'CREATE_BATCH': 'Batch erstellt', - 'BACKUP': 'Backup erstellt', - 'LOGIN_2FA_SUCCESS': '2FA-Anmeldung', - 'LOGIN_2FA_BACKUP': '2FA-Backup-Code', - 'LOGIN_2FA_FAILED': '2FA-Fehlgeschlagen', - 'LOGIN_BLOCKED': 'Login-Blockiert', - 'RESTORE': 'Wiederhergestellt', - 'PASSWORD_CHANGE': 'Passwort geändert', - '2FA_ENABLED': '2FA aktiviert', - '2FA_DISABLED': '2FA deaktiviert' - }.get(log[3], log[3]) - - data.append({ - 'ID': log[0], - 'Zeitstempel': log[1].strftime('%d.%m.%Y %H:%M:%S'), - 'Benutzer': log[2], - 'Aktion': action_text, - 'Entität': log[4], - 'Entität-ID': log[5] or '', - 'IP-Adresse': log[8] or '', - 'Zusatzinfo': log[10] or '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'audit_log_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'audit_log', - additional_info=f"{export_format.upper()} Export mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Audit Log') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Audit Log'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/customers") -@login_required -def export_customers(): - conn = get_connection() - cur = conn.cursor() - - # Check if test data should be included - include_test = request.args.get('include_test', 'false').lower() == 'true' - - # Build query based on test data filter - if include_test: - # Include all customers - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - else: - # Exclude test customers and test licenses - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(CASE WHEN l.is_test = FALSE THEN 1 END) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.is_test = FALSE - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - - cur.execute(query) - - # Spaltennamen - columns = ['ID', 'Name', 'E-Mail', 'Erstellt am', 'Testdaten', - 'Lizenzen gesamt', 'Aktive Lizenzen', 'Abgelaufene Lizenzen'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Erstellt am'] = pd.to_datetime(df['Erstellt am']).dt.strftime('%d.%m.%Y %H:%M') - - # Testdaten formatting - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'customer', - additional_info=f"Export aller Kunden als {export_format.upper()}") - filename = f'kunden_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Kunden', index=False) - - # Formatierung - worksheet = writer.sheets['Kunden'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/sessions") -@login_required -def export_sessions(): - conn = get_connection() - cur = conn.cursor() - - # Holen des Session-Typs (active oder ended) - session_type = request.args.get('type', 'active') - export_format = request.args.get('format', 'excel') - - # Daten je nach Typ abrufen - if session_type == 'active': - # Aktive Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = true - ORDER BY s.last_heartbeat DESC - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Letzte Aktivität': sess[5].strftime('%d.%m.%Y %H:%M:%S'), - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Aktive Sessions' - filename_prefix = 'aktive_sessions' - else: - # Beendete Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = false AND s.ended_at IS NOT NULL - ORDER BY s.ended_at DESC - LIMIT 1000 - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] if sess[6] else 0 - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Endzeit': sess[5].strftime('%d.%m.%Y %H:%M:%S') if sess[5] else '', - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Beendete Sessions' - filename_prefix = 'beendete_sessions' - - cur.close() - conn.close() - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'{filename_prefix}_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'sessions', - additional_info=f"{export_format.upper()} Export von {session_type} Sessions mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name=sheet_name) - - # Spaltenbreiten anpassen - worksheet = writer.sheets[sheet_name] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/resources") -@login_required -def export_resources(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_type = request.args.get('type', '') - filter_status = request.args.get('status', '') - search_query = request.args.get('search', '') - show_test = request.args.get('show_test', 'false').lower() == 'true' - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT r.id, r.resource_type, r.resource_value, r.status, r.allocated_to_license, - r.created_at, r.status_changed_at, - l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type - FROM resource_pools r - LEFT JOIN licenses l ON r.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE 1=1 - """ - params = [] - - # Filter für Testdaten - if not show_test: - query += " AND (r.is_test = false OR r.is_test IS NULL)" - - # Filter für Ressourcentyp - if filter_type: - query += " AND r.resource_type = %s" - params.append(filter_type) - - # Filter für Status - if filter_status: - query += " AND r.status = %s" - params.append(filter_status) - - # Suchfilter - if search_query: - query += " AND (r.resource_value ILIKE %s OR l.license_key ILIKE %s OR c.name ILIKE %s)" - params.extend([f'%{search_query}%', f'%{search_query}%', f'%{search_query}%']) - - query += " ORDER BY r.id DESC" - - cur.execute(query, params) - resources = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for res in resources: - status_text = { - 'available': 'Verfügbar', - 'allocated': 'Zugewiesen', - 'quarantine': 'Quarantäne' - }.get(res[3], res[3]) - - type_text = { - 'domain': 'Domain', - 'ipv4': 'IPv4', - 'phone': 'Telefon' - }.get(res[1], res[1]) - - data.append({ - 'ID': res[0], - 'Typ': type_text, - 'Ressource': res[2], - 'Status': status_text, - 'Lizenzschlüssel': res[7] or '', - 'Kunde': res[8] or '', - 'Kunden-Email': res[9] or '', - 'Lizenztyp': res[10] or '', - 'Erstellt am': res[5].strftime('%d.%m.%Y %H:%M:%S') if res[5] else '', - 'Zugewiesen am': res[6].strftime('%d.%m.%Y %H:%M:%S') if res[6] else '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'resources_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'resources', - additional_info=f"{export_format.upper()} Export mit {len(data)} Ressourcen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Resources') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Resources'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/audit") -@login_required -def audit_log(): - conn = get_connection() - cur = conn.cursor() - - # Parameter - filter_user = request.args.get('user', '').strip() - filter_action = request.args.get('action', '').strip() - filter_entity = request.args.get('entity', '').strip() - page = request.args.get('page', 1, type=int) - sort = request.args.get('sort', 'timestamp') - order = request.args.get('order', 'desc') - per_page = 50 - - # Whitelist für erlaubte Sortierfelder - allowed_sort_fields = { - 'timestamp': 'timestamp', - 'username': 'username', - 'action': 'action', - 'entity': 'entity_type', - 'ip': 'ip_address' - } - - # Validierung - if sort not in allowed_sort_fields: - sort = 'timestamp' - if order not in ['asc', 'desc']: - order = 'desc' - - sort_field = allowed_sort_fields[sort] - - # SQL Query mit optionalen Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - - params = [] - - # Filter - if filter_user: - query += " AND LOWER(username) LIKE LOWER(%s)" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - # Gesamtanzahl für Pagination - count_query = "SELECT COUNT(*) FROM (" + query + ") as count_table" - cur.execute(count_query, params) - total = cur.fetchone()[0] - - # Pagination - offset = (page - 1) * per_page - query += f" ORDER BY {sort_field} {order.upper()} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - logs = cur.fetchall() - - # JSON-Werte parsen - parsed_logs = [] - for log in logs: - parsed_log = list(log) - # old_values und new_values sind bereits Dictionaries (JSONB) - # Keine Konvertierung nötig - parsed_logs.append(parsed_log) - - # Pagination Info - total_pages = (total + per_page - 1) // per_page - - cur.close() - conn.close() - - return render_template("audit_log.html", - logs=parsed_logs, - filter_user=filter_user, - filter_action=filter_action, - filter_entity=filter_entity, - page=page, - total_pages=total_pages, - total=total, - sort=sort, - order=order, - username=session.get('username')) - -@app.route("/backups") -@login_required -def backups(): - """Zeigt die Backup-Historie an""" - conn = get_connection() - cur = conn.cursor() - - # Letztes erfolgreiches Backup für Dashboard - cur.execute(""" - SELECT created_at, filesize, duration_seconds - FROM backup_history - WHERE status = 'success' - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup = cur.fetchone() - - # Alle Backups abrufen - cur.execute(""" - SELECT id, filename, filesize, backup_type, status, error_message, - created_at, created_by, tables_count, records_count, - duration_seconds, is_encrypted - FROM backup_history - ORDER BY created_at DESC - """) - backups = cur.fetchall() - - cur.close() - conn.close() - - return render_template("backups.html", - backups=backups, - last_backup=last_backup, - username=session.get('username')) - -@app.route("/backup/create", methods=["POST"]) -@login_required -def create_backup_route(): - """Erstellt ein manuelles Backup""" - username = session.get('username') - success, result = create_backup(backup_type="manual", created_by=username) - - if success: - return jsonify({ - 'success': True, - 'message': f'Backup erfolgreich erstellt: {result}' - }) - else: - return jsonify({ - 'success': False, - 'message': f'Backup fehlgeschlagen: {result}' - }), 500 - -@app.route("/backup/restore/", methods=["POST"]) -@login_required -def restore_backup_route(backup_id): - """Stellt ein Backup wieder her""" - encryption_key = request.form.get('encryption_key') - - success, message = restore_backup(backup_id, encryption_key) - - if success: - return jsonify({ - 'success': True, - 'message': message - }) - else: - return jsonify({ - 'success': False, - 'message': message - }), 500 - -@app.route("/backup/download/") -@login_required -def download_backup(backup_id): - """Lädt eine Backup-Datei herunter""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - cur.close() - conn.close() - - if not backup_info: - return "Backup nicht gefunden", 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - if not filepath.exists(): - return "Backup-Datei nicht gefunden", 404 - - # Audit-Log - log_audit('DOWNLOAD', 'backup', backup_id, - additional_info=f"Backup heruntergeladen: {filename}") - - return send_file(filepath, as_attachment=True, download_name=filename) - -@app.route("/backup/delete/", methods=["DELETE"]) -@login_required -def delete_backup(backup_id): - """Löscht ein Backup""" - conn = get_connection() - cur = conn.cursor() - - try: - # Backup-Informationen abrufen - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - if not backup_info: - return jsonify({ - 'success': False, - 'message': 'Backup nicht gefunden' - }), 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - # Datei löschen, wenn sie existiert - if filepath.exists(): - filepath.unlink() - - # Aus Datenbank löschen - cur.execute(""" - DELETE FROM backup_history - WHERE id = %s - """, (backup_id,)) - - conn.commit() - - # Audit-Log - log_audit('DELETE', 'backup', backup_id, - additional_info=f"Backup gelöscht: {filename}") - - return jsonify({ - 'success': True, - 'message': f'Backup "{filename}" wurde erfolgreich gelöscht' - }) - - except Exception as e: - conn.rollback() - return jsonify({ - 'success': False, - 'message': f'Fehler beim Löschen des Backups: {str(e)}' - }), 500 - finally: - cur.close() - conn.close() - -@app.route("/security/blocked-ips") -@login_required -def blocked_ips(): - """Zeigt alle gesperrten IPs an""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT - ip_address, - attempt_count, - first_attempt, - last_attempt, - blocked_until, - last_username_tried, - last_error_message - FROM login_attempts - WHERE blocked_until IS NOT NULL - ORDER BY blocked_until DESC - """) - - blocked_ips_list = [] - for ip in cur.fetchall(): - blocked_ips_list.append({ - 'ip_address': ip[0], - 'attempt_count': ip[1], - 'first_attempt': ip[2].strftime('%d.%m.%Y %H:%M'), - 'last_attempt': ip[3].strftime('%d.%m.%Y %H:%M'), - 'blocked_until': ip[4].strftime('%d.%m.%Y %H:%M'), - 'is_active': ip[4] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None), - 'last_username': ip[5], - 'last_error': ip[6] - }) - - cur.close() - conn.close() - - return render_template("blocked_ips.html", - blocked_ips=blocked_ips_list, - username=session.get('username')) - -@app.route("/security/unblock-ip", methods=["POST"]) -@login_required -def unblock_ip(): - """Entsperrt eine IP-Adresse""" - ip_address = request.form.get('ip_address') - - if ip_address: - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - UPDATE login_attempts - SET blocked_until = NULL - WHERE ip_address = %s - """, (ip_address,)) - - conn.commit() - cur.close() - conn.close() - - # Audit-Log - log_audit('UNBLOCK_IP', 'security', - additional_info=f"IP {ip_address} manuell entsperrt") - - return redirect(url_for('blocked_ips')) - -@app.route("/security/clear-attempts", methods=["POST"]) -@login_required -def clear_attempts(): - """Löscht alle Login-Versuche für eine IP""" - ip_address = request.form.get('ip_address') - - if ip_address: - reset_login_attempts(ip_address) - - # Audit-Log - log_audit('CLEAR_ATTEMPTS', 'security', - additional_info=f"Login-Versuche für IP {ip_address} zurückgesetzt") - - return redirect(url_for('blocked_ips')) - -# API Endpoints for License Management -@app.route("/api/license//toggle", methods=["POST"]) -@login_required -def toggle_license_api(license_id): - """Toggle license active status via API""" - try: - data = request.get_json() - is_active = data.get('is_active', False) - - conn = get_connection() - cur = conn.cursor() - - # Update license status - cur.execute(""" - UPDATE licenses - SET is_active = %s - WHERE id = %s - """, (is_active, license_id)) - - conn.commit() - - # Log the action - log_audit('UPDATE', 'license', license_id, - new_values={'is_active': is_active}, - additional_info=f"Lizenz {'aktiviert' if is_active else 'deaktiviert'} via Toggle") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Status erfolgreich geändert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-activate", methods=["POST"]) -@login_required -def bulk_activate_licenses(): - """Activate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = TRUE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': True, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen aktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen aktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-deactivate", methods=["POST"]) -@login_required -def bulk_deactivate_licenses(): - """Deactivate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = FALSE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': False, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen deaktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen deaktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/license//devices") -@login_required -def get_license_devices(license_id): - """Hole alle registrierten Geräte einer Lizenz""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und hole device_limit - cur.execute(""" - SELECT device_limit FROM licenses WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit = license_data[0] - - # Hole alle Geräte für diese Lizenz - cur.execute(""" - SELECT id, hardware_id, device_name, operating_system, - first_seen, last_seen, is_active, ip_address - FROM device_registrations - WHERE license_id = %s - ORDER BY is_active DESC, last_seen DESC - """, (license_id,)) - - devices = [] - for row in cur.fetchall(): - devices.append({ - 'id': row[0], - 'hardware_id': row[1], - 'device_name': row[2] or 'Unbekanntes Gerät', - 'operating_system': row[3] or 'Unbekannt', - 'first_seen': row[4].strftime('%d.%m.%Y %H:%M') if row[4] else '', - 'last_seen': row[5].strftime('%d.%m.%Y %H:%M') if row[5] else '', - 'is_active': row[6], - 'ip_address': row[7] or '-' - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'devices': devices, - 'device_limit': device_limit, - 'active_count': sum(1 for d in devices if d['is_active']) - }) - - except Exception as e: - logging.error(f"Fehler beim Abrufen der Geräte: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Abrufen der Geräte'}), 500 - -@app.route("/api/license//register-device", methods=["POST"]) -def register_device(license_id): - """Registriere ein neues Gerät für eine Lizenz""" - try: - data = request.get_json() - hardware_id = data.get('hardware_id') - device_name = data.get('device_name', '') - operating_system = data.get('operating_system', '') - - if not hardware_id: - return jsonify({'success': False, 'message': 'Hardware-ID fehlt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und aktiv ist - cur.execute(""" - SELECT device_limit, is_active, valid_until - FROM licenses - WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit, is_active, valid_until = license_data - - # Prüfe ob Lizenz aktiv und gültig ist - if not is_active: - return jsonify({'success': False, 'message': 'Lizenz ist deaktiviert'}), 403 - - if valid_until < datetime.now(ZoneInfo("Europe/Berlin")).date(): - return jsonify({'success': False, 'message': 'Lizenz ist abgelaufen'}), 403 - - # Prüfe ob Gerät bereits registriert ist - cur.execute(""" - SELECT id, is_active FROM device_registrations - WHERE license_id = %s AND hardware_id = %s - """, (license_id, hardware_id)) - existing_device = cur.fetchone() - - if existing_device: - device_id, is_device_active = existing_device - if is_device_active: - # Gerät ist bereits aktiv, update last_seen - cur.execute(""" - UPDATE device_registrations - SET last_seen = CURRENT_TIMESTAMP, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät bereits registriert', 'device_id': device_id}) - else: - # Gerät war deaktiviert, prüfe ob wir es reaktivieren können - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Reaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = TRUE, - last_seen = CURRENT_TIMESTAMP, - deactivated_at = NULL, - deactivated_by = NULL, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät reaktiviert', 'device_id': device_id}) - - # Neues Gerät - prüfe Gerätelimit - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Registriere neues Gerät - cur.execute(""" - INSERT INTO device_registrations - (license_id, hardware_id, device_name, operating_system, ip_address, user_agent) - VALUES (%s, %s, %s, %s, %s, %s) - RETURNING id - """, (license_id, hardware_id, device_name, operating_system, - get_client_ip(), request.headers.get('User-Agent', ''))) - device_id = cur.fetchone()[0] - - conn.commit() - - # Audit Log - log_audit('DEVICE_REGISTER', 'device', device_id, - new_values={'license_id': license_id, 'hardware_id': hardware_id}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich registriert', 'device_id': device_id}) - - except Exception as e: - logging.error(f"Fehler bei Geräte-Registrierung: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler bei der Registrierung'}), 500 - -@app.route("/api/license//deactivate-device/", methods=["POST"]) -@login_required -def deactivate_device(license_id, device_id): - """Deaktiviere ein registriertes Gerät""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob das Gerät zu dieser Lizenz gehört - cur.execute(""" - SELECT id FROM device_registrations - WHERE id = %s AND license_id = %s AND is_active = TRUE - """, (device_id, license_id)) - - if not cur.fetchone(): - return jsonify({'success': False, 'message': 'Gerät nicht gefunden oder bereits deaktiviert'}), 404 - - # Deaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = FALSE, - deactivated_at = CURRENT_TIMESTAMP, - deactivated_by = %s - WHERE id = %s - """, (session['username'], device_id)) - - conn.commit() - - # Audit Log - log_audit('DEVICE_DEACTIVATE', 'device', device_id, - old_values={'is_active': True}, - new_values={'is_active': False}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich deaktiviert'}) - - except Exception as e: - logging.error(f"Fehler beim Deaktivieren des Geräts: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Deaktivieren'}), 500 - -@app.route("/api/licenses/bulk-delete", methods=["POST"]) -@login_required -def bulk_delete_licenses(): - """Delete multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Get license info for audit log (nur Live-Daten) - cur.execute(""" - SELECT license_key - FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - license_keys = [row[0] for row in cur.fetchall()] - - # Delete all selected licenses (nur Live-Daten) - cur.execute(""" - DELETE FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_DELETE', 'licenses', None, - old_values={'license_keys': license_keys, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen gelöscht") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen gelöscht'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# ===================== RESOURCE POOL MANAGEMENT ===================== - -@app.route('/resources') -@login_required -def resources(): - """Resource Pool Hauptübersicht""" - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Testdaten angezeigt werden sollen (gleiche Logik wie bei Kunden) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - # Statistiken abrufen - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = %s - GROUP BY resource_type - """, (show_test,)) - - stats = {} - for row in cur.fetchall(): - stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - } - - # Letzte Aktivitäten (gefiltert nach Test/Live) - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rp.resource_type, - rp.resource_value, - rh.details - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - WHERE rp.is_test = %s - ORDER BY rh.action_at DESC - LIMIT 10 - """, (show_test,)) - recent_activities = cur.fetchall() - - # Ressourcen-Liste mit Pagination - page = request.args.get('page', 1, type=int) - per_page = 50 - offset = (page - 1) * per_page - - resource_type = request.args.get('type', '') - status_filter = request.args.get('status', '') - search = request.args.get('search', '') - - # Sortierung - sort_by = request.args.get('sort', 'id') - sort_order = request.args.get('order', 'desc') - - # Base Query - query = """ - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - rp.allocated_to_license, - l.license_key, - c.name as customer_name, - rp.status_changed_at, - rp.quarantine_reason, - rp.quarantine_until, - c.id as customer_id - FROM resource_pools rp - LEFT JOIN licenses l ON rp.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rp.is_test = %s - """ - params = [show_test] - - if resource_type: - query += " AND rp.resource_type = %s" - params.append(resource_type) - - if status_filter: - query += " AND rp.status = %s" - params.append(status_filter) - - if search: - query += " AND rp.resource_value ILIKE %s" - params.append(f'%{search}%') - - # Count total - count_query = f"SELECT COUNT(*) FROM ({query}) as cnt" - cur.execute(count_query, params) - total = cur.fetchone()[0] - total_pages = (total + per_page - 1) // per_page - - # Get paginated results with dynamic sorting - sort_column_map = { - 'id': 'rp.id', - 'type': 'rp.resource_type', - 'resource': 'rp.resource_value', - 'status': 'rp.status', - 'assigned': 'c.name', - 'changed': 'rp.status_changed_at' - } - - sort_column = sort_column_map.get(sort_by, 'rp.id') - sort_direction = 'ASC' if sort_order == 'asc' else 'DESC' - - query += f" ORDER BY {sort_column} {sort_direction} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - resources = cur.fetchall() - - cur.close() - conn.close() - - return render_template('resources.html', - stats=stats, - resources=resources, - recent_activities=recent_activities, - page=page, - total_pages=total_pages, - total=total, - resource_type=resource_type, - status_filter=status_filter, - search=search, - show_test=show_test, - sort_by=sort_by, - sort_order=sort_order, - datetime=datetime, - timedelta=timedelta) - -@app.route('/resources/add', methods=['GET', 'POST']) -@login_required -def add_resources(): - """Ressourcen zum Pool hinzufügen""" - # Hole show_test Parameter für die Anzeige - show_test = request.args.get('show_test', 'false').lower() == 'true' - - if request.method == 'POST': - resource_type = request.form.get('resource_type') - resources_text = request.form.get('resources_text', '') - is_test = request.form.get('is_test') == 'on' # Checkbox für Testdaten - - # Parse resources (one per line) - resources = [r.strip() for r in resources_text.split('\n') if r.strip()] - - if not resources: - flash('Keine Ressourcen angegeben', 'error') - return redirect(url_for('add_resources', show_test=show_test)) - - conn = get_connection() - cur = conn.cursor() - - added = 0 - duplicates = 0 - - for resource_value in resources: - try: - cur.execute(""" - INSERT INTO resource_pools (resource_type, resource_value, status_changed_by, is_test) - VALUES (%s, %s, %s, %s) - ON CONFLICT (resource_type, resource_value) DO NOTHING - """, (resource_type, resource_value, session['username'], is_test)) - - if cur.rowcount > 0: - added += 1 - # Get the inserted ID - cur.execute("SELECT id FROM resource_pools WHERE resource_type = %s AND resource_value = %s", - (resource_type, resource_value)) - resource_id = cur.fetchone()[0] - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'created', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - else: - duplicates += 1 - - except Exception as e: - app.logger.error(f"Error adding resource {resource_value}: {e}") - - conn.commit() - cur.close() - conn.close() - - log_audit('CREATE', 'resource_pool', None, - new_values={'type': resource_type, 'added': added, 'duplicates': duplicates, 'is_test': is_test}, - additional_info=f"{added} {'Test-' if is_test else ''}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen") - - flash(f'{added} {"Test-" if is_test else ""}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen', 'success') - return redirect(url_for('resources', show_test=show_test)) - - return render_template('add_resources.html', show_test=show_test) - -@app.route('/resources/quarantine/', methods=['POST']) -@login_required -def quarantine_resource(resource_id): - """Ressource in Quarantäne setzen""" - reason = request.form.get('reason', 'review') - until_date = request.form.get('until_date') - notes = request.form.get('notes', '') - - conn = get_connection() - cur = conn.cursor() - - # Get current resource info - cur.execute("SELECT resource_type, resource_value, status FROM resource_pools WHERE id = %s", (resource_id,)) - resource = cur.fetchone() - - if not resource: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - old_status = resource[2] - - # Update resource - cur.execute(""" - UPDATE resource_pools - SET status = 'quarantine', - quarantine_reason = %s, - quarantine_until = %s, - notes = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (reason, until_date if until_date else None, notes, session['username'], resource_id)) - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address, details) - VALUES (%s, 'quarantined', %s, %s, %s) - """, (resource_id, session['username'], get_client_ip(), - Json({'reason': reason, 'until': until_date, 'notes': notes, 'old_status': old_status}))) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource', resource_id, - old_values={'status': old_status}, - new_values={'status': 'quarantine', 'reason': reason}, - additional_info=f"Ressource {resource[0]}: {resource[1]} in Quarantäne") - - flash('Ressource in Quarantäne gesetzt', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/resources/release', methods=['POST']) -@login_required -def release_resources(): - """Ressourcen aus Quarantäne freigeben""" - resource_ids = request.form.getlist('resource_ids') - - if not resource_ids: - flash('Keine Ressourcen ausgewählt', 'error') - return redirect(url_for('resources')) - - conn = get_connection() - cur = conn.cursor() - - released = 0 - for resource_id in resource_ids: - cur.execute(""" - UPDATE resource_pools - SET status = 'available', - quarantine_reason = NULL, - quarantine_until = NULL, - allocated_to_license = NULL, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s AND status = 'quarantine' - """, (session['username'], resource_id)) - - if cur.rowcount > 0: - released += 1 - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'released', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource_pool', None, - new_values={'released': released}, - additional_info=f"{released} Ressourcen aus Quarantäne freigegeben") - - flash(f'{released} Ressourcen freigegeben', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/api/resources/allocate', methods=['POST']) -@login_required -def allocate_resources_api(): - """API für Ressourcen-Zuweisung bei Lizenzerstellung""" - data = request.json - license_id = data.get('license_id') - domain_count = data.get('domain_count', 1) - ipv4_count = data.get('ipv4_count', 1) - phone_count = data.get('phone_count', 1) - - conn = get_connection() - cur = conn.cursor() - - try: - allocated = {'domains': [], 'ipv4s': [], 'phones': []} - - # Allocate domains - if domain_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' - LIMIT %s FOR UPDATE - """, (domain_count,)) - domains = cur.fetchall() - - if len(domains) < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {len(domains)})") - - for domain_id, domain_value in domains: - # Update resource status - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], domain_id)) - - # Create assignment - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, domain_id, session['username'])) - - # Log history - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (domain_id, license_id, session['username'], get_client_ip())) - - allocated['domains'].append(domain_value) - - # Allocate IPv4s (similar logic) - if ipv4_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' - LIMIT %s FOR UPDATE - """, (ipv4_count,)) - ipv4s = cur.fetchall() - - if len(ipv4s) < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar") - - for ipv4_id, ipv4_value in ipv4s: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], ipv4_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, ipv4_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (ipv4_id, license_id, session['username'], get_client_ip())) - - allocated['ipv4s'].append(ipv4_value) - - # Allocate phones (similar logic) - if phone_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' - LIMIT %s FOR UPDATE - """, (phone_count,)) - phones = cur.fetchall() - - if len(phones) < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar") - - for phone_id, phone_value in phones: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], phone_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, phone_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (phone_id, license_id, session['username'], get_client_ip())) - - allocated['phones'].append(phone_value) - - # Update license resource counts - cur.execute(""" - UPDATE licenses - SET domain_count = %s, - ipv4_count = %s, - phone_count = %s - WHERE id = %s - """, (domain_count, ipv4_count, phone_count, license_id)) - - conn.commit() - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'allocated': allocated - }) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({ - 'success': False, - 'error': str(e) - }), 400 - -@app.route('/api/resources/check-availability', methods=['GET']) -@login_required -def check_resource_availability(): - """Prüft verfügbare Ressourcen""" - resource_type = request.args.get('type', '') - count = request.args.get('count', 10, type=int) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - conn = get_connection() - cur = conn.cursor() - - if resource_type: - # Spezifische Ressourcen für einen Typ - cur.execute(""" - SELECT id, resource_value - FROM resource_pools - WHERE status = 'available' - AND resource_type = %s - AND is_test = %s - ORDER BY resource_value - LIMIT %s - """, (resource_type, show_test, count)) - - resources = [] - for row in cur.fetchall(): - resources.append({ - 'id': row[0], - 'value': row[1] - }) - - cur.close() - conn.close() - - return jsonify({ - 'available': resources, - 'type': resource_type, - 'count': len(resources) - }) - else: - # Zusammenfassung aller Typen - cur.execute(""" - SELECT - resource_type, - COUNT(*) as available - FROM resource_pools - WHERE status = 'available' - AND is_test = %s - GROUP BY resource_type - """, (show_test,)) - - availability = {} - for row in cur.fetchall(): - availability[row[0]] = row[1] - - cur.close() - conn.close() - - return jsonify(availability) - -@app.route('/api/global-search', methods=['GET']) -@login_required -def global_search(): - """Global search API endpoint for searching customers and licenses""" - query = request.args.get('q', '').strip() - - if not query or len(query) < 2: - return jsonify({'customers': [], 'licenses': []}) - - conn = get_connection() - cur = conn.cursor() - - # Search pattern with wildcards - search_pattern = f'%{query}%' - - # Search customers - cur.execute(""" - SELECT id, name, email, company_name - FROM customers - WHERE (LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - OR LOWER(company_name) LIKE LOWER(%s)) - AND is_test = FALSE - ORDER BY name - LIMIT 5 - """, (search_pattern, search_pattern, search_pattern)) - - customers = [] - for row in cur.fetchall(): - customers.append({ - 'id': row[0], - 'name': row[1], - 'email': row[2], - 'company_name': row[3] - }) - - # Search licenses - cur.execute(""" - SELECT l.id, l.license_key, c.name as customer_name - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE LOWER(l.license_key) LIKE LOWER(%s) - AND l.is_test = FALSE - ORDER BY l.created_at DESC - LIMIT 5 - """, (search_pattern,)) - - licenses = [] - for row in cur.fetchall(): - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'customer_name': row[2] - }) - - cur.close() - conn.close() - - return jsonify({ - 'customers': customers, - 'licenses': licenses - }) - -@app.route('/resources/history/') -@login_required -def resource_history(resource_id): - """Zeigt die komplette Historie einer Ressource""" - conn = get_connection() - cur = conn.cursor() - - # Get complete resource info using named columns - cur.execute(""" - SELECT id, resource_type, resource_value, status, allocated_to_license, - status_changed_at, status_changed_by, quarantine_reason, - quarantine_until, created_at, notes - FROM resource_pools - WHERE id = %s - """, (resource_id,)) - row = cur.fetchone() - - if not row: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - # Create resource object with named attributes - resource = { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'allocated_to_license': row[4], - 'status_changed_at': row[5], - 'status_changed_by': row[6], - 'quarantine_reason': row[7], - 'quarantine_until': row[8], - 'created_at': row[9], - 'notes': row[10] - } - - # Get license info if allocated - license_info = None - if resource['allocated_to_license']: - cur.execute("SELECT license_key FROM licenses WHERE id = %s", - (resource['allocated_to_license'],)) - lic = cur.fetchone() - if lic: - license_info = {'license_key': lic[0]} - - # Get history with named columns - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rh.details, - rh.license_id, - rh.ip_address - FROM resource_history rh - WHERE rh.resource_id = %s - ORDER BY rh.action_at DESC - """, (resource_id,)) - - history = [] - for row in cur.fetchall(): - history.append({ - 'action': row[0], - 'action_by': row[1], - 'action_at': row[2], - 'details': row[3], - 'license_id': row[4], - 'ip_address': row[5] - }) - - cur.close() - conn.close() - - # Convert to object-like for template - class ResourceObj: - def __init__(self, data): - for key, value in data.items(): - setattr(self, key, value) - - resource_obj = ResourceObj(resource) - history_objs = [ResourceObj(h) for h in history] - - return render_template('resource_history.html', - resource=resource_obj, - license_info=license_info, - history=history_objs) - -@app.route('/resources/metrics') -@login_required -def resources_metrics(): - """Dashboard für Resource Metrics und Reports""" - conn = get_connection() - cur = conn.cursor() - - # Overall stats with fallback values - cur.execute(""" - SELECT - COUNT(DISTINCT resource_id) as total_resources, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(cost), 0) as total_cost, - COALESCE(SUM(revenue), 0) as total_revenue, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - """) - row = cur.fetchone() - - # Calculate ROI - roi = 0 - if row[2] > 0: # if total_cost > 0 - roi = row[3] / row[2] # revenue / cost - - stats = { - 'total_resources': row[0] or 0, - 'avg_performance': row[1] or 0, - 'total_cost': row[2] or 0, - 'total_revenue': row[3] or 0, - 'total_issues': row[4] or 0, - 'roi': roi - } - - # Performance by type - cur.execute(""" - SELECT - rp.resource_type, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COUNT(DISTINCT rp.id) as resource_count - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY rp.resource_type - ORDER BY rp.resource_type - """) - performance_by_type = cur.fetchall() - - # Utilization data - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) as total, - ROUND(COUNT(*) FILTER (WHERE status = 'allocated') * 100.0 / COUNT(*), 1) as allocated_percent - FROM resource_pools - GROUP BY resource_type - """) - utilization_rows = cur.fetchall() - utilization_data = [ - { - 'type': row[0].upper(), - 'allocated': row[1], - 'total': row[2], - 'allocated_percent': row[3] - } - for row in utilization_rows - ] - - # Top performing resources - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COALESCE(SUM(rm.revenue), 0) as total_revenue, - COALESCE(SUM(rm.cost), 1) as total_cost, - CASE - WHEN COALESCE(SUM(rm.cost), 0) = 0 THEN 0 - ELSE COALESCE(SUM(rm.revenue), 0) / COALESCE(SUM(rm.cost), 1) - END as roi - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rp.status != 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value - HAVING AVG(rm.performance_score) IS NOT NULL - ORDER BY avg_score DESC - LIMIT 10 - """) - top_rows = cur.fetchall() - top_performers = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'avg_score': row[3], - 'roi': row[6] - } - for row in top_rows - ] - - # Resources with issues - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - COALESCE(SUM(rm.issues_count), 0) as total_issues - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rm.issues_count > 0 OR rp.status = 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - HAVING SUM(rm.issues_count) > 0 - ORDER BY total_issues DESC - LIMIT 10 - """) - problem_rows = cur.fetchall() - problem_resources = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'total_issues': row[4] - } - for row in problem_rows - ] - - # Daily metrics for trend chart (last 30 days) - cur.execute(""" - SELECT - metric_date, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY metric_date - ORDER BY metric_date - """) - daily_rows = cur.fetchall() - daily_metrics = [ - { - 'date': row[0].strftime('%d.%m'), - 'performance': float(row[1]), - 'issues': int(row[2]) - } - for row in daily_rows - ] - - cur.close() - conn.close() - - return render_template('resource_metrics.html', - stats=stats, - performance_by_type=performance_by_type, - utilization_data=utilization_data, - top_performers=top_performers, - problem_resources=problem_resources, - daily_metrics=daily_metrics) - -@app.route('/resources/report', methods=['GET']) -@login_required -def resources_report(): - """Generiert Ressourcen-Reports oder zeigt Report-Formular""" - # Prüfe ob Download angefordert wurde - if request.args.get('download') == 'true': - report_type = request.args.get('type', 'usage') - format_type = request.args.get('format', 'excel') - date_from = request.args.get('from', (datetime.now(ZoneInfo("Europe/Berlin")) - timedelta(days=30)).strftime('%Y-%m-%d')) - date_to = request.args.get('to', datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y-%m-%d')) - - conn = get_connection() - cur = conn.cursor() - - if report_type == 'usage': - # Auslastungsreport - query = """ - SELECT - rp.resource_type, - rp.resource_value, - rp.status, - COUNT(DISTINCT rh.license_id) as unique_licenses, - COUNT(rh.id) as total_allocations, - MIN(rh.action_at) as first_used, - MAX(rh.action_at) as last_used - FROM resource_pools rp - LEFT JOIN resource_history rh ON rp.id = rh.resource_id - AND rh.action = 'allocated' - AND rh.action_at BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - ORDER BY rp.resource_type, total_allocations DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Status', 'Unique Lizenzen', 'Gesamt Zuweisungen', 'Erste Nutzung', 'Letzte Nutzung'] - - elif report_type == 'performance': - # Performance-Report - query = """ - SELECT - rp.resource_type, - rp.resource_value, - AVG(rm.performance_score) as avg_performance, - SUM(rm.usage_count) as total_usage, - SUM(rm.revenue) as total_revenue, - SUM(rm.cost) as total_cost, - SUM(rm.revenue - rm.cost) as profit, - SUM(rm.issues_count) as total_issues - FROM resource_pools rp - JOIN resource_metrics rm ON rp.id = rm.resource_id - WHERE rm.metric_date BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value - ORDER BY profit DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Durchschn. Performance', 'Gesamt Nutzung', 'Umsatz', 'Kosten', 'Gewinn', 'Issues'] - - elif report_type == 'compliance': - # Compliance-Report - query = """ - SELECT - rh.action_at, - rh.action, - rh.action_by, - rp.resource_type, - rp.resource_value, - l.license_key, - c.name as customer_name, - rh.ip_address - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - LEFT JOIN licenses l ON rh.license_id = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rh.action_at BETWEEN %s AND %s - ORDER BY rh.action_at DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Zeit', 'Aktion', 'Von', 'Typ', 'Ressource', 'Lizenz', 'Kunde', 'IP-Adresse'] - - else: # inventory report - # Inventar-Report - query = """ - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - GROUP BY resource_type - ORDER BY resource_type - """ - cur.execute(query) - columns = ['Typ', 'Verfügbar', 'Zugeteilt', 'Quarantäne', 'Gesamt'] - - # Convert to DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - cur.close() - conn.close() - - # Generate file - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f"resource_report_{report_type}_{timestamp}" - - if format_type == 'excel': - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Report', index=False) - - # Auto-adjust columns width - worksheet = writer.sheets['Report'] - for column in worksheet.columns: - max_length = 0 - column = [cell for cell in column] - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = (max_length + 2) - worksheet.column_dimensions[column[0].column_letter].width = adjusted_width - - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'excel', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx') - - else: # CSV - output = io.StringIO() - df.to_csv(output, index=False, sep=';', encoding='utf-8-sig') - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'csv', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv') - - # Wenn kein Download, zeige Report-Formular - return render_template('resource_report.html', - datetime=datetime, - timedelta=timedelta, - username=session.get('username')) - -if __name__ == "__main__": - app.run(host="0.0.0.0", port=5000) diff --git a/v2_adminpanel/app.py.backup_before_cleanup_20250616_223830 b/v2_adminpanel/app.py.backup_before_cleanup_20250616_223830 deleted file mode 100644 index 4e6204a..0000000 --- a/v2_adminpanel/app.py.backup_before_cleanup_20250616_223830 +++ /dev/null @@ -1,4475 +0,0 @@ -import os -import sys -import time -import json -import logging -import requests -import re -import random -import base64 -from io import BytesIO -from datetime import datetime, timedelta -from zoneinfo import ZoneInfo -from pathlib import Path - -# Add current directory to Python path to ensure modules can be imported -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from flask import Flask, render_template, request, redirect, session, url_for, send_file, jsonify, flash -from flask_session import Session -from werkzeug.middleware.proxy_fix import ProxyFix -from apscheduler.schedulers.background import BackgroundScheduler -import pandas as pd -from psycopg2.extras import Json - -# Import our new modules -import config -from db import get_connection, get_db_connection, get_db_cursor, execute_query -from auth.decorators import login_required -from auth.password import hash_password, verify_password -from auth.two_factor import ( - generate_totp_secret, generate_qr_code, verify_totp, - generate_backup_codes, hash_backup_code, verify_backup_code -) -from auth.rate_limiting import ( - check_ip_blocked, record_failed_attempt, - reset_login_attempts, get_login_attempts -) -from utils.network import get_client_ip -from utils.audit import log_audit -from utils.license import generate_license_key, validate_license_key -from utils.backup import create_backup, restore_backup, get_or_create_encryption_key -from utils.export import ( - create_excel_export, format_datetime_for_export, - prepare_license_export_data, prepare_customer_export_data, - prepare_session_export_data, prepare_audit_export_data -) -from models import get_user_by_username - -app = Flask(__name__) -# Load configuration from config module -app.config['SECRET_KEY'] = config.SECRET_KEY -app.config['SESSION_TYPE'] = config.SESSION_TYPE -app.config['JSON_AS_ASCII'] = config.JSON_AS_ASCII -app.config['JSONIFY_MIMETYPE'] = config.JSONIFY_MIMETYPE -app.config['PERMANENT_SESSION_LIFETIME'] = config.PERMANENT_SESSION_LIFETIME -app.config['SESSION_COOKIE_HTTPONLY'] = config.SESSION_COOKIE_HTTPONLY -app.config['SESSION_COOKIE_SECURE'] = config.SESSION_COOKIE_SECURE -app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE -app.config['SESSION_COOKIE_NAME'] = config.SESSION_COOKIE_NAME -app.config['SESSION_REFRESH_EACH_REQUEST'] = config.SESSION_REFRESH_EACH_REQUEST -Session(app) - -# ProxyFix für korrekte IP-Adressen hinter Nginx -app.wsgi_app = ProxyFix( - app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 -) - -# Configuration is now loaded from config module - -# Scheduler für automatische Backups -scheduler = BackgroundScheduler() -scheduler.start() - -# Logging konfigurieren -logging.basicConfig(level=logging.INFO) - -# Import and register blueprints -from routes.auth_routes import auth_bp -from routes.admin_routes import admin_bp -from routes.license_routes import license_bp -from routes.customer_routes import customer_bp -from routes.resource_routes import resource_bp -from routes.session_routes import session_bp -from routes.batch_routes import batch_bp -from routes.api_routes import api_bp -from routes.export_routes import export_bp - -# Register blueprints -app.register_blueprint(auth_bp) -app.register_blueprint(admin_bp) -app.register_blueprint(license_bp) -app.register_blueprint(customer_bp) -app.register_blueprint(resource_bp) -app.register_blueprint(session_bp) -app.register_blueprint(batch_bp) -app.register_blueprint(api_bp) -app.register_blueprint(export_bp) - - -# Scheduled Backup Job -def scheduled_backup(): - """Führt ein geplantes Backup aus""" - logging.info("Starte geplantes Backup...") - create_backup(backup_type="scheduled", created_by="scheduler") - -# Scheduler konfigurieren - täglich um 3:00 Uhr -scheduler.add_job( - scheduled_backup, - 'cron', - hour=config.SCHEDULER_CONFIG['backup_hour'], - minute=config.SCHEDULER_CONFIG['backup_minute'], - id='daily_backup', - replace_existing=True -) - - -def verify_recaptcha(response): - """Verifiziert die reCAPTCHA v2 Response mit Google""" - secret_key = config.RECAPTCHA_SECRET_KEY - - # Wenn kein Secret Key konfiguriert ist, CAPTCHA als bestanden werten (für PoC) - if not secret_key: - logging.warning("RECAPTCHA_SECRET_KEY nicht konfiguriert - CAPTCHA wird übersprungen") - return True - - # Verifizierung bei Google - try: - verify_url = 'https://www.google.com/recaptcha/api/siteverify' - data = { - 'secret': secret_key, - 'response': response - } - - # Timeout für Request setzen - r = requests.post(verify_url, data=data, timeout=5) - result = r.json() - - # Log für Debugging - if not result.get('success'): - logging.warning(f"reCAPTCHA Validierung fehlgeschlagen: {result.get('error-codes', [])}") - - return result.get('success', False) - - except requests.exceptions.RequestException as e: - logging.error(f"reCAPTCHA Verifizierung fehlgeschlagen: {str(e)}") - # Bei Netzwerkfehlern CAPTCHA als bestanden werten - return True - except Exception as e: - logging.error(f"Unerwarteter Fehler bei reCAPTCHA: {str(e)}") - return False - - -# @app.route("/login", methods=["GET", "POST"]) -# def login(): - # Timing-Attack Schutz - Start Zeit merken - # start_time = time.time() - - # IP-Adresse ermitteln - # ip_address = get_client_ip() - - # Prüfen ob IP gesperrt ist - # is_blocked, blocked_until = check_ip_blocked(ip_address) - # if is_blocked: - # time_remaining = (blocked_until - datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None)).total_seconds() / 3600 - # error_msg = f"IP GESPERRT! Noch {time_remaining:.1f} Stunden warten." - # return render_template("login.html", error=error_msg, error_type="blocked") - - # Anzahl bisheriger Versuche - # attempt_count = get_login_attempts(ip_address) - - # if request.method == "POST": - # username = request.form.get("username") - # password = request.form.get("password") - # captcha_response = request.form.get("g-recaptcha-response") - - # CAPTCHA-Prüfung nur wenn Keys konfiguriert sind - # recaptcha_site_key = config.RECAPTCHA_SITE_KEY - # if attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and recaptcha_site_key: - # if not captcha_response: - # Timing-Attack Schutz - # elapsed = time.time() - start_time - # if elapsed < 1.0: - # time.sleep(1.0 - elapsed) - # return render_template("login.html", - # error="CAPTCHA ERFORDERLICH!", - # show_captcha=True, - # error_type="captcha", - # attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - # recaptcha_site_key=recaptcha_site_key) - - # CAPTCHA validieren - # if not verify_recaptcha(captcha_response): - # Timing-Attack Schutz - # elapsed = time.time() - start_time - # if elapsed < 1.0: - # time.sleep(1.0 - elapsed) - # return render_template("login.html", - # error="CAPTCHA UNGÜLTIG! Bitte erneut versuchen.", - # show_captcha=True, - # error_type="captcha", - # attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - # recaptcha_site_key=recaptcha_site_key) - - # Check user in database first, fallback to env vars - # user = get_user_by_username(username) - # login_success = False - # needs_2fa = False - - # if user: - # Database user authentication - # if verify_password(password, user['password_hash']): - # login_success = True - # needs_2fa = user['totp_enabled'] - # else: - # Fallback to environment variables for backward compatibility - # if username in config.ADMIN_USERS and password == config.ADMIN_USERS[username]: - # login_success = True - - # Timing-Attack Schutz - Mindestens 1 Sekunde warten - # elapsed = time.time() - start_time - # if elapsed < 1.0: - # time.sleep(1.0 - elapsed) - - # if login_success: - # Erfolgreicher Login - # if needs_2fa: - # Store temporary session for 2FA verification - # session['temp_username'] = username - # session['temp_user_id'] = user['id'] - # session['awaiting_2fa'] = True - # return redirect(url_for('verify_2fa')) - # else: - # Complete login without 2FA - # session.permanent = True # Aktiviert das Timeout - # session['logged_in'] = True - # session['username'] = username - # session['user_id'] = user['id'] if user else None - # session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # reset_login_attempts(ip_address) - # log_audit('LOGIN_SUCCESS', 'user', - # additional_info=f"Erfolgreiche Anmeldung von IP: {ip_address}") - # return redirect(url_for('dashboard')) - # else: - # Fehlgeschlagener Login - # error_message = record_failed_attempt(ip_address, username) - # new_attempt_count = get_login_attempts(ip_address) - - # Prüfen ob jetzt gesperrt - # is_now_blocked, _ = check_ip_blocked(ip_address) - # if is_now_blocked: - # log_audit('LOGIN_BLOCKED', 'security', - # additional_info=f"IP {ip_address} wurde nach {config.MAX_LOGIN_ATTEMPTS} Versuchen gesperrt") - - # return render_template("login.html", - # error=error_message, - # show_captcha=(new_attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - # error_type="failed", - # attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - new_attempt_count), - # recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - - # GET Request - # return render_template("login.html", - # show_captcha=(attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - # attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - # recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - -# @app.route("/logout") -# def logout(): - # username = session.get('username', 'unknown') - # log_audit('LOGOUT', 'user', additional_info=f"Abmeldung") - # session.pop('logged_in', None) - # session.pop('username', None) - # session.pop('user_id', None) - # session.pop('temp_username', None) - # session.pop('temp_user_id', None) - # session.pop('awaiting_2fa', None) - # return redirect(url_for('login')) - -# @app.route("/verify-2fa", methods=["GET", "POST"]) -# def verify_2fa(): - # if not session.get('awaiting_2fa'): - # return redirect(url_for('login')) - - # if request.method == "POST": - # token = request.form.get('token', '').replace(' ', '') - # username = session.get('temp_username') - # user_id = session.get('temp_user_id') - - # if not username or not user_id: - # flash('Session expired. Please login again.', 'error') - # return redirect(url_for('login')) - - # user = get_user_by_username(username) - # if not user: - # flash('User not found.', 'error') - # return redirect(url_for('login')) - - # Check if it's a backup code - # if len(token) == 8 and token.isupper(): - # Try backup code - # backup_codes = json.loads(user['backup_codes']) if user['backup_codes'] else [] - # if verify_backup_code(token, backup_codes): - # Remove used backup code - # code_hash = hash_backup_code(token) - # backup_codes.remove(code_hash) - - # conn = get_connection() - # cur = conn.cursor() - # cur.execute("UPDATE users SET backup_codes = %s WHERE id = %s", - # (json.dumps(backup_codes), user_id)) - # conn.commit() - # cur.close() - # conn.close() - - # Complete login - # session.permanent = True - # session['logged_in'] = True - # session['username'] = username - # session['user_id'] = user_id - # session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # session.pop('temp_username', None) - # session.pop('temp_user_id', None) - # session.pop('awaiting_2fa', None) - - # flash('Login successful using backup code. Please generate new backup codes.', 'warning') - # log_audit('LOGIN_2FA_BACKUP', 'user', additional_info=f"2FA login with backup code") - # return redirect(url_for('dashboard')) - # else: - # Try TOTP token - # if verify_totp(user['totp_secret'], token): - # Complete login - # session.permanent = True - # session['logged_in'] = True - # session['username'] = username - # session['user_id'] = user_id - # session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # session.pop('temp_username', None) - # session.pop('temp_user_id', None) - # session.pop('awaiting_2fa', None) - - # log_audit('LOGIN_2FA_SUCCESS', 'user', additional_info=f"2FA login successful") - # return redirect(url_for('dashboard')) - - # Failed verification - # conn = get_connection() - # cur = conn.cursor() - # cur.execute("UPDATE users SET failed_2fa_attempts = failed_2fa_attempts + 1, last_failed_2fa = %s WHERE id = %s", - # (datetime.now(), user_id)) - # conn.commit() - # cur.close() - # conn.close() - - # flash('Invalid authentication code. Please try again.', 'error') - # log_audit('LOGIN_2FA_FAILED', 'user', additional_info=f"Failed 2FA attempt") - - # return render_template('verify_2fa.html') - -# @app.route("/profile") -# @login_required -def profile(): - user = get_user_by_username(session['username']) - if not user: - # For environment-based users, redirect with message - flash('Bitte führen Sie das Migrations-Script aus, um Passwort-Änderung und 2FA zu aktivieren.', 'info') - return redirect(url_for('dashboard')) - return render_template('profile.html', user=user) - -# @app.route("/profile/change-password", methods=["POST"]) -# @login_required -def change_password(): - current_password = request.form.get('current_password') - new_password = request.form.get('new_password') - confirm_password = request.form.get('confirm_password') - - user = get_user_by_username(session['username']) - - # Verify current password - if not verify_password(current_password, user['password_hash']): - flash('Current password is incorrect.', 'error') - return redirect(url_for('profile')) - - # Check new password - if new_password != confirm_password: - flash('New passwords do not match.', 'error') - return redirect(url_for('profile')) - - if len(new_password) < 8: - flash('Password must be at least 8 characters long.', 'error') - return redirect(url_for('profile')) - - # Update password - new_hash = hash_password(new_password) - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET password_hash = %s, last_password_change = %s WHERE id = %s", - (new_hash, datetime.now(), user['id'])) - conn.commit() - cur.close() - conn.close() - - log_audit('PASSWORD_CHANGE', 'user', entity_id=user['id'], - additional_info="Password changed successfully") - flash('Password changed successfully.', 'success') - return redirect(url_for('profile')) - -# @app.route("/profile/setup-2fa") -# @login_required -def setup_2fa(): - user = get_user_by_username(session['username']) - - if user['totp_enabled']: - flash('2FA is already enabled for your account.', 'info') - return redirect(url_for('profile')) - - # Generate new TOTP secret - totp_secret = generate_totp_secret() - session['temp_totp_secret'] = totp_secret - - # Generate QR code - qr_code = generate_qr_code(user['username'], totp_secret) - - return render_template('setup_2fa.html', - totp_secret=totp_secret, - qr_code=qr_code) - -# @app.route("/profile/enable-2fa", methods=["POST"]) -# @login_required -def enable_2fa(): - token = request.form.get('token', '').replace(' ', '') - totp_secret = session.get('temp_totp_secret') - - if not totp_secret: - flash('2FA setup session expired. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Verify the token - if not verify_totp(totp_secret, token): - flash('Invalid authentication code. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Generate backup codes - backup_codes = generate_backup_codes() - hashed_codes = [hash_backup_code(code) for code in backup_codes] - - # Enable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_secret = %s, totp_enabled = TRUE, backup_codes = %s - WHERE username = %s - """, (totp_secret, json.dumps(hashed_codes), session['username'])) - conn.commit() - cur.close() - conn.close() - - session.pop('temp_totp_secret', None) - - log_audit('2FA_ENABLED', 'user', additional_info="2FA enabled successfully") - - # Show backup codes - return render_template('backup_codes.html', backup_codes=backup_codes) - -# @app.route("/profile/disable-2fa", methods=["POST"]) -# @login_required -def disable_2fa(): - password = request.form.get('password') - user = get_user_by_username(session['username']) - - # Verify password - if not verify_password(password, user['password_hash']): - flash('Incorrect password.', 'error') - return redirect(url_for('profile')) - - # Disable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_enabled = FALSE, totp_secret = NULL, backup_codes = NULL - WHERE username = %s - """, (session['username'],)) - conn.commit() - cur.close() - conn.close() - - log_audit('2FA_DISABLED', 'user', additional_info="2FA disabled") - flash('2FA has been disabled for your account.', 'success') - return redirect(url_for('profile')) - -# @app.route("/heartbeat", methods=['POST']) -# @login_required -def heartbeat(): - """Endpoint für Session Keep-Alive - aktualisiert last_activity""" - # Aktualisiere last_activity nur wenn explizit angefordert - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # Force session save - session.modified = True - - return jsonify({ - 'status': 'ok', - 'last_activity': session['last_activity'], - 'username': session.get('username') - }) - -# @app.route("/api/generate-license-key", methods=['POST']) -# @login_required -def api_generate_key(): - """API Endpoint zur Generierung eines neuen Lizenzschlüssels""" - try: - # Lizenztyp aus Request holen (default: full) - data = request.get_json() or {} - license_type = data.get('type', 'full') - - # Key generieren - key = generate_license_key(license_type) - - # Prüfen ob Key bereits existiert (sehr unwahrscheinlich aber sicher ist sicher) - conn = get_connection() - cur = conn.cursor() - - # Wiederhole bis eindeutiger Key gefunden - attempts = 0 - while attempts < 10: # Max 10 Versuche - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (key,)) - if not cur.fetchone(): - break # Key ist eindeutig - key = generate_license_key(license_type) - attempts += 1 - - cur.close() - conn.close() - - # Log für Audit - log_audit('GENERATE_KEY', 'license', - additional_info={'type': license_type, 'key': key}) - - return jsonify({ - 'success': True, - 'key': key, - 'type': license_type - }) - - except Exception as e: - logging.error(f"Fehler bei Key-Generierung: {str(e)}") - return jsonify({ - 'success': False, - 'error': 'Fehler bei der Key-Generierung' - }), 500 - -# @app.route("/api/customers", methods=['GET']) -# @login_required -def api_customers(): - """API Endpoint für die Kundensuche mit Select2""" - try: - # Suchparameter - search = request.args.get('q', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - customer_id = request.args.get('id', type=int) - - conn = get_connection() - cur = conn.cursor() - - # Einzelnen Kunden per ID abrufen - if customer_id: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.id = %s - GROUP BY c.id, c.name, c.email - """, (customer_id,)) - - customer = cur.fetchone() - results = [] - if customer: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} ({customer[2]})", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - cur.close() - conn.close() - - return jsonify({ - 'results': results, - 'pagination': {'more': False} - }) - - # SQL Query mit optionaler Suche - elif search: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE LOWER(c.name) LIKE LOWER(%s) - OR LOWER(c.email) LIKE LOWER(%s) - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (f'%{search}%', f'%{search}%', per_page, (page - 1) * per_page)) - else: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (per_page, (page - 1) * per_page)) - - customers = cur.fetchall() - - # Format für Select2 - results = [] - for customer in customers: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} - {customer[2]} ({customer[3]} Lizenzen)", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - # Gesamtanzahl für Pagination - if search: - cur.execute(""" - SELECT COUNT(*) FROM customers - WHERE LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - """, (f'%{search}%', f'%{search}%')) - else: - cur.execute("SELECT COUNT(*) FROM customers") - - total_count = cur.fetchone()[0] - - cur.close() - conn.close() - - # Select2 Response Format - return jsonify({ - 'results': results, - 'pagination': { - 'more': (page * per_page) < total_count - } - }) - - except Exception as e: - logging.error(f"Fehler bei Kundensuche: {str(e)}") - return jsonify({ - 'results': [], - 'error': 'Fehler bei der Kundensuche' - }), 500 - -# @app.route("/") -# @login_required -def dashboard(): - conn = get_connection() - cur = conn.cursor() - - # Statistiken abrufen - # Gesamtanzahl Kunden (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = FALSE") - total_customers = cur.fetchone()[0] - - # Gesamtanzahl Lizenzen (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = FALSE") - total_licenses = cur.fetchone()[0] - - # Aktive Lizenzen (nicht abgelaufen und is_active = true, ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE AND is_active = TRUE AND is_test = FALSE - """) - active_licenses = cur.fetchone()[0] - - # Aktive Sessions - cur.execute("SELECT COUNT(*) FROM sessions WHERE is_active = TRUE") - active_sessions_count = cur.fetchone()[0] - - # Abgelaufene Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until < CURRENT_DATE AND is_test = FALSE - """) - expired_licenses = cur.fetchone()[0] - - # Deaktivierte Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE is_active = FALSE AND is_test = FALSE - """) - inactive_licenses = cur.fetchone()[0] - - # Lizenzen die in den nächsten 30 Tagen ablaufen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE - AND valid_until < CURRENT_DATE + INTERVAL '30 days' - AND is_active = TRUE - AND is_test = FALSE - """) - expiring_soon = cur.fetchone()[0] - - # Testlizenzen vs Vollversionen (ohne Testdaten) - cur.execute(""" - SELECT license_type, COUNT(*) - FROM licenses - WHERE is_test = FALSE - GROUP BY license_type - """) - license_types = dict(cur.fetchall()) - - # Anzahl Testdaten - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = TRUE") - test_data_count = cur.fetchone()[0] - - # Anzahl Test-Kunden - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = TRUE") - test_customers_count = cur.fetchone()[0] - - # Anzahl Test-Ressourcen - cur.execute("SELECT COUNT(*) FROM resource_pools WHERE is_test = TRUE") - test_resources_count = cur.fetchone()[0] - - # Letzte 5 erstellten Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.is_test = FALSE - ORDER BY l.id DESC - LIMIT 5 - """) - recent_licenses = cur.fetchall() - - # Bald ablaufende Lizenzen (nächste 30 Tage, ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - l.valid_until - CURRENT_DATE as days_left - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.valid_until >= CURRENT_DATE - AND l.valid_until < CURRENT_DATE + INTERVAL '30 days' - AND l.is_active = TRUE - AND l.is_test = FALSE - ORDER BY l.valid_until - LIMIT 10 - """) - expiring_licenses = cur.fetchall() - - # Letztes Backup - cur.execute(""" - SELECT created_at, filesize, duration_seconds, backup_type, status - FROM backup_history - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup_info = cur.fetchone() - - # Sicherheitsstatistiken - # Gesperrte IPs - cur.execute(""" - SELECT COUNT(*) FROM login_attempts - WHERE blocked_until IS NOT NULL AND blocked_until > CURRENT_TIMESTAMP - """) - blocked_ips_count = cur.fetchone()[0] - - # Fehlversuche heute - cur.execute(""" - SELECT COALESCE(SUM(attempt_count), 0) FROM login_attempts - WHERE last_attempt::date = CURRENT_DATE - """) - failed_attempts_today = cur.fetchone()[0] - - # Letzte 5 Sicherheitsereignisse - cur.execute(""" - SELECT - la.ip_address, - la.attempt_count, - la.last_attempt, - la.blocked_until, - la.last_username_tried, - la.last_error_message - FROM login_attempts la - ORDER BY la.last_attempt DESC - LIMIT 5 - """) - recent_security_events = [] - for event in cur.fetchall(): - recent_security_events.append({ - 'ip_address': event[0], - 'attempt_count': event[1], - 'last_attempt': event[2].strftime('%d.%m %H:%M'), - 'blocked_until': event[3].strftime('%d.%m %H:%M') if event[3] and event[3] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) else None, - 'username_tried': event[4], - 'error_message': event[5] - }) - - # Sicherheitslevel berechnen - if blocked_ips_count > 5 or failed_attempts_today > 50: - security_level = 'danger' - security_level_text = 'KRITISCH' - elif blocked_ips_count > 2 or failed_attempts_today > 20: - security_level = 'warning' - security_level_text = 'ERHÖHT' - else: - security_level = 'success' - security_level_text = 'NORMAL' - - # Resource Pool Statistiken (nur Live-Daten, keine Testdaten) - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = FALSE - GROUP BY resource_type - """) - - resource_stats = {} - resource_warning = None - - for row in cur.fetchall(): - available_percent = round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - resource_stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': available_percent, - 'warning_level': 'danger' if row[1] < 50 else 'warning' if row[1] < 100 else 'success' - } - - # Warnung bei niedrigem Bestand - if row[1] < 50: - if not resource_warning: - resource_warning = f"Niedriger Bestand bei {row[0].upper()}: nur noch {row[1]} verfügbar!" - else: - resource_warning += f" | {row[0].upper()}: {row[1]}" - - cur.close() - conn.close() - - stats = { - 'total_customers': total_customers, - 'total_licenses': total_licenses, - 'active_licenses': active_licenses, - 'expired_licenses': expired_licenses, - 'inactive_licenses': inactive_licenses, - 'expiring_soon': expiring_soon, - 'full_licenses': license_types.get('full', 0), - 'test_licenses': license_types.get('test', 0), - 'test_data_count': test_data_count, - 'test_customers_count': test_customers_count, - 'test_resources_count': test_resources_count, - 'recent_licenses': recent_licenses, - 'expiring_licenses': expiring_licenses, - 'active_sessions': active_sessions_count, - 'last_backup': last_backup_info, - # Sicherheitsstatistiken - 'blocked_ips_count': blocked_ips_count, - 'failed_attempts_today': failed_attempts_today, - 'recent_security_events': recent_security_events, - 'security_level': security_level, - 'security_level_text': security_level_text, - 'resource_stats': resource_stats - } - - return render_template("dashboard.html", - stats=stats, - resource_stats=resource_stats, - resource_warning=resource_warning, - username=session.get('username')) - -# @app.route("/create", methods=["GET", "POST"]) -# @login_required -def create_license(): - if request.method == "POST": - customer_id = request.form.get("customer_id") - license_key = request.form["license_key"].upper() # Immer Großbuchstaben - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Validiere License Key Format - if not validate_license_key(license_key): - flash('Ungültiges License Key Format! Erwartet: AF-YYYYMMFT-XXXX-YYYY-ZZZZ', 'error') - return redirect(url_for('create_license')) - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('create_license')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('create_license')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - customer_info = {'name': name, 'email': email, 'is_test': is_test} - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos für Audit-Log - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('create_license')) - customer_info = {'name': customer_data[0], 'email': customer_data[1]} - - # Wenn Kunde Test-Kunde ist, Lizenz auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Lizenz hinzufügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit, is_test) - VALUES (%s, %s, %s, %s, %s, TRUE, %s, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit, is_test)) - license_id = cur.fetchone()[0] - - # Ressourcen zuweisen - try: - # Prüfe Verfügbarkeit - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {available[0]})") - if available[1] < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {ipv4_count}, verfügbar: {available[1]})") - if available[2] < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar (benötigt: {phone_count}, verfügbar: {available[2]})") - - # Domains zuweisen - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s zuweisen - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern zuweisen - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - except ValueError as e: - conn.rollback() - flash(str(e), 'error') - return redirect(url_for('create_license')) - - conn.commit() - - # Audit-Log - log_audit('CREATE', 'license', license_id, - new_values={ - 'license_key': license_key, - 'customer_name': customer_info['name'], - 'customer_email': customer_info['email'], - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'device_limit': device_limit, - 'is_test': is_test - }) - - flash(f'Lizenz {license_key} erfolgreich erstellt!', 'success') - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Erstellen der Lizenz: {str(e)}") - flash('Fehler beim Erstellen der Lizenz!', 'error') - finally: - cur.close() - conn.close() - - # Preserve show_test parameter if present - redirect_url = "/create" - if request.args.get('show_test') == 'true': - redirect_url += "?show_test=true" - return redirect(redirect_url) - - # Unterstützung für vorausgewählten Kunden - preselected_customer_id = request.args.get('customer_id', type=int) - return render_template("index.html", username=session.get('username'), preselected_customer_id=preselected_customer_id) - -# @app.route("/batch", methods=["GET", "POST"]) -# @login_required -def batch_licenses(): - """Batch-Generierung mehrerer Lizenzen für einen Kunden""" - if request.method == "POST": - # Formulardaten - customer_id = request.form.get("customer_id") - license_type = request.form["license_type"] - quantity = int(request.form["quantity"]) - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - # Sicherheitslimit - if quantity < 1 or quantity > 100: - flash('Anzahl muss zwischen 1 und 100 liegen!', 'error') - return redirect(url_for('batch_licenses')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('batch_licenses')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('batch_licenses')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('batch_licenses')) - name = customer_data[0] - email = customer_data[1] - - # Wenn Kunde Test-Kunde ist, Lizenzen auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Prüfe Ressourcen-Verfügbarkeit für gesamten Batch - total_domains_needed = domain_count * quantity - total_ipv4s_needed = ipv4_count * quantity - total_phones_needed = phone_count * quantity - - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < total_domains_needed: - flash(f"Nicht genügend Domains verfügbar (benötigt: {total_domains_needed}, verfügbar: {available[0]})", 'error') - return redirect(url_for('batch_licenses')) - if available[1] < total_ipv4s_needed: - flash(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {total_ipv4s_needed}, verfügbar: {available[1]})", 'error') - return redirect(url_for('batch_licenses')) - if available[2] < total_phones_needed: - flash(f"Nicht genügend Telefonnummern verfügbar (benötigt: {total_phones_needed}, verfügbar: {available[2]})", 'error') - return redirect(url_for('batch_licenses')) - - # Lizenzen generieren und speichern - generated_licenses = [] - for i in range(quantity): - # Eindeutigen Key generieren - attempts = 0 - while attempts < 10: - license_key = generate_license_key(license_type) - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (license_key,)) - if not cur.fetchone(): - break - attempts += 1 - - # Lizenz einfügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, is_test, - valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit) - VALUES (%s, %s, %s, %s, %s, %s, true, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, is_test, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit)) - license_id = cur.fetchone()[0] - - # Ressourcen für diese Lizenz zuweisen - # Domains - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - generated_licenses.append({ - 'id': license_id, - 'key': license_key, - 'type': license_type - }) - - conn.commit() - - # Audit-Log - log_audit('CREATE_BATCH', 'license', - new_values={'customer': name, 'quantity': quantity, 'type': license_type}, - additional_info=f"Batch-Generierung von {quantity} Lizenzen") - - # Session für Export speichern - session['batch_export'] = { - 'customer': name, - 'email': email, - 'licenses': generated_licenses, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'timestamp': datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - } - - flash(f'{quantity} Lizenzen erfolgreich generiert!', 'success') - return render_template("batch_result.html", - customer=name, - email=email, - licenses=generated_licenses, - valid_from=valid_from, - valid_until=valid_until) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler bei Batch-Generierung: {str(e)}") - flash('Fehler bei der Batch-Generierung!', 'error') - return redirect(url_for('batch_licenses')) - finally: - cur.close() - conn.close() - - # GET Request - return render_template("batch_form.html") - -# @app.route("/batch/export") -# @login_required -def export_batch(): - """Exportiert die zuletzt generierten Batch-Lizenzen""" - batch_data = session.get('batch_export') - if not batch_data: - flash('Keine Batch-Daten zum Exportieren vorhanden!', 'error') - return redirect(url_for('batch_licenses')) - - # CSV generieren - output = io.StringIO() - output.write('\ufeff') # UTF-8 BOM für Excel - - # Header - output.write(f"Kunde: {batch_data['customer']}\n") - output.write(f"E-Mail: {batch_data['email']}\n") - output.write(f"Generiert am: {datetime.fromisoformat(batch_data['timestamp']).strftime('%d.%m.%Y %H:%M')}\n") - output.write(f"Gültig von: {batch_data['valid_from']} bis {batch_data['valid_until']}\n") - output.write("\n") - output.write("Nr;Lizenzschlüssel;Typ\n") - - # Lizenzen - for i, license in enumerate(batch_data['licenses'], 1): - typ_text = "Vollversion" if license['type'] == 'full' else "Testversion" - output.write(f"{i};{license['key']};{typ_text}\n") - - output.seek(0) - - # Audit-Log - log_audit('EXPORT', 'batch_licenses', - additional_info=f"Export von {len(batch_data['licenses'])} Batch-Lizenzen") - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f"batch_licenses_{batch_data['customer'].replace(' ', '_')}_{datetime.now(ZoneInfo('Europe/Berlin')).strftime('%Y%m%d_%H%M%S')}.csv" - ) - -# @app.route("/licenses") -# @login_required -def licenses(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -# @app.route("/license/edit/", methods=["GET", "POST"]) -# @login_required -def edit_license(license_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute(""" - SELECT license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit - FROM licenses WHERE id = %s - """, (license_id,)) - old_license = cur.fetchone() - - # Update license - license_key = request.form["license_key"] - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - valid_until = request.form["valid_until"] - is_active = request.form.get("is_active") == "on" - is_test = request.form.get("is_test") == "on" - device_limit = int(request.form.get("device_limit", 3)) - - cur.execute(""" - UPDATE licenses - SET license_key = %s, license_type = %s, valid_from = %s, - valid_until = %s, is_active = %s, is_test = %s, device_limit = %s - WHERE id = %s - """, (license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit, license_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'license_key': old_license[0], - 'license_type': old_license[1], - 'valid_from': str(old_license[2]), - 'valid_until': str(old_license[3]), - 'is_active': old_license[4], - 'is_test': old_license[5], - 'device_limit': old_license[6] - }, - new_values={ - 'license_key': license_key, - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'is_active': is_active, - 'is_test': is_test, - 'device_limit': device_limit - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei wenn vorhanden - if request.referrer and 'customer_id=' in request.referrer: - import re - match = re.search(r'customer_id=(\d+)', request.referrer) - if match: - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={match.group(1)}" - - return redirect(redirect_url) - - # Get license data - cur.execute(""" - SELECT l.id, l.license_key, c.name, c.email, l.license_type, - l.valid_from, l.valid_until, l.is_active, c.id, l.is_test, l.device_limit - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - - license = cur.fetchone() - cur.close() - conn.close() - - if not license: - return redirect("/licenses") - - return render_template("edit_license.html", license=license, username=session.get('username')) - -# @app.route("/license/delete/", methods=["POST"]) -# @login_required -def delete_license(license_id): - conn = get_connection() - cur = conn.cursor() - - # Lizenzdetails für Audit-Log abrufen - cur.execute(""" - SELECT l.license_key, c.name, l.license_type - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - license_info = cur.fetchone() - - cur.execute("DELETE FROM licenses WHERE id = %s", (license_id,)) - - conn.commit() - - # Audit-Log - if license_info: - log_audit('DELETE', 'license', license_id, - old_values={ - 'license_key': license_info[0], - 'customer_name': license_info[1], - 'license_type': license_info[2] - }) - - cur.close() - conn.close() - - return redirect("/licenses") - -# @app.route("/customers") -# @login_required -def customers(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -# @app.route("/customer/edit/", methods=["GET", "POST"]) -# @login_required -def edit_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - old_customer = cur.fetchone() - - # Update customer - name = request.form["name"] - email = request.form["email"] - is_test = request.form.get("is_test") == "on" - - cur.execute(""" - UPDATE customers - SET name = %s, email = %s, is_test = %s - WHERE id = %s - """, (name, email, is_test, customer_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'customer', customer_id, - old_values={ - 'name': old_customer[0], - 'email': old_customer[1], - 'is_test': old_customer[2] - }, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei (immer der aktuelle Kunde) - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={customer_id}" - - return redirect(redirect_url) - - # Get customer data with licenses - cur.execute(""" - SELECT id, name, email, created_at, is_test FROM customers WHERE id = %s - """, (customer_id,)) - - customer = cur.fetchone() - if not customer: - cur.close() - conn.close() - return "Kunde nicht gefunden", 404 - - - # Get customer's licenses - cur.execute(""" - SELECT id, license_key, license_type, valid_from, valid_until, is_active - FROM licenses - WHERE customer_id = %s - ORDER BY valid_until DESC - """, (customer_id,)) - - licenses = cur.fetchall() - - cur.close() - conn.close() - - if not customer: - return redirect("/customers-licenses") - - return render_template("edit_customer.html", customer=customer, licenses=licenses, username=session.get('username')) - -# @app.route("/customer/create", methods=["GET", "POST"]) -# @login_required -def create_customer(): - """Erstellt einen neuen Kunden ohne Lizenz""" - if request.method == "POST": - name = request.form.get('name') - email = request.form.get('email') - is_test = request.form.get('is_test') == 'on' - - if not name or not email: - flash("Name und E-Mail sind Pflichtfelder!", "error") - return render_template("create_customer.html", username=session.get('username')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfen ob E-Mail bereits existiert - cur.execute("SELECT id, name FROM customers WHERE email = %s", (email,)) - existing = cur.fetchone() - if existing: - flash(f"Ein Kunde mit der E-Mail '{email}' existiert bereits: {existing[1]}", "error") - return render_template("create_customer.html", username=session.get('username')) - - # Kunde erstellen - cur.execute(""" - INSERT INTO customers (name, email, created_at, is_test) - VALUES (%s, %s, %s, %s) RETURNING id - """, (name, email, datetime.now(), is_test)) - - customer_id = cur.fetchone()[0] - conn.commit() - - # Audit-Log - log_audit('CREATE', 'customer', customer_id, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - flash(f"Kunde '{name}' wurde erfolgreich angelegt!", "success") - return redirect(f"/customer/edit/{customer_id}") - - except Exception as e: - conn.rollback() - flash(f"Fehler beim Anlegen des Kunden: {str(e)}", "error") - return render_template("create_customer.html", username=session.get('username')) - finally: - cur.close() - conn.close() - - # GET Request - Formular anzeigen - return render_template("create_customer.html", username=session.get('username')) - -# @app.route("/customer/delete/", methods=["POST"]) -# @login_required -def delete_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - # Prüfen ob Kunde Lizenzen hat - cur.execute("SELECT COUNT(*) FROM licenses WHERE customer_id = %s", (customer_id,)) - license_count = cur.fetchone()[0] - - if license_count > 0: - # Kunde hat Lizenzen - nicht löschen - cur.close() - conn.close() - return redirect("/customers") - - # Kundendetails für Audit-Log abrufen - cur.execute("SELECT name, email FROM customers WHERE id = %s", (customer_id,)) - customer_info = cur.fetchone() - - # Kunde löschen wenn keine Lizenzen vorhanden - cur.execute("DELETE FROM customers WHERE id = %s", (customer_id,)) - - conn.commit() - - # Audit-Log - if customer_info: - log_audit('DELETE', 'customer', customer_id, - old_values={ - 'name': customer_info[0], - 'email': customer_info[1] - }) - - cur.close() - conn.close() - - return redirect("/customers") - -# @app.route("/customers-licenses") -# @login_required -def customers_licenses(): - """Kombinierte Ansicht für Kunden und deren Lizenzen""" - conn = get_connection() - cur = conn.cursor() - - # Hole alle Kunden mit Lizenzstatistiken (inkl. Testkunden wenn gewünscht) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - query = """ - SELECT - c.id, - c.name, - c.email, - c.created_at, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - """ - - if not show_test: - query += " WHERE c.is_test = FALSE" - - query += """ - GROUP BY c.id, c.name, c.email, c.created_at - ORDER BY c.name - """ - - cur.execute(query) - customers = cur.fetchall() - - # Hole ausgewählten Kunden nur wenn explizit in URL angegeben - selected_customer_id = request.args.get('customer_id', type=int) - licenses = [] - selected_customer = None - - if customers and selected_customer_id: - # Hole Daten des ausgewählten Kunden - for customer in customers: - if customer[0] == selected_customer_id: - selected_customer = customer - break - - # Hole Lizenzen des ausgewählten Kunden - if selected_customer: - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (selected_customer_id,)) - licenses = cur.fetchall() - - cur.close() - conn.close() - - return render_template("customers_licenses.html", - customers=customers, - selected_customer=selected_customer, - selected_customer_id=selected_customer_id, - licenses=licenses, - show_test=show_test) - -# @app.route("/api/customer//licenses") -# @login_required -def api_customer_licenses(customer_id): - """API-Endpoint für AJAX-Abruf der Lizenzen eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Lizenzen des Kunden - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (customer_id,)) - - licenses = [] - for row in cur.fetchall(): - license_id = row[0] - - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for res_row in cur.fetchall(): - resource_info = { - 'id': res_row[0], - 'value': res_row[2], - 'assigned_at': res_row[3].strftime('%d.%m.%Y') if res_row[3] else '' - } - - if res_row[1] == 'domain': - resources['domains'].append(resource_info) - elif res_row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif res_row[1] == 'phone': - resources['phones'].append(resource_info) - - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'license_type': row[2], - 'valid_from': row[3].strftime('%d.%m.%Y') if row[3] else '', - 'valid_until': row[4].strftime('%d.%m.%Y') if row[4] else '', - 'is_active': row[5], - 'status': row[6], - 'domain_count': row[7], # limit - 'ipv4_count': row[8], # limit - 'phone_count': row[9], # limit - 'device_limit': row[10], - 'active_devices': row[11], - 'actual_domain_count': row[12], # actual count - 'actual_ipv4_count': row[13], # actual count - 'actual_phone_count': row[14], # actual count - 'resources': resources - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'licenses': licenses, - 'count': len(licenses) - }) - -# @app.route("/api/customer//quick-stats") -# @login_required -def api_customer_quick_stats(customer_id): - """API-Endpoint für Schnellstatistiken eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Kundenstatistiken - cur.execute(""" - SELECT - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' AND l.valid_until >= CURRENT_DATE THEN 1 END) as expiring_soon - FROM licenses l - WHERE l.customer_id = %s - """, (customer_id,)) - - stats = cur.fetchone() - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'stats': { - 'total': stats[0], - 'active': stats[1], - 'expired': stats[2], - 'expiring_soon': stats[3] - } - }) - -# @app.route("/api/license//quick-edit", methods=['POST']) -# @login_required -def api_license_quick_edit(license_id): - """API-Endpoint für schnelle Lizenz-Bearbeitung""" - conn = get_connection() - cur = conn.cursor() - - try: - data = request.get_json() - - # Hole alte Werte für Audit-Log - cur.execute(""" - SELECT is_active, valid_until, license_type - FROM licenses WHERE id = %s - """, (license_id,)) - old_values = cur.fetchone() - - if not old_values: - return jsonify({'success': False, 'error': 'Lizenz nicht gefunden'}), 404 - - # Update-Felder vorbereiten - updates = [] - params = [] - new_values = {} - - if 'is_active' in data: - updates.append("is_active = %s") - params.append(data['is_active']) - new_values['is_active'] = data['is_active'] - - if 'valid_until' in data: - updates.append("valid_until = %s") - params.append(data['valid_until']) - new_values['valid_until'] = data['valid_until'] - - if 'license_type' in data: - updates.append("license_type = %s") - params.append(data['license_type']) - new_values['license_type'] = data['license_type'] - - if updates: - params.append(license_id) - cur.execute(f""" - UPDATE licenses - SET {', '.join(updates)} - WHERE id = %s - """, params) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'is_active': old_values[0], - 'valid_until': old_values[1].isoformat() if old_values[1] else None, - 'license_type': old_values[2] - }, - new_values=new_values) - - cur.close() - conn.close() - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -# @app.route("/api/license//resources") -# @login_required -def api_license_resources(license_id): - """API-Endpoint für detaillierte Ressourcen-Informationen einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for row in cur.fetchall(): - resource_info = { - 'id': row[0], - 'value': row[2], - 'assigned_at': row[3].strftime('%d.%m.%Y') if row[3] else '' - } - - if row[1] == 'domain': - resources['domains'].append(resource_info) - elif row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif row[1] == 'phone': - resources['phones'].append(resource_info) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'resources': resources - }) - - except Exception as e: - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -# @app.route("/sessions") -# @login_required -def sessions(): - conn = get_connection() - cur = conn.cursor() - - # Sortierparameter - active_sort = request.args.get('active_sort', 'last_heartbeat') - active_order = request.args.get('active_order', 'desc') - ended_sort = request.args.get('ended_sort', 'ended_at') - ended_order = request.args.get('ended_order', 'desc') - - # Whitelist für erlaubte Sortierfelder - Aktive Sessions - active_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'last_heartbeat': 's.last_heartbeat', - 'inactive': 'minutes_inactive' - } - - # Whitelist für erlaubte Sortierfelder - Beendete Sessions - ended_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'ended_at': 's.ended_at', - 'duration': 'duration_minutes' - } - - # Validierung - if active_sort not in active_sort_fields: - active_sort = 'last_heartbeat' - if ended_sort not in ended_sort_fields: - ended_sort = 'ended_at' - if active_order not in ['asc', 'desc']: - active_order = 'desc' - if ended_order not in ['asc', 'desc']: - ended_order = 'desc' - - # Aktive Sessions abrufen - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.user_agent, s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.last_heartbeat))/60 as minutes_inactive - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = TRUE - ORDER BY {active_sort_fields[active_sort]} {active_order.upper()} - """) - active_sessions = cur.fetchall() - - # Inaktive Sessions der letzten 24 Stunden - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))/60 as duration_minutes - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = FALSE - AND s.ended_at > NOW() - INTERVAL '24 hours' - ORDER BY {ended_sort_fields[ended_sort]} {ended_order.upper()} - LIMIT 50 - """) - recent_sessions = cur.fetchall() - - cur.close() - conn.close() - - return render_template("sessions.html", - active_sessions=active_sessions, - recent_sessions=recent_sessions, - active_sort=active_sort, - active_order=active_order, - ended_sort=ended_sort, - ended_order=ended_order, - username=session.get('username')) - -# @app.route("/session/end/", methods=["POST"]) -# @login_required -def end_session(session_id): - conn = get_connection() - cur = conn.cursor() - - # Session beenden - cur.execute(""" - UPDATE sessions - SET is_active = FALSE, ended_at = NOW() - WHERE id = %s AND is_active = TRUE - """, (session_id,)) - - conn.commit() - cur.close() - conn.close() - - return redirect("/sessions") - -# @app.route("/export/licenses") -# @login_required -def export_licenses(): - conn = get_connection() - cur = conn.cursor() - - # Alle Lizenzen mit Kundeninformationen abrufen (ohne Testdaten, außer explizit gewünscht) - include_test = request.args.get('include_test', 'false').lower() == 'true' - customer_id = request.args.get('customer_id', type=int) - - query = """ - SELECT l.id, l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type, l.valid_from, l.valid_until, l.is_active, l.is_test, - CASE - WHEN l.is_active = FALSE THEN 'Deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'Abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'Läuft bald ab' - ELSE 'Aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - """ - - # Build WHERE clause - where_conditions = [] - params = [] - - if not include_test: - where_conditions.append("l.is_test = FALSE") - - if customer_id: - where_conditions.append("l.customer_id = %s") - params.append(customer_id) - - if where_conditions: - query += " WHERE " + " AND ".join(where_conditions) - - query += " ORDER BY l.id" - - cur.execute(query, params) - - # Spaltennamen - columns = ['ID', 'Lizenzschlüssel', 'Kunde', 'E-Mail', 'Typ', - 'Gültig von', 'Gültig bis', 'Aktiv', 'Testdaten', 'Status'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Gültig von'] = pd.to_datetime(df['Gültig von']).dt.strftime('%d.%m.%Y') - df['Gültig bis'] = pd.to_datetime(df['Gültig bis']).dt.strftime('%d.%m.%Y') - - # Typ und Aktiv Status anpassen - df['Typ'] = df['Typ'].replace({'full': 'Vollversion', 'test': 'Testversion'}) - df['Aktiv'] = df['Aktiv'].replace({True: 'Ja', False: 'Nein'}) - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'license', - additional_info=f"Export aller Lizenzen als {export_format.upper()}") - filename = f'lizenzen_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Lizenzen', index=False) - - # Formatierung - worksheet = writer.sheets['Lizenzen'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -# @app.route("/export/audit") -# @login_required -def export_audit(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_user = request.args.get('user', '') - filter_action = request.args.get('action', '') - filter_entity = request.args.get('entity', '') - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - params = [] - - if filter_user: - query += " AND username ILIKE %s" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - query += " ORDER BY timestamp DESC" - - cur.execute(query, params) - audit_logs = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for log in audit_logs: - action_text = { - 'CREATE': 'Erstellt', - 'UPDATE': 'Bearbeitet', - 'DELETE': 'Gelöscht', - 'LOGIN': 'Anmeldung', - 'LOGOUT': 'Abmeldung', - 'AUTO_LOGOUT': 'Auto-Logout', - 'EXPORT': 'Export', - 'GENERATE_KEY': 'Key generiert', - 'CREATE_BATCH': 'Batch erstellt', - 'BACKUP': 'Backup erstellt', - 'LOGIN_2FA_SUCCESS': '2FA-Anmeldung', - 'LOGIN_2FA_BACKUP': '2FA-Backup-Code', - 'LOGIN_2FA_FAILED': '2FA-Fehlgeschlagen', - 'LOGIN_BLOCKED': 'Login-Blockiert', - 'RESTORE': 'Wiederhergestellt', - 'PASSWORD_CHANGE': 'Passwort geändert', - '2FA_ENABLED': '2FA aktiviert', - '2FA_DISABLED': '2FA deaktiviert' - }.get(log[3], log[3]) - - data.append({ - 'ID': log[0], - 'Zeitstempel': log[1].strftime('%d.%m.%Y %H:%M:%S'), - 'Benutzer': log[2], - 'Aktion': action_text, - 'Entität': log[4], - 'Entität-ID': log[5] or '', - 'IP-Adresse': log[8] or '', - 'Zusatzinfo': log[10] or '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'audit_log_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'audit_log', - additional_info=f"{export_format.upper()} Export mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Audit Log') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Audit Log'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -# @app.route("/export/customers") -# @login_required -def export_customers(): - conn = get_connection() - cur = conn.cursor() - - # Check if test data should be included - include_test = request.args.get('include_test', 'false').lower() == 'true' - - # Build query based on test data filter - if include_test: - # Include all customers - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - else: - # Exclude test customers and test licenses - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(CASE WHEN l.is_test = FALSE THEN 1 END) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.is_test = FALSE - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - - cur.execute(query) - - # Spaltennamen - columns = ['ID', 'Name', 'E-Mail', 'Erstellt am', 'Testdaten', - 'Lizenzen gesamt', 'Aktive Lizenzen', 'Abgelaufene Lizenzen'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Erstellt am'] = pd.to_datetime(df['Erstellt am']).dt.strftime('%d.%m.%Y %H:%M') - - # Testdaten formatting - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'customer', - additional_info=f"Export aller Kunden als {export_format.upper()}") - filename = f'kunden_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Kunden', index=False) - - # Formatierung - worksheet = writer.sheets['Kunden'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -# @app.route("/export/sessions") -# @login_required -def export_sessions(): - conn = get_connection() - cur = conn.cursor() - - # Holen des Session-Typs (active oder ended) - session_type = request.args.get('type', 'active') - export_format = request.args.get('format', 'excel') - - # Daten je nach Typ abrufen - if session_type == 'active': - # Aktive Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = true - ORDER BY s.last_heartbeat DESC - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Letzte Aktivität': sess[5].strftime('%d.%m.%Y %H:%M:%S'), - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Aktive Sessions' - filename_prefix = 'aktive_sessions' - else: - # Beendete Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = false AND s.ended_at IS NOT NULL - ORDER BY s.ended_at DESC - LIMIT 1000 - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] if sess[6] else 0 - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Endzeit': sess[5].strftime('%d.%m.%Y %H:%M:%S') if sess[5] else '', - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Beendete Sessions' - filename_prefix = 'beendete_sessions' - - cur.close() - conn.close() - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'{filename_prefix}_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'sessions', - additional_info=f"{export_format.upper()} Export von {session_type} Sessions mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name=sheet_name) - - # Spaltenbreiten anpassen - worksheet = writer.sheets[sheet_name] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -# @app.route("/export/resources") -# @login_required -def export_resources(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_type = request.args.get('type', '') - filter_status = request.args.get('status', '') - search_query = request.args.get('search', '') - show_test = request.args.get('show_test', 'false').lower() == 'true' - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT r.id, r.resource_type, r.resource_value, r.status, r.allocated_to_license, - r.created_at, r.status_changed_at, - l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type - FROM resource_pools r - LEFT JOIN licenses l ON r.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE 1=1 - """ - params = [] - - # Filter für Testdaten - if not show_test: - query += " AND (r.is_test = false OR r.is_test IS NULL)" - - # Filter für Ressourcentyp - if filter_type: - query += " AND r.resource_type = %s" - params.append(filter_type) - - # Filter für Status - if filter_status: - query += " AND r.status = %s" - params.append(filter_status) - - # Suchfilter - if search_query: - query += " AND (r.resource_value ILIKE %s OR l.license_key ILIKE %s OR c.name ILIKE %s)" - params.extend([f'%{search_query}%', f'%{search_query}%', f'%{search_query}%']) - - query += " ORDER BY r.id DESC" - - cur.execute(query, params) - resources = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for res in resources: - status_text = { - 'available': 'Verfügbar', - 'allocated': 'Zugewiesen', - 'quarantine': 'Quarantäne' - }.get(res[3], res[3]) - - type_text = { - 'domain': 'Domain', - 'ipv4': 'IPv4', - 'phone': 'Telefon' - }.get(res[1], res[1]) - - data.append({ - 'ID': res[0], - 'Typ': type_text, - 'Ressource': res[2], - 'Status': status_text, - 'Lizenzschlüssel': res[7] or '', - 'Kunde': res[8] or '', - 'Kunden-Email': res[9] or '', - 'Lizenztyp': res[10] or '', - 'Erstellt am': res[5].strftime('%d.%m.%Y %H:%M:%S') if res[5] else '', - 'Zugewiesen am': res[6].strftime('%d.%m.%Y %H:%M:%S') if res[6] else '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'resources_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'resources', - additional_info=f"{export_format.upper()} Export mit {len(data)} Ressourcen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Resources') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Resources'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -# @app.route("/audit") -# @login_required -def audit_log(): - conn = get_connection() - cur = conn.cursor() - - # Parameter - filter_user = request.args.get('user', '').strip() - filter_action = request.args.get('action', '').strip() - filter_entity = request.args.get('entity', '').strip() - page = request.args.get('page', 1, type=int) - sort = request.args.get('sort', 'timestamp') - order = request.args.get('order', 'desc') - per_page = 50 - - # Whitelist für erlaubte Sortierfelder - allowed_sort_fields = { - 'timestamp': 'timestamp', - 'username': 'username', - 'action': 'action', - 'entity': 'entity_type', - 'ip': 'ip_address' - } - - # Validierung - if sort not in allowed_sort_fields: - sort = 'timestamp' - if order not in ['asc', 'desc']: - order = 'desc' - - sort_field = allowed_sort_fields[sort] - - # SQL Query mit optionalen Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - - params = [] - - # Filter - if filter_user: - query += " AND LOWER(username) LIKE LOWER(%s)" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - # Gesamtanzahl für Pagination - count_query = "SELECT COUNT(*) FROM (" + query + ") as count_table" - cur.execute(count_query, params) - total = cur.fetchone()[0] - - # Pagination - offset = (page - 1) * per_page - query += f" ORDER BY {sort_field} {order.upper()} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - logs = cur.fetchall() - - # JSON-Werte parsen - parsed_logs = [] - for log in logs: - parsed_log = list(log) - # old_values und new_values sind bereits Dictionaries (JSONB) - # Keine Konvertierung nötig - parsed_logs.append(parsed_log) - - # Pagination Info - total_pages = (total + per_page - 1) // per_page - - cur.close() - conn.close() - - return render_template("audit_log.html", - logs=parsed_logs, - filter_user=filter_user, - filter_action=filter_action, - filter_entity=filter_entity, - page=page, - total_pages=total_pages, - total=total, - sort=sort, - order=order, - username=session.get('username')) - -# @app.route("/backups") -# @login_required -def backups(): - """Zeigt die Backup-Historie an""" - conn = get_connection() - cur = conn.cursor() - - # Letztes erfolgreiches Backup für Dashboard - cur.execute(""" - SELECT created_at, filesize, duration_seconds - FROM backup_history - WHERE status = 'success' - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup = cur.fetchone() - - # Alle Backups abrufen - cur.execute(""" - SELECT id, filename, filesize, backup_type, status, error_message, - created_at, created_by, tables_count, records_count, - duration_seconds, is_encrypted - FROM backup_history - ORDER BY created_at DESC - """) - backups = cur.fetchall() - - cur.close() - conn.close() - - return render_template("backups.html", - backups=backups, - last_backup=last_backup, - username=session.get('username')) - -# @app.route("/backup/create", methods=["POST"]) -# @login_required -def create_backup_route(): - """Erstellt ein manuelles Backup""" - username = session.get('username') - success, result = create_backup(backup_type="manual", created_by=username) - - if success: - return jsonify({ - 'success': True, - 'message': f'Backup erfolgreich erstellt: {result}' - }) - else: - return jsonify({ - 'success': False, - 'message': f'Backup fehlgeschlagen: {result}' - }), 500 - -# @app.route("/backup/restore/", methods=["POST"]) -# @login_required -def restore_backup_route(backup_id): - """Stellt ein Backup wieder her""" - encryption_key = request.form.get('encryption_key') - - success, message = restore_backup(backup_id, encryption_key) - - if success: - return jsonify({ - 'success': True, - 'message': message - }) - else: - return jsonify({ - 'success': False, - 'message': message - }), 500 - -# @app.route("/backup/download/") -# @login_required -def download_backup(backup_id): - """Lädt eine Backup-Datei herunter""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - cur.close() - conn.close() - - if not backup_info: - return "Backup nicht gefunden", 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - if not filepath.exists(): - return "Backup-Datei nicht gefunden", 404 - - # Audit-Log - log_audit('DOWNLOAD', 'backup', backup_id, - additional_info=f"Backup heruntergeladen: {filename}") - - return send_file(filepath, as_attachment=True, download_name=filename) - -# @app.route("/backup/delete/", methods=["DELETE"]) -# @login_required -def delete_backup(backup_id): - """Löscht ein Backup""" - conn = get_connection() - cur = conn.cursor() - - try: - # Backup-Informationen abrufen - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - if not backup_info: - return jsonify({ - 'success': False, - 'message': 'Backup nicht gefunden' - }), 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - # Datei löschen, wenn sie existiert - if filepath.exists(): - filepath.unlink() - - # Aus Datenbank löschen - cur.execute(""" - DELETE FROM backup_history - WHERE id = %s - """, (backup_id,)) - - conn.commit() - - # Audit-Log - log_audit('DELETE', 'backup', backup_id, - additional_info=f"Backup gelöscht: {filename}") - - return jsonify({ - 'success': True, - 'message': f'Backup "{filename}" wurde erfolgreich gelöscht' - }) - - except Exception as e: - conn.rollback() - return jsonify({ - 'success': False, - 'message': f'Fehler beim Löschen des Backups: {str(e)}' - }), 500 - finally: - cur.close() - conn.close() - -# @app.route("/security/blocked-ips") -# @login_required -def blocked_ips(): - """Zeigt alle gesperrten IPs an""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT - ip_address, - attempt_count, - first_attempt, - last_attempt, - blocked_until, - last_username_tried, - last_error_message - FROM login_attempts - WHERE blocked_until IS NOT NULL - ORDER BY blocked_until DESC - """) - - blocked_ips_list = [] - for ip in cur.fetchall(): - blocked_ips_list.append({ - 'ip_address': ip[0], - 'attempt_count': ip[1], - 'first_attempt': ip[2].strftime('%d.%m.%Y %H:%M'), - 'last_attempt': ip[3].strftime('%d.%m.%Y %H:%M'), - 'blocked_until': ip[4].strftime('%d.%m.%Y %H:%M'), - 'is_active': ip[4] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None), - 'last_username': ip[5], - 'last_error': ip[6] - }) - - cur.close() - conn.close() - - return render_template("blocked_ips.html", - blocked_ips=blocked_ips_list, - username=session.get('username')) - -# @app.route("/security/unblock-ip", methods=["POST"]) -# @login_required -def unblock_ip(): - """Entsperrt eine IP-Adresse""" - ip_address = request.form.get('ip_address') - - if ip_address: - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - UPDATE login_attempts - SET blocked_until = NULL - WHERE ip_address = %s - """, (ip_address,)) - - conn.commit() - cur.close() - conn.close() - - # Audit-Log - log_audit('UNBLOCK_IP', 'security', - additional_info=f"IP {ip_address} manuell entsperrt") - - return redirect(url_for('blocked_ips')) - -# @app.route("/security/clear-attempts", methods=["POST"]) -# @login_required -def clear_attempts(): - """Löscht alle Login-Versuche für eine IP""" - ip_address = request.form.get('ip_address') - - if ip_address: - reset_login_attempts(ip_address) - - # Audit-Log - log_audit('CLEAR_ATTEMPTS', 'security', - additional_info=f"Login-Versuche für IP {ip_address} zurückgesetzt") - - return redirect(url_for('blocked_ips')) - -# API Endpoints for License Management -# @app.route("/api/license//toggle", methods=["POST"]) -# @login_required -def toggle_license_api(license_id): - """Toggle license active status via API""" - try: - data = request.get_json() - is_active = data.get('is_active', False) - - conn = get_connection() - cur = conn.cursor() - - # Update license status - cur.execute(""" - UPDATE licenses - SET is_active = %s - WHERE id = %s - """, (is_active, license_id)) - - conn.commit() - - # Log the action - log_audit('UPDATE', 'license', license_id, - new_values={'is_active': is_active}, - additional_info=f"Lizenz {'aktiviert' if is_active else 'deaktiviert'} via Toggle") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Status erfolgreich geändert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# @app.route("/api/licenses/bulk-activate", methods=["POST"]) -# @login_required -def bulk_activate_licenses(): - """Activate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = TRUE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': True, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen aktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen aktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# @app.route("/api/licenses/bulk-deactivate", methods=["POST"]) -# @login_required -def bulk_deactivate_licenses(): - """Deactivate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = FALSE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': False, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen deaktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen deaktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# @app.route("/api/license//devices") -# @login_required -def get_license_devices(license_id): - """Hole alle registrierten Geräte einer Lizenz""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und hole device_limit - cur.execute(""" - SELECT device_limit FROM licenses WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit = license_data[0] - - # Hole alle Geräte für diese Lizenz - cur.execute(""" - SELECT id, hardware_id, device_name, operating_system, - first_seen, last_seen, is_active, ip_address - FROM device_registrations - WHERE license_id = %s - ORDER BY is_active DESC, last_seen DESC - """, (license_id,)) - - devices = [] - for row in cur.fetchall(): - devices.append({ - 'id': row[0], - 'hardware_id': row[1], - 'device_name': row[2] or 'Unbekanntes Gerät', - 'operating_system': row[3] or 'Unbekannt', - 'first_seen': row[4].strftime('%d.%m.%Y %H:%M') if row[4] else '', - 'last_seen': row[5].strftime('%d.%m.%Y %H:%M') if row[5] else '', - 'is_active': row[6], - 'ip_address': row[7] or '-' - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'devices': devices, - 'device_limit': device_limit, - 'active_count': sum(1 for d in devices if d['is_active']) - }) - - except Exception as e: - logging.error(f"Fehler beim Abrufen der Geräte: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Abrufen der Geräte'}), 500 - -# @app.route("/api/license//register-device", methods=["POST"]) -# def register_device(license_id): - # """Registriere ein neues Gerät für eine Lizenz""" - # try: - # data = request.get_json() - # hardware_id = data.get('hardware_id') - # device_name = data.get('device_name', '') - # operating_system = data.get('operating_system', '') - - # if not hardware_id: - # return jsonify({'success': False, 'message': 'Hardware-ID fehlt'}), 400 - - # conn = get_connection() - # cur = conn.cursor() - - # Prüfe ob Lizenz existiert und aktiv ist - # cur.execute(""" - # SELECT device_limit, is_active, valid_until - # FROM licenses - # WHERE id = %s - # """, (license_id,)) - # license_data = cur.fetchone() - - # if not license_data: - # return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - # device_limit, is_active, valid_until = license_data - - # Prüfe ob Lizenz aktiv und gültig ist - # if not is_active: - # return jsonify({'success': False, 'message': 'Lizenz ist deaktiviert'}), 403 - - # if valid_until < datetime.now(ZoneInfo("Europe/Berlin")).date(): - # return jsonify({'success': False, 'message': 'Lizenz ist abgelaufen'}), 403 - - # Prüfe ob Gerät bereits registriert ist - # cur.execute(""" - # SELECT id, is_active FROM device_registrations - # WHERE license_id = %s AND hardware_id = %s - # """, (license_id, hardware_id)) - # existing_device = cur.fetchone() - - # if existing_device: - # device_id, is_device_active = existing_device - # if is_device_active: - # Gerät ist bereits aktiv, update last_seen - # cur.execute(""" - # UPDATE device_registrations - # SET last_seen = CURRENT_TIMESTAMP, - # ip_address = %s, - # user_agent = %s - # WHERE id = %s - # """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - # conn.commit() - # return jsonify({'success': True, 'message': 'Gerät bereits registriert', 'device_id': device_id}) - # else: - # Gerät war deaktiviert, prüfe ob wir es reaktivieren können - # cur.execute(""" - # SELECT COUNT(*) FROM device_registrations - # WHERE license_id = %s AND is_active = TRUE - # """, (license_id,)) - # active_count = cur.fetchone()[0] - - # if active_count >= device_limit: - # return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Reaktiviere das Gerät - # cur.execute(""" - # UPDATE device_registrations - # SET is_active = TRUE, - # last_seen = CURRENT_TIMESTAMP, - # deactivated_at = NULL, - # deactivated_by = NULL, - # ip_address = %s, - # user_agent = %s - # WHERE id = %s - # """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - # conn.commit() - # return jsonify({'success': True, 'message': 'Gerät reaktiviert', 'device_id': device_id}) - - # Neues Gerät - prüfe Gerätelimit - # cur.execute(""" - # SELECT COUNT(*) FROM device_registrations - # WHERE license_id = %s AND is_active = TRUE - # """, (license_id,)) - # active_count = cur.fetchone()[0] - - # if active_count >= device_limit: - # return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Registriere neues Gerät - # cur.execute(""" - # INSERT INTO device_registrations - # (license_id, hardware_id, device_name, operating_system, ip_address, user_agent) - # VALUES (%s, %s, %s, %s, %s, %s) - # RETURNING id - # """, (license_id, hardware_id, device_name, operating_system, - # get_client_ip(), request.headers.get('User-Agent', ''))) - # device_id = cur.fetchone()[0] - - # conn.commit() - - # Audit Log - # log_audit('DEVICE_REGISTER', 'device', device_id, - # new_values={'license_id': license_id, 'hardware_id': hardware_id}) - - # cur.close() - # conn.close() - - # return jsonify({'success': True, 'message': 'Gerät erfolgreich registriert', 'device_id': device_id}) - - # except Exception as e: - # logging.error(f"Fehler bei Geräte-Registrierung: {str(e)}") - # return jsonify({'success': False, 'message': 'Fehler bei der Registrierung'}), 500 - -# @app.route("/api/license//deactivate-device/", methods=["POST"]) -# @login_required -def deactivate_device(license_id, device_id): - """Deaktiviere ein registriertes Gerät""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob das Gerät zu dieser Lizenz gehört - cur.execute(""" - SELECT id FROM device_registrations - WHERE id = %s AND license_id = %s AND is_active = TRUE - """, (device_id, license_id)) - - if not cur.fetchone(): - return jsonify({'success': False, 'message': 'Gerät nicht gefunden oder bereits deaktiviert'}), 404 - - # Deaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = FALSE, - deactivated_at = CURRENT_TIMESTAMP, - deactivated_by = %s - WHERE id = %s - """, (session['username'], device_id)) - - conn.commit() - - # Audit Log - log_audit('DEVICE_DEACTIVATE', 'device', device_id, - old_values={'is_active': True}, - new_values={'is_active': False}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich deaktiviert'}) - - except Exception as e: - logging.error(f"Fehler beim Deaktivieren des Geräts: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Deaktivieren'}), 500 - -# @app.route("/api/licenses/bulk-delete", methods=["POST"]) -# @login_required -def bulk_delete_licenses(): - """Delete multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Get license info for audit log (nur Live-Daten) - cur.execute(""" - SELECT license_key - FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - license_keys = [row[0] for row in cur.fetchall()] - - # Delete all selected licenses (nur Live-Daten) - cur.execute(""" - DELETE FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_DELETE', 'licenses', None, - old_values={'license_keys': license_keys, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen gelöscht") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen gelöscht'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# ===================== RESOURCE POOL MANAGEMENT ===================== - -# @app.route('/resources') -# @login_required -def resources(): - """Resource Pool Hauptübersicht""" - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Testdaten angezeigt werden sollen (gleiche Logik wie bei Kunden) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - # Statistiken abrufen - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = %s - GROUP BY resource_type - """, (show_test,)) - - stats = {} - for row in cur.fetchall(): - stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - } - - # Letzte Aktivitäten (gefiltert nach Test/Live) - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rp.resource_type, - rp.resource_value, - rh.details - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - WHERE rp.is_test = %s - ORDER BY rh.action_at DESC - LIMIT 10 - """, (show_test,)) - recent_activities = cur.fetchall() - - # Ressourcen-Liste mit Pagination - page = request.args.get('page', 1, type=int) - per_page = 50 - offset = (page - 1) * per_page - - resource_type = request.args.get('type', '') - status_filter = request.args.get('status', '') - search = request.args.get('search', '') - - # Sortierung - sort_by = request.args.get('sort', 'id') - sort_order = request.args.get('order', 'desc') - - # Base Query - query = """ - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - rp.allocated_to_license, - l.license_key, - c.name as customer_name, - rp.status_changed_at, - rp.quarantine_reason, - rp.quarantine_until, - c.id as customer_id - FROM resource_pools rp - LEFT JOIN licenses l ON rp.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rp.is_test = %s - """ - params = [show_test] - - if resource_type: - query += " AND rp.resource_type = %s" - params.append(resource_type) - - if status_filter: - query += " AND rp.status = %s" - params.append(status_filter) - - if search: - query += " AND rp.resource_value ILIKE %s" - params.append(f'%{search}%') - - # Count total - count_query = f"SELECT COUNT(*) FROM ({query}) as cnt" - cur.execute(count_query, params) - total = cur.fetchone()[0] - total_pages = (total + per_page - 1) // per_page - - # Get paginated results with dynamic sorting - sort_column_map = { - 'id': 'rp.id', - 'type': 'rp.resource_type', - 'resource': 'rp.resource_value', - 'status': 'rp.status', - 'assigned': 'c.name', - 'changed': 'rp.status_changed_at' - } - - sort_column = sort_column_map.get(sort_by, 'rp.id') - sort_direction = 'ASC' if sort_order == 'asc' else 'DESC' - - query += f" ORDER BY {sort_column} {sort_direction} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - resources = cur.fetchall() - - cur.close() - conn.close() - - return render_template('resources.html', - stats=stats, - resources=resources, - recent_activities=recent_activities, - page=page, - total_pages=total_pages, - total=total, - resource_type=resource_type, - status_filter=status_filter, - search=search, - show_test=show_test, - sort_by=sort_by, - sort_order=sort_order, - datetime=datetime, - timedelta=timedelta) - -# @app.route('/resources/add', methods=['GET', 'POST']) -# @login_required -def add_resources(): - """Ressourcen zum Pool hinzufügen""" - # Hole show_test Parameter für die Anzeige - show_test = request.args.get('show_test', 'false').lower() == 'true' - - if request.method == 'POST': - resource_type = request.form.get('resource_type') - resources_text = request.form.get('resources_text', '') - is_test = request.form.get('is_test') == 'on' # Checkbox für Testdaten - - # Parse resources (one per line) - resources = [r.strip() for r in resources_text.split('\n') if r.strip()] - - if not resources: - flash('Keine Ressourcen angegeben', 'error') - return redirect(url_for('add_resources', show_test=show_test)) - - conn = get_connection() - cur = conn.cursor() - - added = 0 - duplicates = 0 - - for resource_value in resources: - try: - cur.execute(""" - INSERT INTO resource_pools (resource_type, resource_value, status_changed_by, is_test) - VALUES (%s, %s, %s, %s) - ON CONFLICT (resource_type, resource_value) DO NOTHING - """, (resource_type, resource_value, session['username'], is_test)) - - if cur.rowcount > 0: - added += 1 - # Get the inserted ID - cur.execute("SELECT id FROM resource_pools WHERE resource_type = %s AND resource_value = %s", - (resource_type, resource_value)) - resource_id = cur.fetchone()[0] - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'created', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - else: - duplicates += 1 - - except Exception as e: - app.logger.error(f"Error adding resource {resource_value}: {e}") - - conn.commit() - cur.close() - conn.close() - - log_audit('CREATE', 'resource_pool', None, - new_values={'type': resource_type, 'added': added, 'duplicates': duplicates, 'is_test': is_test}, - additional_info=f"{added} {'Test-' if is_test else ''}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen") - - flash(f'{added} {"Test-" if is_test else ""}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen', 'success') - return redirect(url_for('resources', show_test=show_test)) - - return render_template('add_resources.html', show_test=show_test) - -# @app.route('/resources/quarantine/', methods=['POST']) -# @login_required -def quarantine_resource(resource_id): - """Ressource in Quarantäne setzen""" - reason = request.form.get('reason', 'review') - until_date = request.form.get('until_date') - notes = request.form.get('notes', '') - - conn = get_connection() - cur = conn.cursor() - - # Get current resource info - cur.execute("SELECT resource_type, resource_value, status FROM resource_pools WHERE id = %s", (resource_id,)) - resource = cur.fetchone() - - if not resource: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - old_status = resource[2] - - # Update resource - cur.execute(""" - UPDATE resource_pools - SET status = 'quarantine', - quarantine_reason = %s, - quarantine_until = %s, - notes = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (reason, until_date if until_date else None, notes, session['username'], resource_id)) - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address, details) - VALUES (%s, 'quarantined', %s, %s, %s) - """, (resource_id, session['username'], get_client_ip(), - Json({'reason': reason, 'until': until_date, 'notes': notes, 'old_status': old_status}))) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource', resource_id, - old_values={'status': old_status}, - new_values={'status': 'quarantine', 'reason': reason}, - additional_info=f"Ressource {resource[0]}: {resource[1]} in Quarantäne") - - flash('Ressource in Quarantäne gesetzt', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -# @app.route('/resources/release', methods=['POST']) -# @login_required -def release_resources(): - """Ressourcen aus Quarantäne freigeben""" - resource_ids = request.form.getlist('resource_ids') - - if not resource_ids: - flash('Keine Ressourcen ausgewählt', 'error') - return redirect(url_for('resources')) - - conn = get_connection() - cur = conn.cursor() - - released = 0 - for resource_id in resource_ids: - cur.execute(""" - UPDATE resource_pools - SET status = 'available', - quarantine_reason = NULL, - quarantine_until = NULL, - allocated_to_license = NULL, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s AND status = 'quarantine' - """, (session['username'], resource_id)) - - if cur.rowcount > 0: - released += 1 - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'released', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource_pool', None, - new_values={'released': released}, - additional_info=f"{released} Ressourcen aus Quarantäne freigegeben") - - flash(f'{released} Ressourcen freigegeben', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -# @app.route('/api/resources/allocate', methods=['POST']) -# @login_required -def allocate_resources_api(): - """API für Ressourcen-Zuweisung bei Lizenzerstellung""" - data = request.json - license_id = data.get('license_id') - domain_count = data.get('domain_count', 1) - ipv4_count = data.get('ipv4_count', 1) - phone_count = data.get('phone_count', 1) - - conn = get_connection() - cur = conn.cursor() - - try: - allocated = {'domains': [], 'ipv4s': [], 'phones': []} - - # Allocate domains - if domain_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' - LIMIT %s FOR UPDATE - """, (domain_count,)) - domains = cur.fetchall() - - if len(domains) < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {len(domains)})") - - for domain_id, domain_value in domains: - # Update resource status - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], domain_id)) - - # Create assignment - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, domain_id, session['username'])) - - # Log history - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (domain_id, license_id, session['username'], get_client_ip())) - - allocated['domains'].append(domain_value) - - # Allocate IPv4s (similar logic) - if ipv4_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' - LIMIT %s FOR UPDATE - """, (ipv4_count,)) - ipv4s = cur.fetchall() - - if len(ipv4s) < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar") - - for ipv4_id, ipv4_value in ipv4s: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], ipv4_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, ipv4_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (ipv4_id, license_id, session['username'], get_client_ip())) - - allocated['ipv4s'].append(ipv4_value) - - # Allocate phones (similar logic) - if phone_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' - LIMIT %s FOR UPDATE - """, (phone_count,)) - phones = cur.fetchall() - - if len(phones) < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar") - - for phone_id, phone_value in phones: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], phone_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, phone_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (phone_id, license_id, session['username'], get_client_ip())) - - allocated['phones'].append(phone_value) - - # Update license resource counts - cur.execute(""" - UPDATE licenses - SET domain_count = %s, - ipv4_count = %s, - phone_count = %s - WHERE id = %s - """, (domain_count, ipv4_count, phone_count, license_id)) - - conn.commit() - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'allocated': allocated - }) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({ - 'success': False, - 'error': str(e) - }), 400 - -# @app.route('/api/resources/check-availability', methods=['GET']) -# @login_required -def check_resource_availability(): - """Prüft verfügbare Ressourcen""" - resource_type = request.args.get('type', '') - count = request.args.get('count', 10, type=int) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - conn = get_connection() - cur = conn.cursor() - - if resource_type: - # Spezifische Ressourcen für einen Typ - cur.execute(""" - SELECT id, resource_value - FROM resource_pools - WHERE status = 'available' - AND resource_type = %s - AND is_test = %s - ORDER BY resource_value - LIMIT %s - """, (resource_type, show_test, count)) - - resources = [] - for row in cur.fetchall(): - resources.append({ - 'id': row[0], - 'value': row[1] - }) - - cur.close() - conn.close() - - return jsonify({ - 'available': resources, - 'type': resource_type, - 'count': len(resources) - }) - else: - # Zusammenfassung aller Typen - cur.execute(""" - SELECT - resource_type, - COUNT(*) as available - FROM resource_pools - WHERE status = 'available' - AND is_test = %s - GROUP BY resource_type - """, (show_test,)) - - availability = {} - for row in cur.fetchall(): - availability[row[0]] = row[1] - - cur.close() - conn.close() - - return jsonify(availability) - -# @app.route('/api/global-search', methods=['GET']) -# @login_required -def global_search(): - """Global search API endpoint for searching customers and licenses""" - query = request.args.get('q', '').strip() - - if not query or len(query) < 2: - return jsonify({'customers': [], 'licenses': []}) - - conn = get_connection() - cur = conn.cursor() - - # Search pattern with wildcards - search_pattern = f'%{query}%' - - # Search customers - cur.execute(""" - SELECT id, name, email, company_name - FROM customers - WHERE (LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - OR LOWER(company_name) LIKE LOWER(%s)) - AND is_test = FALSE - ORDER BY name - LIMIT 5 - """, (search_pattern, search_pattern, search_pattern)) - - customers = [] - for row in cur.fetchall(): - customers.append({ - 'id': row[0], - 'name': row[1], - 'email': row[2], - 'company_name': row[3] - }) - - # Search licenses - cur.execute(""" - SELECT l.id, l.license_key, c.name as customer_name - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE LOWER(l.license_key) LIKE LOWER(%s) - AND l.is_test = FALSE - ORDER BY l.created_at DESC - LIMIT 5 - """, (search_pattern,)) - - licenses = [] - for row in cur.fetchall(): - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'customer_name': row[2] - }) - - cur.close() - conn.close() - - return jsonify({ - 'customers': customers, - 'licenses': licenses - }) - -# @app.route('/resources/history/') -# @login_required -def resource_history(resource_id): - """Zeigt die komplette Historie einer Ressource""" - conn = get_connection() - cur = conn.cursor() - - # Get complete resource info using named columns - cur.execute(""" - SELECT id, resource_type, resource_value, status, allocated_to_license, - status_changed_at, status_changed_by, quarantine_reason, - quarantine_until, created_at, notes - FROM resource_pools - WHERE id = %s - """, (resource_id,)) - row = cur.fetchone() - - if not row: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - # Create resource object with named attributes - resource = { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'allocated_to_license': row[4], - 'status_changed_at': row[5], - 'status_changed_by': row[6], - 'quarantine_reason': row[7], - 'quarantine_until': row[8], - 'created_at': row[9], - 'notes': row[10] - } - - # Get license info if allocated - license_info = None - if resource['allocated_to_license']: - cur.execute("SELECT license_key FROM licenses WHERE id = %s", - (resource['allocated_to_license'],)) - lic = cur.fetchone() - if lic: - license_info = {'license_key': lic[0]} - - # Get history with named columns - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rh.details, - rh.license_id, - rh.ip_address - FROM resource_history rh - WHERE rh.resource_id = %s - ORDER BY rh.action_at DESC - """, (resource_id,)) - - history = [] - for row in cur.fetchall(): - history.append({ - 'action': row[0], - 'action_by': row[1], - 'action_at': row[2], - 'details': row[3], - 'license_id': row[4], - 'ip_address': row[5] - }) - - cur.close() - conn.close() - - # Convert to object-like for template - class ResourceObj: - def __init__(self, data): - for key, value in data.items(): - setattr(self, key, value) - - resource_obj = ResourceObj(resource) - history_objs = [ResourceObj(h) for h in history] - - return render_template('resource_history.html', - resource=resource_obj, - license_info=license_info, - history=history_objs) - -# @app.route('/resources/metrics') -# @login_required -def resources_metrics(): - """Dashboard für Resource Metrics und Reports""" - conn = get_connection() - cur = conn.cursor() - - # Overall stats with fallback values - cur.execute(""" - SELECT - COUNT(DISTINCT resource_id) as total_resources, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(cost), 0) as total_cost, - COALESCE(SUM(revenue), 0) as total_revenue, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - """) - row = cur.fetchone() - - # Calculate ROI - roi = 0 - if row[2] > 0: # if total_cost > 0 - roi = row[3] / row[2] # revenue / cost - - stats = { - 'total_resources': row[0] or 0, - 'avg_performance': row[1] or 0, - 'total_cost': row[2] or 0, - 'total_revenue': row[3] or 0, - 'total_issues': row[4] or 0, - 'roi': roi - } - - # Performance by type - cur.execute(""" - SELECT - rp.resource_type, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COUNT(DISTINCT rp.id) as resource_count - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY rp.resource_type - ORDER BY rp.resource_type - """) - performance_by_type = cur.fetchall() - - # Utilization data - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) as total, - ROUND(COUNT(*) FILTER (WHERE status = 'allocated') * 100.0 / COUNT(*), 1) as allocated_percent - FROM resource_pools - GROUP BY resource_type - """) - utilization_rows = cur.fetchall() - utilization_data = [ - { - 'type': row[0].upper(), - 'allocated': row[1], - 'total': row[2], - 'allocated_percent': row[3] - } - for row in utilization_rows - ] - - # Top performing resources - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COALESCE(SUM(rm.revenue), 0) as total_revenue, - COALESCE(SUM(rm.cost), 1) as total_cost, - CASE - WHEN COALESCE(SUM(rm.cost), 0) = 0 THEN 0 - ELSE COALESCE(SUM(rm.revenue), 0) / COALESCE(SUM(rm.cost), 1) - END as roi - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rp.status != 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value - HAVING AVG(rm.performance_score) IS NOT NULL - ORDER BY avg_score DESC - LIMIT 10 - """) - top_rows = cur.fetchall() - top_performers = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'avg_score': row[3], - 'roi': row[6] - } - for row in top_rows - ] - - # Resources with issues - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - COALESCE(SUM(rm.issues_count), 0) as total_issues - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rm.issues_count > 0 OR rp.status = 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - HAVING SUM(rm.issues_count) > 0 - ORDER BY total_issues DESC - LIMIT 10 - """) - problem_rows = cur.fetchall() - problem_resources = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'total_issues': row[4] - } - for row in problem_rows - ] - - # Daily metrics for trend chart (last 30 days) - cur.execute(""" - SELECT - metric_date, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY metric_date - ORDER BY metric_date - """) - daily_rows = cur.fetchall() - daily_metrics = [ - { - 'date': row[0].strftime('%d.%m'), - 'performance': float(row[1]), - 'issues': int(row[2]) - } - for row in daily_rows - ] - - cur.close() - conn.close() - - return render_template('resource_metrics.html', - stats=stats, - performance_by_type=performance_by_type, - utilization_data=utilization_data, - top_performers=top_performers, - problem_resources=problem_resources, - daily_metrics=daily_metrics) - -# @app.route('/resources/report', methods=['GET']) -# @login_required -def resources_report(): - """Generiert Ressourcen-Reports oder zeigt Report-Formular""" - # Prüfe ob Download angefordert wurde - if request.args.get('download') == 'true': - report_type = request.args.get('type', 'usage') - format_type = request.args.get('format', 'excel') - date_from = request.args.get('from', (datetime.now(ZoneInfo("Europe/Berlin")) - timedelta(days=30)).strftime('%Y-%m-%d')) - date_to = request.args.get('to', datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y-%m-%d')) - - conn = get_connection() - cur = conn.cursor() - - if report_type == 'usage': - # Auslastungsreport - query = """ - SELECT - rp.resource_type, - rp.resource_value, - rp.status, - COUNT(DISTINCT rh.license_id) as unique_licenses, - COUNT(rh.id) as total_allocations, - MIN(rh.action_at) as first_used, - MAX(rh.action_at) as last_used - FROM resource_pools rp - LEFT JOIN resource_history rh ON rp.id = rh.resource_id - AND rh.action = 'allocated' - AND rh.action_at BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - ORDER BY rp.resource_type, total_allocations DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Status', 'Unique Lizenzen', 'Gesamt Zuweisungen', 'Erste Nutzung', 'Letzte Nutzung'] - - elif report_type == 'performance': - # Performance-Report - query = """ - SELECT - rp.resource_type, - rp.resource_value, - AVG(rm.performance_score) as avg_performance, - SUM(rm.usage_count) as total_usage, - SUM(rm.revenue) as total_revenue, - SUM(rm.cost) as total_cost, - SUM(rm.revenue - rm.cost) as profit, - SUM(rm.issues_count) as total_issues - FROM resource_pools rp - JOIN resource_metrics rm ON rp.id = rm.resource_id - WHERE rm.metric_date BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value - ORDER BY profit DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Durchschn. Performance', 'Gesamt Nutzung', 'Umsatz', 'Kosten', 'Gewinn', 'Issues'] - - elif report_type == 'compliance': - # Compliance-Report - query = """ - SELECT - rh.action_at, - rh.action, - rh.action_by, - rp.resource_type, - rp.resource_value, - l.license_key, - c.name as customer_name, - rh.ip_address - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - LEFT JOIN licenses l ON rh.license_id = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rh.action_at BETWEEN %s AND %s - ORDER BY rh.action_at DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Zeit', 'Aktion', 'Von', 'Typ', 'Ressource', 'Lizenz', 'Kunde', 'IP-Adresse'] - - else: # inventory report - # Inventar-Report - query = """ - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - GROUP BY resource_type - ORDER BY resource_type - """ - cur.execute(query) - columns = ['Typ', 'Verfügbar', 'Zugeteilt', 'Quarantäne', 'Gesamt'] - - # Convert to DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - cur.close() - conn.close() - - # Generate file - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f"resource_report_{report_type}_{timestamp}" - - if format_type == 'excel': - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Report', index=False) - - # Auto-adjust columns width - worksheet = writer.sheets['Report'] - for column in worksheet.columns: - max_length = 0 - column = [cell for cell in column] - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = (max_length + 2) - worksheet.column_dimensions[column[0].column_letter].width = adjusted_width - - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'excel', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx') - - else: # CSV - output = io.StringIO() - df.to_csv(output, index=False, sep=';', encoding='utf-8-sig') - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'csv', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv') - - # Wenn kein Download, zeige Report-Formular - return render_template('resource_report.html', - datetime=datetime, - timedelta=timedelta, - username=session.get('username')) - -if __name__ == "__main__": - app.run(host="0.0.0.0", port=5000) diff --git a/v2_adminpanel/app.py.backup_before_cleanup_20250616_223919 b/v2_adminpanel/app.py.backup_before_cleanup_20250616_223919 deleted file mode 100644 index 4e6204a..0000000 --- a/v2_adminpanel/app.py.backup_before_cleanup_20250616_223919 +++ /dev/null @@ -1,4475 +0,0 @@ -import os -import sys -import time -import json -import logging -import requests -import re -import random -import base64 -from io import BytesIO -from datetime import datetime, timedelta -from zoneinfo import ZoneInfo -from pathlib import Path - -# Add current directory to Python path to ensure modules can be imported -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from flask import Flask, render_template, request, redirect, session, url_for, send_file, jsonify, flash -from flask_session import Session -from werkzeug.middleware.proxy_fix import ProxyFix -from apscheduler.schedulers.background import BackgroundScheduler -import pandas as pd -from psycopg2.extras import Json - -# Import our new modules -import config -from db import get_connection, get_db_connection, get_db_cursor, execute_query -from auth.decorators import login_required -from auth.password import hash_password, verify_password -from auth.two_factor import ( - generate_totp_secret, generate_qr_code, verify_totp, - generate_backup_codes, hash_backup_code, verify_backup_code -) -from auth.rate_limiting import ( - check_ip_blocked, record_failed_attempt, - reset_login_attempts, get_login_attempts -) -from utils.network import get_client_ip -from utils.audit import log_audit -from utils.license import generate_license_key, validate_license_key -from utils.backup import create_backup, restore_backup, get_or_create_encryption_key -from utils.export import ( - create_excel_export, format_datetime_for_export, - prepare_license_export_data, prepare_customer_export_data, - prepare_session_export_data, prepare_audit_export_data -) -from models import get_user_by_username - -app = Flask(__name__) -# Load configuration from config module -app.config['SECRET_KEY'] = config.SECRET_KEY -app.config['SESSION_TYPE'] = config.SESSION_TYPE -app.config['JSON_AS_ASCII'] = config.JSON_AS_ASCII -app.config['JSONIFY_MIMETYPE'] = config.JSONIFY_MIMETYPE -app.config['PERMANENT_SESSION_LIFETIME'] = config.PERMANENT_SESSION_LIFETIME -app.config['SESSION_COOKIE_HTTPONLY'] = config.SESSION_COOKIE_HTTPONLY -app.config['SESSION_COOKIE_SECURE'] = config.SESSION_COOKIE_SECURE -app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE -app.config['SESSION_COOKIE_NAME'] = config.SESSION_COOKIE_NAME -app.config['SESSION_REFRESH_EACH_REQUEST'] = config.SESSION_REFRESH_EACH_REQUEST -Session(app) - -# ProxyFix für korrekte IP-Adressen hinter Nginx -app.wsgi_app = ProxyFix( - app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 -) - -# Configuration is now loaded from config module - -# Scheduler für automatische Backups -scheduler = BackgroundScheduler() -scheduler.start() - -# Logging konfigurieren -logging.basicConfig(level=logging.INFO) - -# Import and register blueprints -from routes.auth_routes import auth_bp -from routes.admin_routes import admin_bp -from routes.license_routes import license_bp -from routes.customer_routes import customer_bp -from routes.resource_routes import resource_bp -from routes.session_routes import session_bp -from routes.batch_routes import batch_bp -from routes.api_routes import api_bp -from routes.export_routes import export_bp - -# Register blueprints -app.register_blueprint(auth_bp) -app.register_blueprint(admin_bp) -app.register_blueprint(license_bp) -app.register_blueprint(customer_bp) -app.register_blueprint(resource_bp) -app.register_blueprint(session_bp) -app.register_blueprint(batch_bp) -app.register_blueprint(api_bp) -app.register_blueprint(export_bp) - - -# Scheduled Backup Job -def scheduled_backup(): - """Führt ein geplantes Backup aus""" - logging.info("Starte geplantes Backup...") - create_backup(backup_type="scheduled", created_by="scheduler") - -# Scheduler konfigurieren - täglich um 3:00 Uhr -scheduler.add_job( - scheduled_backup, - 'cron', - hour=config.SCHEDULER_CONFIG['backup_hour'], - minute=config.SCHEDULER_CONFIG['backup_minute'], - id='daily_backup', - replace_existing=True -) - - -def verify_recaptcha(response): - """Verifiziert die reCAPTCHA v2 Response mit Google""" - secret_key = config.RECAPTCHA_SECRET_KEY - - # Wenn kein Secret Key konfiguriert ist, CAPTCHA als bestanden werten (für PoC) - if not secret_key: - logging.warning("RECAPTCHA_SECRET_KEY nicht konfiguriert - CAPTCHA wird übersprungen") - return True - - # Verifizierung bei Google - try: - verify_url = 'https://www.google.com/recaptcha/api/siteverify' - data = { - 'secret': secret_key, - 'response': response - } - - # Timeout für Request setzen - r = requests.post(verify_url, data=data, timeout=5) - result = r.json() - - # Log für Debugging - if not result.get('success'): - logging.warning(f"reCAPTCHA Validierung fehlgeschlagen: {result.get('error-codes', [])}") - - return result.get('success', False) - - except requests.exceptions.RequestException as e: - logging.error(f"reCAPTCHA Verifizierung fehlgeschlagen: {str(e)}") - # Bei Netzwerkfehlern CAPTCHA als bestanden werten - return True - except Exception as e: - logging.error(f"Unerwarteter Fehler bei reCAPTCHA: {str(e)}") - return False - - -# @app.route("/login", methods=["GET", "POST"]) -# def login(): - # Timing-Attack Schutz - Start Zeit merken - # start_time = time.time() - - # IP-Adresse ermitteln - # ip_address = get_client_ip() - - # Prüfen ob IP gesperrt ist - # is_blocked, blocked_until = check_ip_blocked(ip_address) - # if is_blocked: - # time_remaining = (blocked_until - datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None)).total_seconds() / 3600 - # error_msg = f"IP GESPERRT! Noch {time_remaining:.1f} Stunden warten." - # return render_template("login.html", error=error_msg, error_type="blocked") - - # Anzahl bisheriger Versuche - # attempt_count = get_login_attempts(ip_address) - - # if request.method == "POST": - # username = request.form.get("username") - # password = request.form.get("password") - # captcha_response = request.form.get("g-recaptcha-response") - - # CAPTCHA-Prüfung nur wenn Keys konfiguriert sind - # recaptcha_site_key = config.RECAPTCHA_SITE_KEY - # if attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and recaptcha_site_key: - # if not captcha_response: - # Timing-Attack Schutz - # elapsed = time.time() - start_time - # if elapsed < 1.0: - # time.sleep(1.0 - elapsed) - # return render_template("login.html", - # error="CAPTCHA ERFORDERLICH!", - # show_captcha=True, - # error_type="captcha", - # attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - # recaptcha_site_key=recaptcha_site_key) - - # CAPTCHA validieren - # if not verify_recaptcha(captcha_response): - # Timing-Attack Schutz - # elapsed = time.time() - start_time - # if elapsed < 1.0: - # time.sleep(1.0 - elapsed) - # return render_template("login.html", - # error="CAPTCHA UNGÜLTIG! Bitte erneut versuchen.", - # show_captcha=True, - # error_type="captcha", - # attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - # recaptcha_site_key=recaptcha_site_key) - - # Check user in database first, fallback to env vars - # user = get_user_by_username(username) - # login_success = False - # needs_2fa = False - - # if user: - # Database user authentication - # if verify_password(password, user['password_hash']): - # login_success = True - # needs_2fa = user['totp_enabled'] - # else: - # Fallback to environment variables for backward compatibility - # if username in config.ADMIN_USERS and password == config.ADMIN_USERS[username]: - # login_success = True - - # Timing-Attack Schutz - Mindestens 1 Sekunde warten - # elapsed = time.time() - start_time - # if elapsed < 1.0: - # time.sleep(1.0 - elapsed) - - # if login_success: - # Erfolgreicher Login - # if needs_2fa: - # Store temporary session for 2FA verification - # session['temp_username'] = username - # session['temp_user_id'] = user['id'] - # session['awaiting_2fa'] = True - # return redirect(url_for('verify_2fa')) - # else: - # Complete login without 2FA - # session.permanent = True # Aktiviert das Timeout - # session['logged_in'] = True - # session['username'] = username - # session['user_id'] = user['id'] if user else None - # session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # reset_login_attempts(ip_address) - # log_audit('LOGIN_SUCCESS', 'user', - # additional_info=f"Erfolgreiche Anmeldung von IP: {ip_address}") - # return redirect(url_for('dashboard')) - # else: - # Fehlgeschlagener Login - # error_message = record_failed_attempt(ip_address, username) - # new_attempt_count = get_login_attempts(ip_address) - - # Prüfen ob jetzt gesperrt - # is_now_blocked, _ = check_ip_blocked(ip_address) - # if is_now_blocked: - # log_audit('LOGIN_BLOCKED', 'security', - # additional_info=f"IP {ip_address} wurde nach {config.MAX_LOGIN_ATTEMPTS} Versuchen gesperrt") - - # return render_template("login.html", - # error=error_message, - # show_captcha=(new_attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - # error_type="failed", - # attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - new_attempt_count), - # recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - - # GET Request - # return render_template("login.html", - # show_captcha=(attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - # attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - # recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - -# @app.route("/logout") -# def logout(): - # username = session.get('username', 'unknown') - # log_audit('LOGOUT', 'user', additional_info=f"Abmeldung") - # session.pop('logged_in', None) - # session.pop('username', None) - # session.pop('user_id', None) - # session.pop('temp_username', None) - # session.pop('temp_user_id', None) - # session.pop('awaiting_2fa', None) - # return redirect(url_for('login')) - -# @app.route("/verify-2fa", methods=["GET", "POST"]) -# def verify_2fa(): - # if not session.get('awaiting_2fa'): - # return redirect(url_for('login')) - - # if request.method == "POST": - # token = request.form.get('token', '').replace(' ', '') - # username = session.get('temp_username') - # user_id = session.get('temp_user_id') - - # if not username or not user_id: - # flash('Session expired. Please login again.', 'error') - # return redirect(url_for('login')) - - # user = get_user_by_username(username) - # if not user: - # flash('User not found.', 'error') - # return redirect(url_for('login')) - - # Check if it's a backup code - # if len(token) == 8 and token.isupper(): - # Try backup code - # backup_codes = json.loads(user['backup_codes']) if user['backup_codes'] else [] - # if verify_backup_code(token, backup_codes): - # Remove used backup code - # code_hash = hash_backup_code(token) - # backup_codes.remove(code_hash) - - # conn = get_connection() - # cur = conn.cursor() - # cur.execute("UPDATE users SET backup_codes = %s WHERE id = %s", - # (json.dumps(backup_codes), user_id)) - # conn.commit() - # cur.close() - # conn.close() - - # Complete login - # session.permanent = True - # session['logged_in'] = True - # session['username'] = username - # session['user_id'] = user_id - # session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # session.pop('temp_username', None) - # session.pop('temp_user_id', None) - # session.pop('awaiting_2fa', None) - - # flash('Login successful using backup code. Please generate new backup codes.', 'warning') - # log_audit('LOGIN_2FA_BACKUP', 'user', additional_info=f"2FA login with backup code") - # return redirect(url_for('dashboard')) - # else: - # Try TOTP token - # if verify_totp(user['totp_secret'], token): - # Complete login - # session.permanent = True - # session['logged_in'] = True - # session['username'] = username - # session['user_id'] = user_id - # session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # session.pop('temp_username', None) - # session.pop('temp_user_id', None) - # session.pop('awaiting_2fa', None) - - # log_audit('LOGIN_2FA_SUCCESS', 'user', additional_info=f"2FA login successful") - # return redirect(url_for('dashboard')) - - # Failed verification - # conn = get_connection() - # cur = conn.cursor() - # cur.execute("UPDATE users SET failed_2fa_attempts = failed_2fa_attempts + 1, last_failed_2fa = %s WHERE id = %s", - # (datetime.now(), user_id)) - # conn.commit() - # cur.close() - # conn.close() - - # flash('Invalid authentication code. Please try again.', 'error') - # log_audit('LOGIN_2FA_FAILED', 'user', additional_info=f"Failed 2FA attempt") - - # return render_template('verify_2fa.html') - -# @app.route("/profile") -# @login_required -def profile(): - user = get_user_by_username(session['username']) - if not user: - # For environment-based users, redirect with message - flash('Bitte führen Sie das Migrations-Script aus, um Passwort-Änderung und 2FA zu aktivieren.', 'info') - return redirect(url_for('dashboard')) - return render_template('profile.html', user=user) - -# @app.route("/profile/change-password", methods=["POST"]) -# @login_required -def change_password(): - current_password = request.form.get('current_password') - new_password = request.form.get('new_password') - confirm_password = request.form.get('confirm_password') - - user = get_user_by_username(session['username']) - - # Verify current password - if not verify_password(current_password, user['password_hash']): - flash('Current password is incorrect.', 'error') - return redirect(url_for('profile')) - - # Check new password - if new_password != confirm_password: - flash('New passwords do not match.', 'error') - return redirect(url_for('profile')) - - if len(new_password) < 8: - flash('Password must be at least 8 characters long.', 'error') - return redirect(url_for('profile')) - - # Update password - new_hash = hash_password(new_password) - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET password_hash = %s, last_password_change = %s WHERE id = %s", - (new_hash, datetime.now(), user['id'])) - conn.commit() - cur.close() - conn.close() - - log_audit('PASSWORD_CHANGE', 'user', entity_id=user['id'], - additional_info="Password changed successfully") - flash('Password changed successfully.', 'success') - return redirect(url_for('profile')) - -# @app.route("/profile/setup-2fa") -# @login_required -def setup_2fa(): - user = get_user_by_username(session['username']) - - if user['totp_enabled']: - flash('2FA is already enabled for your account.', 'info') - return redirect(url_for('profile')) - - # Generate new TOTP secret - totp_secret = generate_totp_secret() - session['temp_totp_secret'] = totp_secret - - # Generate QR code - qr_code = generate_qr_code(user['username'], totp_secret) - - return render_template('setup_2fa.html', - totp_secret=totp_secret, - qr_code=qr_code) - -# @app.route("/profile/enable-2fa", methods=["POST"]) -# @login_required -def enable_2fa(): - token = request.form.get('token', '').replace(' ', '') - totp_secret = session.get('temp_totp_secret') - - if not totp_secret: - flash('2FA setup session expired. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Verify the token - if not verify_totp(totp_secret, token): - flash('Invalid authentication code. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Generate backup codes - backup_codes = generate_backup_codes() - hashed_codes = [hash_backup_code(code) for code in backup_codes] - - # Enable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_secret = %s, totp_enabled = TRUE, backup_codes = %s - WHERE username = %s - """, (totp_secret, json.dumps(hashed_codes), session['username'])) - conn.commit() - cur.close() - conn.close() - - session.pop('temp_totp_secret', None) - - log_audit('2FA_ENABLED', 'user', additional_info="2FA enabled successfully") - - # Show backup codes - return render_template('backup_codes.html', backup_codes=backup_codes) - -# @app.route("/profile/disable-2fa", methods=["POST"]) -# @login_required -def disable_2fa(): - password = request.form.get('password') - user = get_user_by_username(session['username']) - - # Verify password - if not verify_password(password, user['password_hash']): - flash('Incorrect password.', 'error') - return redirect(url_for('profile')) - - # Disable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_enabled = FALSE, totp_secret = NULL, backup_codes = NULL - WHERE username = %s - """, (session['username'],)) - conn.commit() - cur.close() - conn.close() - - log_audit('2FA_DISABLED', 'user', additional_info="2FA disabled") - flash('2FA has been disabled for your account.', 'success') - return redirect(url_for('profile')) - -# @app.route("/heartbeat", methods=['POST']) -# @login_required -def heartbeat(): - """Endpoint für Session Keep-Alive - aktualisiert last_activity""" - # Aktualisiere last_activity nur wenn explizit angefordert - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # Force session save - session.modified = True - - return jsonify({ - 'status': 'ok', - 'last_activity': session['last_activity'], - 'username': session.get('username') - }) - -# @app.route("/api/generate-license-key", methods=['POST']) -# @login_required -def api_generate_key(): - """API Endpoint zur Generierung eines neuen Lizenzschlüssels""" - try: - # Lizenztyp aus Request holen (default: full) - data = request.get_json() or {} - license_type = data.get('type', 'full') - - # Key generieren - key = generate_license_key(license_type) - - # Prüfen ob Key bereits existiert (sehr unwahrscheinlich aber sicher ist sicher) - conn = get_connection() - cur = conn.cursor() - - # Wiederhole bis eindeutiger Key gefunden - attempts = 0 - while attempts < 10: # Max 10 Versuche - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (key,)) - if not cur.fetchone(): - break # Key ist eindeutig - key = generate_license_key(license_type) - attempts += 1 - - cur.close() - conn.close() - - # Log für Audit - log_audit('GENERATE_KEY', 'license', - additional_info={'type': license_type, 'key': key}) - - return jsonify({ - 'success': True, - 'key': key, - 'type': license_type - }) - - except Exception as e: - logging.error(f"Fehler bei Key-Generierung: {str(e)}") - return jsonify({ - 'success': False, - 'error': 'Fehler bei der Key-Generierung' - }), 500 - -# @app.route("/api/customers", methods=['GET']) -# @login_required -def api_customers(): - """API Endpoint für die Kundensuche mit Select2""" - try: - # Suchparameter - search = request.args.get('q', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - customer_id = request.args.get('id', type=int) - - conn = get_connection() - cur = conn.cursor() - - # Einzelnen Kunden per ID abrufen - if customer_id: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.id = %s - GROUP BY c.id, c.name, c.email - """, (customer_id,)) - - customer = cur.fetchone() - results = [] - if customer: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} ({customer[2]})", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - cur.close() - conn.close() - - return jsonify({ - 'results': results, - 'pagination': {'more': False} - }) - - # SQL Query mit optionaler Suche - elif search: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE LOWER(c.name) LIKE LOWER(%s) - OR LOWER(c.email) LIKE LOWER(%s) - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (f'%{search}%', f'%{search}%', per_page, (page - 1) * per_page)) - else: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (per_page, (page - 1) * per_page)) - - customers = cur.fetchall() - - # Format für Select2 - results = [] - for customer in customers: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} - {customer[2]} ({customer[3]} Lizenzen)", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - # Gesamtanzahl für Pagination - if search: - cur.execute(""" - SELECT COUNT(*) FROM customers - WHERE LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - """, (f'%{search}%', f'%{search}%')) - else: - cur.execute("SELECT COUNT(*) FROM customers") - - total_count = cur.fetchone()[0] - - cur.close() - conn.close() - - # Select2 Response Format - return jsonify({ - 'results': results, - 'pagination': { - 'more': (page * per_page) < total_count - } - }) - - except Exception as e: - logging.error(f"Fehler bei Kundensuche: {str(e)}") - return jsonify({ - 'results': [], - 'error': 'Fehler bei der Kundensuche' - }), 500 - -# @app.route("/") -# @login_required -def dashboard(): - conn = get_connection() - cur = conn.cursor() - - # Statistiken abrufen - # Gesamtanzahl Kunden (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = FALSE") - total_customers = cur.fetchone()[0] - - # Gesamtanzahl Lizenzen (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = FALSE") - total_licenses = cur.fetchone()[0] - - # Aktive Lizenzen (nicht abgelaufen und is_active = true, ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE AND is_active = TRUE AND is_test = FALSE - """) - active_licenses = cur.fetchone()[0] - - # Aktive Sessions - cur.execute("SELECT COUNT(*) FROM sessions WHERE is_active = TRUE") - active_sessions_count = cur.fetchone()[0] - - # Abgelaufene Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until < CURRENT_DATE AND is_test = FALSE - """) - expired_licenses = cur.fetchone()[0] - - # Deaktivierte Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE is_active = FALSE AND is_test = FALSE - """) - inactive_licenses = cur.fetchone()[0] - - # Lizenzen die in den nächsten 30 Tagen ablaufen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE - AND valid_until < CURRENT_DATE + INTERVAL '30 days' - AND is_active = TRUE - AND is_test = FALSE - """) - expiring_soon = cur.fetchone()[0] - - # Testlizenzen vs Vollversionen (ohne Testdaten) - cur.execute(""" - SELECT license_type, COUNT(*) - FROM licenses - WHERE is_test = FALSE - GROUP BY license_type - """) - license_types = dict(cur.fetchall()) - - # Anzahl Testdaten - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = TRUE") - test_data_count = cur.fetchone()[0] - - # Anzahl Test-Kunden - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = TRUE") - test_customers_count = cur.fetchone()[0] - - # Anzahl Test-Ressourcen - cur.execute("SELECT COUNT(*) FROM resource_pools WHERE is_test = TRUE") - test_resources_count = cur.fetchone()[0] - - # Letzte 5 erstellten Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.is_test = FALSE - ORDER BY l.id DESC - LIMIT 5 - """) - recent_licenses = cur.fetchall() - - # Bald ablaufende Lizenzen (nächste 30 Tage, ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - l.valid_until - CURRENT_DATE as days_left - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.valid_until >= CURRENT_DATE - AND l.valid_until < CURRENT_DATE + INTERVAL '30 days' - AND l.is_active = TRUE - AND l.is_test = FALSE - ORDER BY l.valid_until - LIMIT 10 - """) - expiring_licenses = cur.fetchall() - - # Letztes Backup - cur.execute(""" - SELECT created_at, filesize, duration_seconds, backup_type, status - FROM backup_history - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup_info = cur.fetchone() - - # Sicherheitsstatistiken - # Gesperrte IPs - cur.execute(""" - SELECT COUNT(*) FROM login_attempts - WHERE blocked_until IS NOT NULL AND blocked_until > CURRENT_TIMESTAMP - """) - blocked_ips_count = cur.fetchone()[0] - - # Fehlversuche heute - cur.execute(""" - SELECT COALESCE(SUM(attempt_count), 0) FROM login_attempts - WHERE last_attempt::date = CURRENT_DATE - """) - failed_attempts_today = cur.fetchone()[0] - - # Letzte 5 Sicherheitsereignisse - cur.execute(""" - SELECT - la.ip_address, - la.attempt_count, - la.last_attempt, - la.blocked_until, - la.last_username_tried, - la.last_error_message - FROM login_attempts la - ORDER BY la.last_attempt DESC - LIMIT 5 - """) - recent_security_events = [] - for event in cur.fetchall(): - recent_security_events.append({ - 'ip_address': event[0], - 'attempt_count': event[1], - 'last_attempt': event[2].strftime('%d.%m %H:%M'), - 'blocked_until': event[3].strftime('%d.%m %H:%M') if event[3] and event[3] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) else None, - 'username_tried': event[4], - 'error_message': event[5] - }) - - # Sicherheitslevel berechnen - if blocked_ips_count > 5 or failed_attempts_today > 50: - security_level = 'danger' - security_level_text = 'KRITISCH' - elif blocked_ips_count > 2 or failed_attempts_today > 20: - security_level = 'warning' - security_level_text = 'ERHÖHT' - else: - security_level = 'success' - security_level_text = 'NORMAL' - - # Resource Pool Statistiken (nur Live-Daten, keine Testdaten) - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = FALSE - GROUP BY resource_type - """) - - resource_stats = {} - resource_warning = None - - for row in cur.fetchall(): - available_percent = round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - resource_stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': available_percent, - 'warning_level': 'danger' if row[1] < 50 else 'warning' if row[1] < 100 else 'success' - } - - # Warnung bei niedrigem Bestand - if row[1] < 50: - if not resource_warning: - resource_warning = f"Niedriger Bestand bei {row[0].upper()}: nur noch {row[1]} verfügbar!" - else: - resource_warning += f" | {row[0].upper()}: {row[1]}" - - cur.close() - conn.close() - - stats = { - 'total_customers': total_customers, - 'total_licenses': total_licenses, - 'active_licenses': active_licenses, - 'expired_licenses': expired_licenses, - 'inactive_licenses': inactive_licenses, - 'expiring_soon': expiring_soon, - 'full_licenses': license_types.get('full', 0), - 'test_licenses': license_types.get('test', 0), - 'test_data_count': test_data_count, - 'test_customers_count': test_customers_count, - 'test_resources_count': test_resources_count, - 'recent_licenses': recent_licenses, - 'expiring_licenses': expiring_licenses, - 'active_sessions': active_sessions_count, - 'last_backup': last_backup_info, - # Sicherheitsstatistiken - 'blocked_ips_count': blocked_ips_count, - 'failed_attempts_today': failed_attempts_today, - 'recent_security_events': recent_security_events, - 'security_level': security_level, - 'security_level_text': security_level_text, - 'resource_stats': resource_stats - } - - return render_template("dashboard.html", - stats=stats, - resource_stats=resource_stats, - resource_warning=resource_warning, - username=session.get('username')) - -# @app.route("/create", methods=["GET", "POST"]) -# @login_required -def create_license(): - if request.method == "POST": - customer_id = request.form.get("customer_id") - license_key = request.form["license_key"].upper() # Immer Großbuchstaben - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Validiere License Key Format - if not validate_license_key(license_key): - flash('Ungültiges License Key Format! Erwartet: AF-YYYYMMFT-XXXX-YYYY-ZZZZ', 'error') - return redirect(url_for('create_license')) - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('create_license')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('create_license')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - customer_info = {'name': name, 'email': email, 'is_test': is_test} - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos für Audit-Log - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('create_license')) - customer_info = {'name': customer_data[0], 'email': customer_data[1]} - - # Wenn Kunde Test-Kunde ist, Lizenz auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Lizenz hinzufügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit, is_test) - VALUES (%s, %s, %s, %s, %s, TRUE, %s, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit, is_test)) - license_id = cur.fetchone()[0] - - # Ressourcen zuweisen - try: - # Prüfe Verfügbarkeit - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {available[0]})") - if available[1] < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {ipv4_count}, verfügbar: {available[1]})") - if available[2] < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar (benötigt: {phone_count}, verfügbar: {available[2]})") - - # Domains zuweisen - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s zuweisen - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern zuweisen - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - except ValueError as e: - conn.rollback() - flash(str(e), 'error') - return redirect(url_for('create_license')) - - conn.commit() - - # Audit-Log - log_audit('CREATE', 'license', license_id, - new_values={ - 'license_key': license_key, - 'customer_name': customer_info['name'], - 'customer_email': customer_info['email'], - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'device_limit': device_limit, - 'is_test': is_test - }) - - flash(f'Lizenz {license_key} erfolgreich erstellt!', 'success') - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Erstellen der Lizenz: {str(e)}") - flash('Fehler beim Erstellen der Lizenz!', 'error') - finally: - cur.close() - conn.close() - - # Preserve show_test parameter if present - redirect_url = "/create" - if request.args.get('show_test') == 'true': - redirect_url += "?show_test=true" - return redirect(redirect_url) - - # Unterstützung für vorausgewählten Kunden - preselected_customer_id = request.args.get('customer_id', type=int) - return render_template("index.html", username=session.get('username'), preselected_customer_id=preselected_customer_id) - -# @app.route("/batch", methods=["GET", "POST"]) -# @login_required -def batch_licenses(): - """Batch-Generierung mehrerer Lizenzen für einen Kunden""" - if request.method == "POST": - # Formulardaten - customer_id = request.form.get("customer_id") - license_type = request.form["license_type"] - quantity = int(request.form["quantity"]) - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - # Sicherheitslimit - if quantity < 1 or quantity > 100: - flash('Anzahl muss zwischen 1 und 100 liegen!', 'error') - return redirect(url_for('batch_licenses')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('batch_licenses')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('batch_licenses')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('batch_licenses')) - name = customer_data[0] - email = customer_data[1] - - # Wenn Kunde Test-Kunde ist, Lizenzen auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Prüfe Ressourcen-Verfügbarkeit für gesamten Batch - total_domains_needed = domain_count * quantity - total_ipv4s_needed = ipv4_count * quantity - total_phones_needed = phone_count * quantity - - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < total_domains_needed: - flash(f"Nicht genügend Domains verfügbar (benötigt: {total_domains_needed}, verfügbar: {available[0]})", 'error') - return redirect(url_for('batch_licenses')) - if available[1] < total_ipv4s_needed: - flash(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {total_ipv4s_needed}, verfügbar: {available[1]})", 'error') - return redirect(url_for('batch_licenses')) - if available[2] < total_phones_needed: - flash(f"Nicht genügend Telefonnummern verfügbar (benötigt: {total_phones_needed}, verfügbar: {available[2]})", 'error') - return redirect(url_for('batch_licenses')) - - # Lizenzen generieren und speichern - generated_licenses = [] - for i in range(quantity): - # Eindeutigen Key generieren - attempts = 0 - while attempts < 10: - license_key = generate_license_key(license_type) - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (license_key,)) - if not cur.fetchone(): - break - attempts += 1 - - # Lizenz einfügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, is_test, - valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit) - VALUES (%s, %s, %s, %s, %s, %s, true, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, is_test, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit)) - license_id = cur.fetchone()[0] - - # Ressourcen für diese Lizenz zuweisen - # Domains - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - generated_licenses.append({ - 'id': license_id, - 'key': license_key, - 'type': license_type - }) - - conn.commit() - - # Audit-Log - log_audit('CREATE_BATCH', 'license', - new_values={'customer': name, 'quantity': quantity, 'type': license_type}, - additional_info=f"Batch-Generierung von {quantity} Lizenzen") - - # Session für Export speichern - session['batch_export'] = { - 'customer': name, - 'email': email, - 'licenses': generated_licenses, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'timestamp': datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - } - - flash(f'{quantity} Lizenzen erfolgreich generiert!', 'success') - return render_template("batch_result.html", - customer=name, - email=email, - licenses=generated_licenses, - valid_from=valid_from, - valid_until=valid_until) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler bei Batch-Generierung: {str(e)}") - flash('Fehler bei der Batch-Generierung!', 'error') - return redirect(url_for('batch_licenses')) - finally: - cur.close() - conn.close() - - # GET Request - return render_template("batch_form.html") - -# @app.route("/batch/export") -# @login_required -def export_batch(): - """Exportiert die zuletzt generierten Batch-Lizenzen""" - batch_data = session.get('batch_export') - if not batch_data: - flash('Keine Batch-Daten zum Exportieren vorhanden!', 'error') - return redirect(url_for('batch_licenses')) - - # CSV generieren - output = io.StringIO() - output.write('\ufeff') # UTF-8 BOM für Excel - - # Header - output.write(f"Kunde: {batch_data['customer']}\n") - output.write(f"E-Mail: {batch_data['email']}\n") - output.write(f"Generiert am: {datetime.fromisoformat(batch_data['timestamp']).strftime('%d.%m.%Y %H:%M')}\n") - output.write(f"Gültig von: {batch_data['valid_from']} bis {batch_data['valid_until']}\n") - output.write("\n") - output.write("Nr;Lizenzschlüssel;Typ\n") - - # Lizenzen - for i, license in enumerate(batch_data['licenses'], 1): - typ_text = "Vollversion" if license['type'] == 'full' else "Testversion" - output.write(f"{i};{license['key']};{typ_text}\n") - - output.seek(0) - - # Audit-Log - log_audit('EXPORT', 'batch_licenses', - additional_info=f"Export von {len(batch_data['licenses'])} Batch-Lizenzen") - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f"batch_licenses_{batch_data['customer'].replace(' ', '_')}_{datetime.now(ZoneInfo('Europe/Berlin')).strftime('%Y%m%d_%H%M%S')}.csv" - ) - -# @app.route("/licenses") -# @login_required -def licenses(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -# @app.route("/license/edit/", methods=["GET", "POST"]) -# @login_required -def edit_license(license_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute(""" - SELECT license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit - FROM licenses WHERE id = %s - """, (license_id,)) - old_license = cur.fetchone() - - # Update license - license_key = request.form["license_key"] - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - valid_until = request.form["valid_until"] - is_active = request.form.get("is_active") == "on" - is_test = request.form.get("is_test") == "on" - device_limit = int(request.form.get("device_limit", 3)) - - cur.execute(""" - UPDATE licenses - SET license_key = %s, license_type = %s, valid_from = %s, - valid_until = %s, is_active = %s, is_test = %s, device_limit = %s - WHERE id = %s - """, (license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit, license_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'license_key': old_license[0], - 'license_type': old_license[1], - 'valid_from': str(old_license[2]), - 'valid_until': str(old_license[3]), - 'is_active': old_license[4], - 'is_test': old_license[5], - 'device_limit': old_license[6] - }, - new_values={ - 'license_key': license_key, - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'is_active': is_active, - 'is_test': is_test, - 'device_limit': device_limit - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei wenn vorhanden - if request.referrer and 'customer_id=' in request.referrer: - import re - match = re.search(r'customer_id=(\d+)', request.referrer) - if match: - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={match.group(1)}" - - return redirect(redirect_url) - - # Get license data - cur.execute(""" - SELECT l.id, l.license_key, c.name, c.email, l.license_type, - l.valid_from, l.valid_until, l.is_active, c.id, l.is_test, l.device_limit - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - - license = cur.fetchone() - cur.close() - conn.close() - - if not license: - return redirect("/licenses") - - return render_template("edit_license.html", license=license, username=session.get('username')) - -# @app.route("/license/delete/", methods=["POST"]) -# @login_required -def delete_license(license_id): - conn = get_connection() - cur = conn.cursor() - - # Lizenzdetails für Audit-Log abrufen - cur.execute(""" - SELECT l.license_key, c.name, l.license_type - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - license_info = cur.fetchone() - - cur.execute("DELETE FROM licenses WHERE id = %s", (license_id,)) - - conn.commit() - - # Audit-Log - if license_info: - log_audit('DELETE', 'license', license_id, - old_values={ - 'license_key': license_info[0], - 'customer_name': license_info[1], - 'license_type': license_info[2] - }) - - cur.close() - conn.close() - - return redirect("/licenses") - -# @app.route("/customers") -# @login_required -def customers(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -# @app.route("/customer/edit/", methods=["GET", "POST"]) -# @login_required -def edit_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - old_customer = cur.fetchone() - - # Update customer - name = request.form["name"] - email = request.form["email"] - is_test = request.form.get("is_test") == "on" - - cur.execute(""" - UPDATE customers - SET name = %s, email = %s, is_test = %s - WHERE id = %s - """, (name, email, is_test, customer_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'customer', customer_id, - old_values={ - 'name': old_customer[0], - 'email': old_customer[1], - 'is_test': old_customer[2] - }, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei (immer der aktuelle Kunde) - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={customer_id}" - - return redirect(redirect_url) - - # Get customer data with licenses - cur.execute(""" - SELECT id, name, email, created_at, is_test FROM customers WHERE id = %s - """, (customer_id,)) - - customer = cur.fetchone() - if not customer: - cur.close() - conn.close() - return "Kunde nicht gefunden", 404 - - - # Get customer's licenses - cur.execute(""" - SELECT id, license_key, license_type, valid_from, valid_until, is_active - FROM licenses - WHERE customer_id = %s - ORDER BY valid_until DESC - """, (customer_id,)) - - licenses = cur.fetchall() - - cur.close() - conn.close() - - if not customer: - return redirect("/customers-licenses") - - return render_template("edit_customer.html", customer=customer, licenses=licenses, username=session.get('username')) - -# @app.route("/customer/create", methods=["GET", "POST"]) -# @login_required -def create_customer(): - """Erstellt einen neuen Kunden ohne Lizenz""" - if request.method == "POST": - name = request.form.get('name') - email = request.form.get('email') - is_test = request.form.get('is_test') == 'on' - - if not name or not email: - flash("Name und E-Mail sind Pflichtfelder!", "error") - return render_template("create_customer.html", username=session.get('username')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfen ob E-Mail bereits existiert - cur.execute("SELECT id, name FROM customers WHERE email = %s", (email,)) - existing = cur.fetchone() - if existing: - flash(f"Ein Kunde mit der E-Mail '{email}' existiert bereits: {existing[1]}", "error") - return render_template("create_customer.html", username=session.get('username')) - - # Kunde erstellen - cur.execute(""" - INSERT INTO customers (name, email, created_at, is_test) - VALUES (%s, %s, %s, %s) RETURNING id - """, (name, email, datetime.now(), is_test)) - - customer_id = cur.fetchone()[0] - conn.commit() - - # Audit-Log - log_audit('CREATE', 'customer', customer_id, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - flash(f"Kunde '{name}' wurde erfolgreich angelegt!", "success") - return redirect(f"/customer/edit/{customer_id}") - - except Exception as e: - conn.rollback() - flash(f"Fehler beim Anlegen des Kunden: {str(e)}", "error") - return render_template("create_customer.html", username=session.get('username')) - finally: - cur.close() - conn.close() - - # GET Request - Formular anzeigen - return render_template("create_customer.html", username=session.get('username')) - -# @app.route("/customer/delete/", methods=["POST"]) -# @login_required -def delete_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - # Prüfen ob Kunde Lizenzen hat - cur.execute("SELECT COUNT(*) FROM licenses WHERE customer_id = %s", (customer_id,)) - license_count = cur.fetchone()[0] - - if license_count > 0: - # Kunde hat Lizenzen - nicht löschen - cur.close() - conn.close() - return redirect("/customers") - - # Kundendetails für Audit-Log abrufen - cur.execute("SELECT name, email FROM customers WHERE id = %s", (customer_id,)) - customer_info = cur.fetchone() - - # Kunde löschen wenn keine Lizenzen vorhanden - cur.execute("DELETE FROM customers WHERE id = %s", (customer_id,)) - - conn.commit() - - # Audit-Log - if customer_info: - log_audit('DELETE', 'customer', customer_id, - old_values={ - 'name': customer_info[0], - 'email': customer_info[1] - }) - - cur.close() - conn.close() - - return redirect("/customers") - -# @app.route("/customers-licenses") -# @login_required -def customers_licenses(): - """Kombinierte Ansicht für Kunden und deren Lizenzen""" - conn = get_connection() - cur = conn.cursor() - - # Hole alle Kunden mit Lizenzstatistiken (inkl. Testkunden wenn gewünscht) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - query = """ - SELECT - c.id, - c.name, - c.email, - c.created_at, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - """ - - if not show_test: - query += " WHERE c.is_test = FALSE" - - query += """ - GROUP BY c.id, c.name, c.email, c.created_at - ORDER BY c.name - """ - - cur.execute(query) - customers = cur.fetchall() - - # Hole ausgewählten Kunden nur wenn explizit in URL angegeben - selected_customer_id = request.args.get('customer_id', type=int) - licenses = [] - selected_customer = None - - if customers and selected_customer_id: - # Hole Daten des ausgewählten Kunden - for customer in customers: - if customer[0] == selected_customer_id: - selected_customer = customer - break - - # Hole Lizenzen des ausgewählten Kunden - if selected_customer: - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (selected_customer_id,)) - licenses = cur.fetchall() - - cur.close() - conn.close() - - return render_template("customers_licenses.html", - customers=customers, - selected_customer=selected_customer, - selected_customer_id=selected_customer_id, - licenses=licenses, - show_test=show_test) - -# @app.route("/api/customer//licenses") -# @login_required -def api_customer_licenses(customer_id): - """API-Endpoint für AJAX-Abruf der Lizenzen eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Lizenzen des Kunden - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (customer_id,)) - - licenses = [] - for row in cur.fetchall(): - license_id = row[0] - - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for res_row in cur.fetchall(): - resource_info = { - 'id': res_row[0], - 'value': res_row[2], - 'assigned_at': res_row[3].strftime('%d.%m.%Y') if res_row[3] else '' - } - - if res_row[1] == 'domain': - resources['domains'].append(resource_info) - elif res_row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif res_row[1] == 'phone': - resources['phones'].append(resource_info) - - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'license_type': row[2], - 'valid_from': row[3].strftime('%d.%m.%Y') if row[3] else '', - 'valid_until': row[4].strftime('%d.%m.%Y') if row[4] else '', - 'is_active': row[5], - 'status': row[6], - 'domain_count': row[7], # limit - 'ipv4_count': row[8], # limit - 'phone_count': row[9], # limit - 'device_limit': row[10], - 'active_devices': row[11], - 'actual_domain_count': row[12], # actual count - 'actual_ipv4_count': row[13], # actual count - 'actual_phone_count': row[14], # actual count - 'resources': resources - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'licenses': licenses, - 'count': len(licenses) - }) - -# @app.route("/api/customer//quick-stats") -# @login_required -def api_customer_quick_stats(customer_id): - """API-Endpoint für Schnellstatistiken eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Kundenstatistiken - cur.execute(""" - SELECT - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' AND l.valid_until >= CURRENT_DATE THEN 1 END) as expiring_soon - FROM licenses l - WHERE l.customer_id = %s - """, (customer_id,)) - - stats = cur.fetchone() - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'stats': { - 'total': stats[0], - 'active': stats[1], - 'expired': stats[2], - 'expiring_soon': stats[3] - } - }) - -# @app.route("/api/license//quick-edit", methods=['POST']) -# @login_required -def api_license_quick_edit(license_id): - """API-Endpoint für schnelle Lizenz-Bearbeitung""" - conn = get_connection() - cur = conn.cursor() - - try: - data = request.get_json() - - # Hole alte Werte für Audit-Log - cur.execute(""" - SELECT is_active, valid_until, license_type - FROM licenses WHERE id = %s - """, (license_id,)) - old_values = cur.fetchone() - - if not old_values: - return jsonify({'success': False, 'error': 'Lizenz nicht gefunden'}), 404 - - # Update-Felder vorbereiten - updates = [] - params = [] - new_values = {} - - if 'is_active' in data: - updates.append("is_active = %s") - params.append(data['is_active']) - new_values['is_active'] = data['is_active'] - - if 'valid_until' in data: - updates.append("valid_until = %s") - params.append(data['valid_until']) - new_values['valid_until'] = data['valid_until'] - - if 'license_type' in data: - updates.append("license_type = %s") - params.append(data['license_type']) - new_values['license_type'] = data['license_type'] - - if updates: - params.append(license_id) - cur.execute(f""" - UPDATE licenses - SET {', '.join(updates)} - WHERE id = %s - """, params) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'is_active': old_values[0], - 'valid_until': old_values[1].isoformat() if old_values[1] else None, - 'license_type': old_values[2] - }, - new_values=new_values) - - cur.close() - conn.close() - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -# @app.route("/api/license//resources") -# @login_required -def api_license_resources(license_id): - """API-Endpoint für detaillierte Ressourcen-Informationen einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for row in cur.fetchall(): - resource_info = { - 'id': row[0], - 'value': row[2], - 'assigned_at': row[3].strftime('%d.%m.%Y') if row[3] else '' - } - - if row[1] == 'domain': - resources['domains'].append(resource_info) - elif row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif row[1] == 'phone': - resources['phones'].append(resource_info) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'resources': resources - }) - - except Exception as e: - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -# @app.route("/sessions") -# @login_required -def sessions(): - conn = get_connection() - cur = conn.cursor() - - # Sortierparameter - active_sort = request.args.get('active_sort', 'last_heartbeat') - active_order = request.args.get('active_order', 'desc') - ended_sort = request.args.get('ended_sort', 'ended_at') - ended_order = request.args.get('ended_order', 'desc') - - # Whitelist für erlaubte Sortierfelder - Aktive Sessions - active_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'last_heartbeat': 's.last_heartbeat', - 'inactive': 'minutes_inactive' - } - - # Whitelist für erlaubte Sortierfelder - Beendete Sessions - ended_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'ended_at': 's.ended_at', - 'duration': 'duration_minutes' - } - - # Validierung - if active_sort not in active_sort_fields: - active_sort = 'last_heartbeat' - if ended_sort not in ended_sort_fields: - ended_sort = 'ended_at' - if active_order not in ['asc', 'desc']: - active_order = 'desc' - if ended_order not in ['asc', 'desc']: - ended_order = 'desc' - - # Aktive Sessions abrufen - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.user_agent, s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.last_heartbeat))/60 as minutes_inactive - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = TRUE - ORDER BY {active_sort_fields[active_sort]} {active_order.upper()} - """) - active_sessions = cur.fetchall() - - # Inaktive Sessions der letzten 24 Stunden - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))/60 as duration_minutes - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = FALSE - AND s.ended_at > NOW() - INTERVAL '24 hours' - ORDER BY {ended_sort_fields[ended_sort]} {ended_order.upper()} - LIMIT 50 - """) - recent_sessions = cur.fetchall() - - cur.close() - conn.close() - - return render_template("sessions.html", - active_sessions=active_sessions, - recent_sessions=recent_sessions, - active_sort=active_sort, - active_order=active_order, - ended_sort=ended_sort, - ended_order=ended_order, - username=session.get('username')) - -# @app.route("/session/end/", methods=["POST"]) -# @login_required -def end_session(session_id): - conn = get_connection() - cur = conn.cursor() - - # Session beenden - cur.execute(""" - UPDATE sessions - SET is_active = FALSE, ended_at = NOW() - WHERE id = %s AND is_active = TRUE - """, (session_id,)) - - conn.commit() - cur.close() - conn.close() - - return redirect("/sessions") - -# @app.route("/export/licenses") -# @login_required -def export_licenses(): - conn = get_connection() - cur = conn.cursor() - - # Alle Lizenzen mit Kundeninformationen abrufen (ohne Testdaten, außer explizit gewünscht) - include_test = request.args.get('include_test', 'false').lower() == 'true' - customer_id = request.args.get('customer_id', type=int) - - query = """ - SELECT l.id, l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type, l.valid_from, l.valid_until, l.is_active, l.is_test, - CASE - WHEN l.is_active = FALSE THEN 'Deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'Abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'Läuft bald ab' - ELSE 'Aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - """ - - # Build WHERE clause - where_conditions = [] - params = [] - - if not include_test: - where_conditions.append("l.is_test = FALSE") - - if customer_id: - where_conditions.append("l.customer_id = %s") - params.append(customer_id) - - if where_conditions: - query += " WHERE " + " AND ".join(where_conditions) - - query += " ORDER BY l.id" - - cur.execute(query, params) - - # Spaltennamen - columns = ['ID', 'Lizenzschlüssel', 'Kunde', 'E-Mail', 'Typ', - 'Gültig von', 'Gültig bis', 'Aktiv', 'Testdaten', 'Status'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Gültig von'] = pd.to_datetime(df['Gültig von']).dt.strftime('%d.%m.%Y') - df['Gültig bis'] = pd.to_datetime(df['Gültig bis']).dt.strftime('%d.%m.%Y') - - # Typ und Aktiv Status anpassen - df['Typ'] = df['Typ'].replace({'full': 'Vollversion', 'test': 'Testversion'}) - df['Aktiv'] = df['Aktiv'].replace({True: 'Ja', False: 'Nein'}) - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'license', - additional_info=f"Export aller Lizenzen als {export_format.upper()}") - filename = f'lizenzen_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Lizenzen', index=False) - - # Formatierung - worksheet = writer.sheets['Lizenzen'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -# @app.route("/export/audit") -# @login_required -def export_audit(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_user = request.args.get('user', '') - filter_action = request.args.get('action', '') - filter_entity = request.args.get('entity', '') - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - params = [] - - if filter_user: - query += " AND username ILIKE %s" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - query += " ORDER BY timestamp DESC" - - cur.execute(query, params) - audit_logs = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for log in audit_logs: - action_text = { - 'CREATE': 'Erstellt', - 'UPDATE': 'Bearbeitet', - 'DELETE': 'Gelöscht', - 'LOGIN': 'Anmeldung', - 'LOGOUT': 'Abmeldung', - 'AUTO_LOGOUT': 'Auto-Logout', - 'EXPORT': 'Export', - 'GENERATE_KEY': 'Key generiert', - 'CREATE_BATCH': 'Batch erstellt', - 'BACKUP': 'Backup erstellt', - 'LOGIN_2FA_SUCCESS': '2FA-Anmeldung', - 'LOGIN_2FA_BACKUP': '2FA-Backup-Code', - 'LOGIN_2FA_FAILED': '2FA-Fehlgeschlagen', - 'LOGIN_BLOCKED': 'Login-Blockiert', - 'RESTORE': 'Wiederhergestellt', - 'PASSWORD_CHANGE': 'Passwort geändert', - '2FA_ENABLED': '2FA aktiviert', - '2FA_DISABLED': '2FA deaktiviert' - }.get(log[3], log[3]) - - data.append({ - 'ID': log[0], - 'Zeitstempel': log[1].strftime('%d.%m.%Y %H:%M:%S'), - 'Benutzer': log[2], - 'Aktion': action_text, - 'Entität': log[4], - 'Entität-ID': log[5] or '', - 'IP-Adresse': log[8] or '', - 'Zusatzinfo': log[10] or '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'audit_log_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'audit_log', - additional_info=f"{export_format.upper()} Export mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Audit Log') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Audit Log'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -# @app.route("/export/customers") -# @login_required -def export_customers(): - conn = get_connection() - cur = conn.cursor() - - # Check if test data should be included - include_test = request.args.get('include_test', 'false').lower() == 'true' - - # Build query based on test data filter - if include_test: - # Include all customers - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - else: - # Exclude test customers and test licenses - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(CASE WHEN l.is_test = FALSE THEN 1 END) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.is_test = FALSE - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - - cur.execute(query) - - # Spaltennamen - columns = ['ID', 'Name', 'E-Mail', 'Erstellt am', 'Testdaten', - 'Lizenzen gesamt', 'Aktive Lizenzen', 'Abgelaufene Lizenzen'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Erstellt am'] = pd.to_datetime(df['Erstellt am']).dt.strftime('%d.%m.%Y %H:%M') - - # Testdaten formatting - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'customer', - additional_info=f"Export aller Kunden als {export_format.upper()}") - filename = f'kunden_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Kunden', index=False) - - # Formatierung - worksheet = writer.sheets['Kunden'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -# @app.route("/export/sessions") -# @login_required -def export_sessions(): - conn = get_connection() - cur = conn.cursor() - - # Holen des Session-Typs (active oder ended) - session_type = request.args.get('type', 'active') - export_format = request.args.get('format', 'excel') - - # Daten je nach Typ abrufen - if session_type == 'active': - # Aktive Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = true - ORDER BY s.last_heartbeat DESC - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Letzte Aktivität': sess[5].strftime('%d.%m.%Y %H:%M:%S'), - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Aktive Sessions' - filename_prefix = 'aktive_sessions' - else: - # Beendete Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = false AND s.ended_at IS NOT NULL - ORDER BY s.ended_at DESC - LIMIT 1000 - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] if sess[6] else 0 - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Endzeit': sess[5].strftime('%d.%m.%Y %H:%M:%S') if sess[5] else '', - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Beendete Sessions' - filename_prefix = 'beendete_sessions' - - cur.close() - conn.close() - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'{filename_prefix}_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'sessions', - additional_info=f"{export_format.upper()} Export von {session_type} Sessions mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name=sheet_name) - - # Spaltenbreiten anpassen - worksheet = writer.sheets[sheet_name] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -# @app.route("/export/resources") -# @login_required -def export_resources(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_type = request.args.get('type', '') - filter_status = request.args.get('status', '') - search_query = request.args.get('search', '') - show_test = request.args.get('show_test', 'false').lower() == 'true' - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT r.id, r.resource_type, r.resource_value, r.status, r.allocated_to_license, - r.created_at, r.status_changed_at, - l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type - FROM resource_pools r - LEFT JOIN licenses l ON r.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE 1=1 - """ - params = [] - - # Filter für Testdaten - if not show_test: - query += " AND (r.is_test = false OR r.is_test IS NULL)" - - # Filter für Ressourcentyp - if filter_type: - query += " AND r.resource_type = %s" - params.append(filter_type) - - # Filter für Status - if filter_status: - query += " AND r.status = %s" - params.append(filter_status) - - # Suchfilter - if search_query: - query += " AND (r.resource_value ILIKE %s OR l.license_key ILIKE %s OR c.name ILIKE %s)" - params.extend([f'%{search_query}%', f'%{search_query}%', f'%{search_query}%']) - - query += " ORDER BY r.id DESC" - - cur.execute(query, params) - resources = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for res in resources: - status_text = { - 'available': 'Verfügbar', - 'allocated': 'Zugewiesen', - 'quarantine': 'Quarantäne' - }.get(res[3], res[3]) - - type_text = { - 'domain': 'Domain', - 'ipv4': 'IPv4', - 'phone': 'Telefon' - }.get(res[1], res[1]) - - data.append({ - 'ID': res[0], - 'Typ': type_text, - 'Ressource': res[2], - 'Status': status_text, - 'Lizenzschlüssel': res[7] or '', - 'Kunde': res[8] or '', - 'Kunden-Email': res[9] or '', - 'Lizenztyp': res[10] or '', - 'Erstellt am': res[5].strftime('%d.%m.%Y %H:%M:%S') if res[5] else '', - 'Zugewiesen am': res[6].strftime('%d.%m.%Y %H:%M:%S') if res[6] else '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'resources_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'resources', - additional_info=f"{export_format.upper()} Export mit {len(data)} Ressourcen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Resources') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Resources'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -# @app.route("/audit") -# @login_required -def audit_log(): - conn = get_connection() - cur = conn.cursor() - - # Parameter - filter_user = request.args.get('user', '').strip() - filter_action = request.args.get('action', '').strip() - filter_entity = request.args.get('entity', '').strip() - page = request.args.get('page', 1, type=int) - sort = request.args.get('sort', 'timestamp') - order = request.args.get('order', 'desc') - per_page = 50 - - # Whitelist für erlaubte Sortierfelder - allowed_sort_fields = { - 'timestamp': 'timestamp', - 'username': 'username', - 'action': 'action', - 'entity': 'entity_type', - 'ip': 'ip_address' - } - - # Validierung - if sort not in allowed_sort_fields: - sort = 'timestamp' - if order not in ['asc', 'desc']: - order = 'desc' - - sort_field = allowed_sort_fields[sort] - - # SQL Query mit optionalen Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - - params = [] - - # Filter - if filter_user: - query += " AND LOWER(username) LIKE LOWER(%s)" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - # Gesamtanzahl für Pagination - count_query = "SELECT COUNT(*) FROM (" + query + ") as count_table" - cur.execute(count_query, params) - total = cur.fetchone()[0] - - # Pagination - offset = (page - 1) * per_page - query += f" ORDER BY {sort_field} {order.upper()} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - logs = cur.fetchall() - - # JSON-Werte parsen - parsed_logs = [] - for log in logs: - parsed_log = list(log) - # old_values und new_values sind bereits Dictionaries (JSONB) - # Keine Konvertierung nötig - parsed_logs.append(parsed_log) - - # Pagination Info - total_pages = (total + per_page - 1) // per_page - - cur.close() - conn.close() - - return render_template("audit_log.html", - logs=parsed_logs, - filter_user=filter_user, - filter_action=filter_action, - filter_entity=filter_entity, - page=page, - total_pages=total_pages, - total=total, - sort=sort, - order=order, - username=session.get('username')) - -# @app.route("/backups") -# @login_required -def backups(): - """Zeigt die Backup-Historie an""" - conn = get_connection() - cur = conn.cursor() - - # Letztes erfolgreiches Backup für Dashboard - cur.execute(""" - SELECT created_at, filesize, duration_seconds - FROM backup_history - WHERE status = 'success' - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup = cur.fetchone() - - # Alle Backups abrufen - cur.execute(""" - SELECT id, filename, filesize, backup_type, status, error_message, - created_at, created_by, tables_count, records_count, - duration_seconds, is_encrypted - FROM backup_history - ORDER BY created_at DESC - """) - backups = cur.fetchall() - - cur.close() - conn.close() - - return render_template("backups.html", - backups=backups, - last_backup=last_backup, - username=session.get('username')) - -# @app.route("/backup/create", methods=["POST"]) -# @login_required -def create_backup_route(): - """Erstellt ein manuelles Backup""" - username = session.get('username') - success, result = create_backup(backup_type="manual", created_by=username) - - if success: - return jsonify({ - 'success': True, - 'message': f'Backup erfolgreich erstellt: {result}' - }) - else: - return jsonify({ - 'success': False, - 'message': f'Backup fehlgeschlagen: {result}' - }), 500 - -# @app.route("/backup/restore/", methods=["POST"]) -# @login_required -def restore_backup_route(backup_id): - """Stellt ein Backup wieder her""" - encryption_key = request.form.get('encryption_key') - - success, message = restore_backup(backup_id, encryption_key) - - if success: - return jsonify({ - 'success': True, - 'message': message - }) - else: - return jsonify({ - 'success': False, - 'message': message - }), 500 - -# @app.route("/backup/download/") -# @login_required -def download_backup(backup_id): - """Lädt eine Backup-Datei herunter""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - cur.close() - conn.close() - - if not backup_info: - return "Backup nicht gefunden", 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - if not filepath.exists(): - return "Backup-Datei nicht gefunden", 404 - - # Audit-Log - log_audit('DOWNLOAD', 'backup', backup_id, - additional_info=f"Backup heruntergeladen: {filename}") - - return send_file(filepath, as_attachment=True, download_name=filename) - -# @app.route("/backup/delete/", methods=["DELETE"]) -# @login_required -def delete_backup(backup_id): - """Löscht ein Backup""" - conn = get_connection() - cur = conn.cursor() - - try: - # Backup-Informationen abrufen - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - if not backup_info: - return jsonify({ - 'success': False, - 'message': 'Backup nicht gefunden' - }), 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - # Datei löschen, wenn sie existiert - if filepath.exists(): - filepath.unlink() - - # Aus Datenbank löschen - cur.execute(""" - DELETE FROM backup_history - WHERE id = %s - """, (backup_id,)) - - conn.commit() - - # Audit-Log - log_audit('DELETE', 'backup', backup_id, - additional_info=f"Backup gelöscht: {filename}") - - return jsonify({ - 'success': True, - 'message': f'Backup "{filename}" wurde erfolgreich gelöscht' - }) - - except Exception as e: - conn.rollback() - return jsonify({ - 'success': False, - 'message': f'Fehler beim Löschen des Backups: {str(e)}' - }), 500 - finally: - cur.close() - conn.close() - -# @app.route("/security/blocked-ips") -# @login_required -def blocked_ips(): - """Zeigt alle gesperrten IPs an""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT - ip_address, - attempt_count, - first_attempt, - last_attempt, - blocked_until, - last_username_tried, - last_error_message - FROM login_attempts - WHERE blocked_until IS NOT NULL - ORDER BY blocked_until DESC - """) - - blocked_ips_list = [] - for ip in cur.fetchall(): - blocked_ips_list.append({ - 'ip_address': ip[0], - 'attempt_count': ip[1], - 'first_attempt': ip[2].strftime('%d.%m.%Y %H:%M'), - 'last_attempt': ip[3].strftime('%d.%m.%Y %H:%M'), - 'blocked_until': ip[4].strftime('%d.%m.%Y %H:%M'), - 'is_active': ip[4] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None), - 'last_username': ip[5], - 'last_error': ip[6] - }) - - cur.close() - conn.close() - - return render_template("blocked_ips.html", - blocked_ips=blocked_ips_list, - username=session.get('username')) - -# @app.route("/security/unblock-ip", methods=["POST"]) -# @login_required -def unblock_ip(): - """Entsperrt eine IP-Adresse""" - ip_address = request.form.get('ip_address') - - if ip_address: - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - UPDATE login_attempts - SET blocked_until = NULL - WHERE ip_address = %s - """, (ip_address,)) - - conn.commit() - cur.close() - conn.close() - - # Audit-Log - log_audit('UNBLOCK_IP', 'security', - additional_info=f"IP {ip_address} manuell entsperrt") - - return redirect(url_for('blocked_ips')) - -# @app.route("/security/clear-attempts", methods=["POST"]) -# @login_required -def clear_attempts(): - """Löscht alle Login-Versuche für eine IP""" - ip_address = request.form.get('ip_address') - - if ip_address: - reset_login_attempts(ip_address) - - # Audit-Log - log_audit('CLEAR_ATTEMPTS', 'security', - additional_info=f"Login-Versuche für IP {ip_address} zurückgesetzt") - - return redirect(url_for('blocked_ips')) - -# API Endpoints for License Management -# @app.route("/api/license//toggle", methods=["POST"]) -# @login_required -def toggle_license_api(license_id): - """Toggle license active status via API""" - try: - data = request.get_json() - is_active = data.get('is_active', False) - - conn = get_connection() - cur = conn.cursor() - - # Update license status - cur.execute(""" - UPDATE licenses - SET is_active = %s - WHERE id = %s - """, (is_active, license_id)) - - conn.commit() - - # Log the action - log_audit('UPDATE', 'license', license_id, - new_values={'is_active': is_active}, - additional_info=f"Lizenz {'aktiviert' if is_active else 'deaktiviert'} via Toggle") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Status erfolgreich geändert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# @app.route("/api/licenses/bulk-activate", methods=["POST"]) -# @login_required -def bulk_activate_licenses(): - """Activate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = TRUE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': True, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen aktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen aktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# @app.route("/api/licenses/bulk-deactivate", methods=["POST"]) -# @login_required -def bulk_deactivate_licenses(): - """Deactivate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = FALSE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': False, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen deaktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen deaktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# @app.route("/api/license//devices") -# @login_required -def get_license_devices(license_id): - """Hole alle registrierten Geräte einer Lizenz""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und hole device_limit - cur.execute(""" - SELECT device_limit FROM licenses WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit = license_data[0] - - # Hole alle Geräte für diese Lizenz - cur.execute(""" - SELECT id, hardware_id, device_name, operating_system, - first_seen, last_seen, is_active, ip_address - FROM device_registrations - WHERE license_id = %s - ORDER BY is_active DESC, last_seen DESC - """, (license_id,)) - - devices = [] - for row in cur.fetchall(): - devices.append({ - 'id': row[0], - 'hardware_id': row[1], - 'device_name': row[2] or 'Unbekanntes Gerät', - 'operating_system': row[3] or 'Unbekannt', - 'first_seen': row[4].strftime('%d.%m.%Y %H:%M') if row[4] else '', - 'last_seen': row[5].strftime('%d.%m.%Y %H:%M') if row[5] else '', - 'is_active': row[6], - 'ip_address': row[7] or '-' - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'devices': devices, - 'device_limit': device_limit, - 'active_count': sum(1 for d in devices if d['is_active']) - }) - - except Exception as e: - logging.error(f"Fehler beim Abrufen der Geräte: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Abrufen der Geräte'}), 500 - -# @app.route("/api/license//register-device", methods=["POST"]) -# def register_device(license_id): - # """Registriere ein neues Gerät für eine Lizenz""" - # try: - # data = request.get_json() - # hardware_id = data.get('hardware_id') - # device_name = data.get('device_name', '') - # operating_system = data.get('operating_system', '') - - # if not hardware_id: - # return jsonify({'success': False, 'message': 'Hardware-ID fehlt'}), 400 - - # conn = get_connection() - # cur = conn.cursor() - - # Prüfe ob Lizenz existiert und aktiv ist - # cur.execute(""" - # SELECT device_limit, is_active, valid_until - # FROM licenses - # WHERE id = %s - # """, (license_id,)) - # license_data = cur.fetchone() - - # if not license_data: - # return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - # device_limit, is_active, valid_until = license_data - - # Prüfe ob Lizenz aktiv und gültig ist - # if not is_active: - # return jsonify({'success': False, 'message': 'Lizenz ist deaktiviert'}), 403 - - # if valid_until < datetime.now(ZoneInfo("Europe/Berlin")).date(): - # return jsonify({'success': False, 'message': 'Lizenz ist abgelaufen'}), 403 - - # Prüfe ob Gerät bereits registriert ist - # cur.execute(""" - # SELECT id, is_active FROM device_registrations - # WHERE license_id = %s AND hardware_id = %s - # """, (license_id, hardware_id)) - # existing_device = cur.fetchone() - - # if existing_device: - # device_id, is_device_active = existing_device - # if is_device_active: - # Gerät ist bereits aktiv, update last_seen - # cur.execute(""" - # UPDATE device_registrations - # SET last_seen = CURRENT_TIMESTAMP, - # ip_address = %s, - # user_agent = %s - # WHERE id = %s - # """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - # conn.commit() - # return jsonify({'success': True, 'message': 'Gerät bereits registriert', 'device_id': device_id}) - # else: - # Gerät war deaktiviert, prüfe ob wir es reaktivieren können - # cur.execute(""" - # SELECT COUNT(*) FROM device_registrations - # WHERE license_id = %s AND is_active = TRUE - # """, (license_id,)) - # active_count = cur.fetchone()[0] - - # if active_count >= device_limit: - # return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Reaktiviere das Gerät - # cur.execute(""" - # UPDATE device_registrations - # SET is_active = TRUE, - # last_seen = CURRENT_TIMESTAMP, - # deactivated_at = NULL, - # deactivated_by = NULL, - # ip_address = %s, - # user_agent = %s - # WHERE id = %s - # """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - # conn.commit() - # return jsonify({'success': True, 'message': 'Gerät reaktiviert', 'device_id': device_id}) - - # Neues Gerät - prüfe Gerätelimit - # cur.execute(""" - # SELECT COUNT(*) FROM device_registrations - # WHERE license_id = %s AND is_active = TRUE - # """, (license_id,)) - # active_count = cur.fetchone()[0] - - # if active_count >= device_limit: - # return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Registriere neues Gerät - # cur.execute(""" - # INSERT INTO device_registrations - # (license_id, hardware_id, device_name, operating_system, ip_address, user_agent) - # VALUES (%s, %s, %s, %s, %s, %s) - # RETURNING id - # """, (license_id, hardware_id, device_name, operating_system, - # get_client_ip(), request.headers.get('User-Agent', ''))) - # device_id = cur.fetchone()[0] - - # conn.commit() - - # Audit Log - # log_audit('DEVICE_REGISTER', 'device', device_id, - # new_values={'license_id': license_id, 'hardware_id': hardware_id}) - - # cur.close() - # conn.close() - - # return jsonify({'success': True, 'message': 'Gerät erfolgreich registriert', 'device_id': device_id}) - - # except Exception as e: - # logging.error(f"Fehler bei Geräte-Registrierung: {str(e)}") - # return jsonify({'success': False, 'message': 'Fehler bei der Registrierung'}), 500 - -# @app.route("/api/license//deactivate-device/", methods=["POST"]) -# @login_required -def deactivate_device(license_id, device_id): - """Deaktiviere ein registriertes Gerät""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob das Gerät zu dieser Lizenz gehört - cur.execute(""" - SELECT id FROM device_registrations - WHERE id = %s AND license_id = %s AND is_active = TRUE - """, (device_id, license_id)) - - if not cur.fetchone(): - return jsonify({'success': False, 'message': 'Gerät nicht gefunden oder bereits deaktiviert'}), 404 - - # Deaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = FALSE, - deactivated_at = CURRENT_TIMESTAMP, - deactivated_by = %s - WHERE id = %s - """, (session['username'], device_id)) - - conn.commit() - - # Audit Log - log_audit('DEVICE_DEACTIVATE', 'device', device_id, - old_values={'is_active': True}, - new_values={'is_active': False}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich deaktiviert'}) - - except Exception as e: - logging.error(f"Fehler beim Deaktivieren des Geräts: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Deaktivieren'}), 500 - -# @app.route("/api/licenses/bulk-delete", methods=["POST"]) -# @login_required -def bulk_delete_licenses(): - """Delete multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Get license info for audit log (nur Live-Daten) - cur.execute(""" - SELECT license_key - FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - license_keys = [row[0] for row in cur.fetchall()] - - # Delete all selected licenses (nur Live-Daten) - cur.execute(""" - DELETE FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_DELETE', 'licenses', None, - old_values={'license_keys': license_keys, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen gelöscht") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen gelöscht'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# ===================== RESOURCE POOL MANAGEMENT ===================== - -# @app.route('/resources') -# @login_required -def resources(): - """Resource Pool Hauptübersicht""" - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Testdaten angezeigt werden sollen (gleiche Logik wie bei Kunden) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - # Statistiken abrufen - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = %s - GROUP BY resource_type - """, (show_test,)) - - stats = {} - for row in cur.fetchall(): - stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - } - - # Letzte Aktivitäten (gefiltert nach Test/Live) - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rp.resource_type, - rp.resource_value, - rh.details - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - WHERE rp.is_test = %s - ORDER BY rh.action_at DESC - LIMIT 10 - """, (show_test,)) - recent_activities = cur.fetchall() - - # Ressourcen-Liste mit Pagination - page = request.args.get('page', 1, type=int) - per_page = 50 - offset = (page - 1) * per_page - - resource_type = request.args.get('type', '') - status_filter = request.args.get('status', '') - search = request.args.get('search', '') - - # Sortierung - sort_by = request.args.get('sort', 'id') - sort_order = request.args.get('order', 'desc') - - # Base Query - query = """ - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - rp.allocated_to_license, - l.license_key, - c.name as customer_name, - rp.status_changed_at, - rp.quarantine_reason, - rp.quarantine_until, - c.id as customer_id - FROM resource_pools rp - LEFT JOIN licenses l ON rp.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rp.is_test = %s - """ - params = [show_test] - - if resource_type: - query += " AND rp.resource_type = %s" - params.append(resource_type) - - if status_filter: - query += " AND rp.status = %s" - params.append(status_filter) - - if search: - query += " AND rp.resource_value ILIKE %s" - params.append(f'%{search}%') - - # Count total - count_query = f"SELECT COUNT(*) FROM ({query}) as cnt" - cur.execute(count_query, params) - total = cur.fetchone()[0] - total_pages = (total + per_page - 1) // per_page - - # Get paginated results with dynamic sorting - sort_column_map = { - 'id': 'rp.id', - 'type': 'rp.resource_type', - 'resource': 'rp.resource_value', - 'status': 'rp.status', - 'assigned': 'c.name', - 'changed': 'rp.status_changed_at' - } - - sort_column = sort_column_map.get(sort_by, 'rp.id') - sort_direction = 'ASC' if sort_order == 'asc' else 'DESC' - - query += f" ORDER BY {sort_column} {sort_direction} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - resources = cur.fetchall() - - cur.close() - conn.close() - - return render_template('resources.html', - stats=stats, - resources=resources, - recent_activities=recent_activities, - page=page, - total_pages=total_pages, - total=total, - resource_type=resource_type, - status_filter=status_filter, - search=search, - show_test=show_test, - sort_by=sort_by, - sort_order=sort_order, - datetime=datetime, - timedelta=timedelta) - -# @app.route('/resources/add', methods=['GET', 'POST']) -# @login_required -def add_resources(): - """Ressourcen zum Pool hinzufügen""" - # Hole show_test Parameter für die Anzeige - show_test = request.args.get('show_test', 'false').lower() == 'true' - - if request.method == 'POST': - resource_type = request.form.get('resource_type') - resources_text = request.form.get('resources_text', '') - is_test = request.form.get('is_test') == 'on' # Checkbox für Testdaten - - # Parse resources (one per line) - resources = [r.strip() for r in resources_text.split('\n') if r.strip()] - - if not resources: - flash('Keine Ressourcen angegeben', 'error') - return redirect(url_for('add_resources', show_test=show_test)) - - conn = get_connection() - cur = conn.cursor() - - added = 0 - duplicates = 0 - - for resource_value in resources: - try: - cur.execute(""" - INSERT INTO resource_pools (resource_type, resource_value, status_changed_by, is_test) - VALUES (%s, %s, %s, %s) - ON CONFLICT (resource_type, resource_value) DO NOTHING - """, (resource_type, resource_value, session['username'], is_test)) - - if cur.rowcount > 0: - added += 1 - # Get the inserted ID - cur.execute("SELECT id FROM resource_pools WHERE resource_type = %s AND resource_value = %s", - (resource_type, resource_value)) - resource_id = cur.fetchone()[0] - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'created', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - else: - duplicates += 1 - - except Exception as e: - app.logger.error(f"Error adding resource {resource_value}: {e}") - - conn.commit() - cur.close() - conn.close() - - log_audit('CREATE', 'resource_pool', None, - new_values={'type': resource_type, 'added': added, 'duplicates': duplicates, 'is_test': is_test}, - additional_info=f"{added} {'Test-' if is_test else ''}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen") - - flash(f'{added} {"Test-" if is_test else ""}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen', 'success') - return redirect(url_for('resources', show_test=show_test)) - - return render_template('add_resources.html', show_test=show_test) - -# @app.route('/resources/quarantine/', methods=['POST']) -# @login_required -def quarantine_resource(resource_id): - """Ressource in Quarantäne setzen""" - reason = request.form.get('reason', 'review') - until_date = request.form.get('until_date') - notes = request.form.get('notes', '') - - conn = get_connection() - cur = conn.cursor() - - # Get current resource info - cur.execute("SELECT resource_type, resource_value, status FROM resource_pools WHERE id = %s", (resource_id,)) - resource = cur.fetchone() - - if not resource: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - old_status = resource[2] - - # Update resource - cur.execute(""" - UPDATE resource_pools - SET status = 'quarantine', - quarantine_reason = %s, - quarantine_until = %s, - notes = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (reason, until_date if until_date else None, notes, session['username'], resource_id)) - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address, details) - VALUES (%s, 'quarantined', %s, %s, %s) - """, (resource_id, session['username'], get_client_ip(), - Json({'reason': reason, 'until': until_date, 'notes': notes, 'old_status': old_status}))) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource', resource_id, - old_values={'status': old_status}, - new_values={'status': 'quarantine', 'reason': reason}, - additional_info=f"Ressource {resource[0]}: {resource[1]} in Quarantäne") - - flash('Ressource in Quarantäne gesetzt', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -# @app.route('/resources/release', methods=['POST']) -# @login_required -def release_resources(): - """Ressourcen aus Quarantäne freigeben""" - resource_ids = request.form.getlist('resource_ids') - - if not resource_ids: - flash('Keine Ressourcen ausgewählt', 'error') - return redirect(url_for('resources')) - - conn = get_connection() - cur = conn.cursor() - - released = 0 - for resource_id in resource_ids: - cur.execute(""" - UPDATE resource_pools - SET status = 'available', - quarantine_reason = NULL, - quarantine_until = NULL, - allocated_to_license = NULL, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s AND status = 'quarantine' - """, (session['username'], resource_id)) - - if cur.rowcount > 0: - released += 1 - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'released', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource_pool', None, - new_values={'released': released}, - additional_info=f"{released} Ressourcen aus Quarantäne freigegeben") - - flash(f'{released} Ressourcen freigegeben', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -# @app.route('/api/resources/allocate', methods=['POST']) -# @login_required -def allocate_resources_api(): - """API für Ressourcen-Zuweisung bei Lizenzerstellung""" - data = request.json - license_id = data.get('license_id') - domain_count = data.get('domain_count', 1) - ipv4_count = data.get('ipv4_count', 1) - phone_count = data.get('phone_count', 1) - - conn = get_connection() - cur = conn.cursor() - - try: - allocated = {'domains': [], 'ipv4s': [], 'phones': []} - - # Allocate domains - if domain_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' - LIMIT %s FOR UPDATE - """, (domain_count,)) - domains = cur.fetchall() - - if len(domains) < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {len(domains)})") - - for domain_id, domain_value in domains: - # Update resource status - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], domain_id)) - - # Create assignment - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, domain_id, session['username'])) - - # Log history - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (domain_id, license_id, session['username'], get_client_ip())) - - allocated['domains'].append(domain_value) - - # Allocate IPv4s (similar logic) - if ipv4_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' - LIMIT %s FOR UPDATE - """, (ipv4_count,)) - ipv4s = cur.fetchall() - - if len(ipv4s) < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar") - - for ipv4_id, ipv4_value in ipv4s: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], ipv4_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, ipv4_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (ipv4_id, license_id, session['username'], get_client_ip())) - - allocated['ipv4s'].append(ipv4_value) - - # Allocate phones (similar logic) - if phone_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' - LIMIT %s FOR UPDATE - """, (phone_count,)) - phones = cur.fetchall() - - if len(phones) < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar") - - for phone_id, phone_value in phones: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], phone_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, phone_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (phone_id, license_id, session['username'], get_client_ip())) - - allocated['phones'].append(phone_value) - - # Update license resource counts - cur.execute(""" - UPDATE licenses - SET domain_count = %s, - ipv4_count = %s, - phone_count = %s - WHERE id = %s - """, (domain_count, ipv4_count, phone_count, license_id)) - - conn.commit() - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'allocated': allocated - }) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({ - 'success': False, - 'error': str(e) - }), 400 - -# @app.route('/api/resources/check-availability', methods=['GET']) -# @login_required -def check_resource_availability(): - """Prüft verfügbare Ressourcen""" - resource_type = request.args.get('type', '') - count = request.args.get('count', 10, type=int) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - conn = get_connection() - cur = conn.cursor() - - if resource_type: - # Spezifische Ressourcen für einen Typ - cur.execute(""" - SELECT id, resource_value - FROM resource_pools - WHERE status = 'available' - AND resource_type = %s - AND is_test = %s - ORDER BY resource_value - LIMIT %s - """, (resource_type, show_test, count)) - - resources = [] - for row in cur.fetchall(): - resources.append({ - 'id': row[0], - 'value': row[1] - }) - - cur.close() - conn.close() - - return jsonify({ - 'available': resources, - 'type': resource_type, - 'count': len(resources) - }) - else: - # Zusammenfassung aller Typen - cur.execute(""" - SELECT - resource_type, - COUNT(*) as available - FROM resource_pools - WHERE status = 'available' - AND is_test = %s - GROUP BY resource_type - """, (show_test,)) - - availability = {} - for row in cur.fetchall(): - availability[row[0]] = row[1] - - cur.close() - conn.close() - - return jsonify(availability) - -# @app.route('/api/global-search', methods=['GET']) -# @login_required -def global_search(): - """Global search API endpoint for searching customers and licenses""" - query = request.args.get('q', '').strip() - - if not query or len(query) < 2: - return jsonify({'customers': [], 'licenses': []}) - - conn = get_connection() - cur = conn.cursor() - - # Search pattern with wildcards - search_pattern = f'%{query}%' - - # Search customers - cur.execute(""" - SELECT id, name, email, company_name - FROM customers - WHERE (LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - OR LOWER(company_name) LIKE LOWER(%s)) - AND is_test = FALSE - ORDER BY name - LIMIT 5 - """, (search_pattern, search_pattern, search_pattern)) - - customers = [] - for row in cur.fetchall(): - customers.append({ - 'id': row[0], - 'name': row[1], - 'email': row[2], - 'company_name': row[3] - }) - - # Search licenses - cur.execute(""" - SELECT l.id, l.license_key, c.name as customer_name - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE LOWER(l.license_key) LIKE LOWER(%s) - AND l.is_test = FALSE - ORDER BY l.created_at DESC - LIMIT 5 - """, (search_pattern,)) - - licenses = [] - for row in cur.fetchall(): - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'customer_name': row[2] - }) - - cur.close() - conn.close() - - return jsonify({ - 'customers': customers, - 'licenses': licenses - }) - -# @app.route('/resources/history/') -# @login_required -def resource_history(resource_id): - """Zeigt die komplette Historie einer Ressource""" - conn = get_connection() - cur = conn.cursor() - - # Get complete resource info using named columns - cur.execute(""" - SELECT id, resource_type, resource_value, status, allocated_to_license, - status_changed_at, status_changed_by, quarantine_reason, - quarantine_until, created_at, notes - FROM resource_pools - WHERE id = %s - """, (resource_id,)) - row = cur.fetchone() - - if not row: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - # Create resource object with named attributes - resource = { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'allocated_to_license': row[4], - 'status_changed_at': row[5], - 'status_changed_by': row[6], - 'quarantine_reason': row[7], - 'quarantine_until': row[8], - 'created_at': row[9], - 'notes': row[10] - } - - # Get license info if allocated - license_info = None - if resource['allocated_to_license']: - cur.execute("SELECT license_key FROM licenses WHERE id = %s", - (resource['allocated_to_license'],)) - lic = cur.fetchone() - if lic: - license_info = {'license_key': lic[0]} - - # Get history with named columns - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rh.details, - rh.license_id, - rh.ip_address - FROM resource_history rh - WHERE rh.resource_id = %s - ORDER BY rh.action_at DESC - """, (resource_id,)) - - history = [] - for row in cur.fetchall(): - history.append({ - 'action': row[0], - 'action_by': row[1], - 'action_at': row[2], - 'details': row[3], - 'license_id': row[4], - 'ip_address': row[5] - }) - - cur.close() - conn.close() - - # Convert to object-like for template - class ResourceObj: - def __init__(self, data): - for key, value in data.items(): - setattr(self, key, value) - - resource_obj = ResourceObj(resource) - history_objs = [ResourceObj(h) for h in history] - - return render_template('resource_history.html', - resource=resource_obj, - license_info=license_info, - history=history_objs) - -# @app.route('/resources/metrics') -# @login_required -def resources_metrics(): - """Dashboard für Resource Metrics und Reports""" - conn = get_connection() - cur = conn.cursor() - - # Overall stats with fallback values - cur.execute(""" - SELECT - COUNT(DISTINCT resource_id) as total_resources, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(cost), 0) as total_cost, - COALESCE(SUM(revenue), 0) as total_revenue, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - """) - row = cur.fetchone() - - # Calculate ROI - roi = 0 - if row[2] > 0: # if total_cost > 0 - roi = row[3] / row[2] # revenue / cost - - stats = { - 'total_resources': row[0] or 0, - 'avg_performance': row[1] or 0, - 'total_cost': row[2] or 0, - 'total_revenue': row[3] or 0, - 'total_issues': row[4] or 0, - 'roi': roi - } - - # Performance by type - cur.execute(""" - SELECT - rp.resource_type, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COUNT(DISTINCT rp.id) as resource_count - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY rp.resource_type - ORDER BY rp.resource_type - """) - performance_by_type = cur.fetchall() - - # Utilization data - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) as total, - ROUND(COUNT(*) FILTER (WHERE status = 'allocated') * 100.0 / COUNT(*), 1) as allocated_percent - FROM resource_pools - GROUP BY resource_type - """) - utilization_rows = cur.fetchall() - utilization_data = [ - { - 'type': row[0].upper(), - 'allocated': row[1], - 'total': row[2], - 'allocated_percent': row[3] - } - for row in utilization_rows - ] - - # Top performing resources - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COALESCE(SUM(rm.revenue), 0) as total_revenue, - COALESCE(SUM(rm.cost), 1) as total_cost, - CASE - WHEN COALESCE(SUM(rm.cost), 0) = 0 THEN 0 - ELSE COALESCE(SUM(rm.revenue), 0) / COALESCE(SUM(rm.cost), 1) - END as roi - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rp.status != 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value - HAVING AVG(rm.performance_score) IS NOT NULL - ORDER BY avg_score DESC - LIMIT 10 - """) - top_rows = cur.fetchall() - top_performers = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'avg_score': row[3], - 'roi': row[6] - } - for row in top_rows - ] - - # Resources with issues - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - COALESCE(SUM(rm.issues_count), 0) as total_issues - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rm.issues_count > 0 OR rp.status = 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - HAVING SUM(rm.issues_count) > 0 - ORDER BY total_issues DESC - LIMIT 10 - """) - problem_rows = cur.fetchall() - problem_resources = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'total_issues': row[4] - } - for row in problem_rows - ] - - # Daily metrics for trend chart (last 30 days) - cur.execute(""" - SELECT - metric_date, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY metric_date - ORDER BY metric_date - """) - daily_rows = cur.fetchall() - daily_metrics = [ - { - 'date': row[0].strftime('%d.%m'), - 'performance': float(row[1]), - 'issues': int(row[2]) - } - for row in daily_rows - ] - - cur.close() - conn.close() - - return render_template('resource_metrics.html', - stats=stats, - performance_by_type=performance_by_type, - utilization_data=utilization_data, - top_performers=top_performers, - problem_resources=problem_resources, - daily_metrics=daily_metrics) - -# @app.route('/resources/report', methods=['GET']) -# @login_required -def resources_report(): - """Generiert Ressourcen-Reports oder zeigt Report-Formular""" - # Prüfe ob Download angefordert wurde - if request.args.get('download') == 'true': - report_type = request.args.get('type', 'usage') - format_type = request.args.get('format', 'excel') - date_from = request.args.get('from', (datetime.now(ZoneInfo("Europe/Berlin")) - timedelta(days=30)).strftime('%Y-%m-%d')) - date_to = request.args.get('to', datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y-%m-%d')) - - conn = get_connection() - cur = conn.cursor() - - if report_type == 'usage': - # Auslastungsreport - query = """ - SELECT - rp.resource_type, - rp.resource_value, - rp.status, - COUNT(DISTINCT rh.license_id) as unique_licenses, - COUNT(rh.id) as total_allocations, - MIN(rh.action_at) as first_used, - MAX(rh.action_at) as last_used - FROM resource_pools rp - LEFT JOIN resource_history rh ON rp.id = rh.resource_id - AND rh.action = 'allocated' - AND rh.action_at BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - ORDER BY rp.resource_type, total_allocations DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Status', 'Unique Lizenzen', 'Gesamt Zuweisungen', 'Erste Nutzung', 'Letzte Nutzung'] - - elif report_type == 'performance': - # Performance-Report - query = """ - SELECT - rp.resource_type, - rp.resource_value, - AVG(rm.performance_score) as avg_performance, - SUM(rm.usage_count) as total_usage, - SUM(rm.revenue) as total_revenue, - SUM(rm.cost) as total_cost, - SUM(rm.revenue - rm.cost) as profit, - SUM(rm.issues_count) as total_issues - FROM resource_pools rp - JOIN resource_metrics rm ON rp.id = rm.resource_id - WHERE rm.metric_date BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value - ORDER BY profit DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Durchschn. Performance', 'Gesamt Nutzung', 'Umsatz', 'Kosten', 'Gewinn', 'Issues'] - - elif report_type == 'compliance': - # Compliance-Report - query = """ - SELECT - rh.action_at, - rh.action, - rh.action_by, - rp.resource_type, - rp.resource_value, - l.license_key, - c.name as customer_name, - rh.ip_address - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - LEFT JOIN licenses l ON rh.license_id = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rh.action_at BETWEEN %s AND %s - ORDER BY rh.action_at DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Zeit', 'Aktion', 'Von', 'Typ', 'Ressource', 'Lizenz', 'Kunde', 'IP-Adresse'] - - else: # inventory report - # Inventar-Report - query = """ - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - GROUP BY resource_type - ORDER BY resource_type - """ - cur.execute(query) - columns = ['Typ', 'Verfügbar', 'Zugeteilt', 'Quarantäne', 'Gesamt'] - - # Convert to DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - cur.close() - conn.close() - - # Generate file - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f"resource_report_{report_type}_{timestamp}" - - if format_type == 'excel': - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Report', index=False) - - # Auto-adjust columns width - worksheet = writer.sheets['Report'] - for column in worksheet.columns: - max_length = 0 - column = [cell for cell in column] - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = (max_length + 2) - worksheet.column_dimensions[column[0].column_letter].width = adjusted_width - - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'excel', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx') - - else: # CSV - output = io.StringIO() - df.to_csv(output, index=False, sep=';', encoding='utf-8-sig') - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'csv', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv') - - # Wenn kein Download, zeige Report-Formular - return render_template('resource_report.html', - datetime=datetime, - timedelta=timedelta, - username=session.get('username')) - -if __name__ == "__main__": - app.run(host="0.0.0.0", port=5000) diff --git a/v2_adminpanel/app.py.old b/v2_adminpanel/app.py.old deleted file mode 100644 index 3849500..0000000 --- a/v2_adminpanel/app.py.old +++ /dev/null @@ -1,5021 +0,0 @@ -import os -import time -import json -import logging -import requests -from io import BytesIO -from datetime import datetime, timedelta -from zoneinfo import ZoneInfo -from pathlib import Path - -from flask import Flask, render_template, request, redirect, session, url_for, send_file, jsonify, flash -from flask_session import Session -from werkzeug.middleware.proxy_fix import ProxyFix -from apscheduler.schedulers.background import BackgroundScheduler -import pandas as pd -from psycopg2.extras import Json - -# Import our new modules -import config -from db import get_connection, get_db_connection, get_db_cursor, execute_query -from auth.decorators import login_required -from auth.password import hash_password, verify_password -from auth.two_factor import ( - generate_totp_secret, generate_qr_code, verify_totp, - generate_backup_codes, hash_backup_code, verify_backup_code -) -from auth.rate_limiting import ( - get_client_ip, check_ip_blocked, record_failed_attempt, - reset_login_attempts, get_login_attempts -) -from utils.audit import log_audit -from utils.license import generate_license_key, validate_license_key -from utils.backup import create_backup, restore_backup, get_or_create_encryption_key -from utils.export import ( - create_excel_export, format_datetime_for_export, - prepare_license_export_data, prepare_customer_export_data, - prepare_session_export_data, prepare_audit_export_data -) - -app = Flask(__name__) -# Load configuration from config module -app.config['SECRET_KEY'] = config.SECRET_KEY -app.config['SESSION_TYPE'] = config.SESSION_TYPE -app.config['JSON_AS_ASCII'] = config.JSON_AS_ASCII -app.config['JSONIFY_MIMETYPE'] = config.JSONIFY_MIMETYPE -app.config['PERMANENT_SESSION_LIFETIME'] = config.PERMANENT_SESSION_LIFETIME -app.config['SESSION_COOKIE_HTTPONLY'] = config.SESSION_COOKIE_HTTPONLY -app.config['SESSION_COOKIE_SECURE'] = config.SESSION_COOKIE_SECURE -app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE -app.config['SESSION_COOKIE_NAME'] = config.SESSION_COOKIE_NAME -app.config['SESSION_REFRESH_EACH_REQUEST'] = config.SESSION_REFRESH_EACH_REQUEST -Session(app) - -# ProxyFix für korrekte IP-Adressen hinter Nginx -app.wsgi_app = ProxyFix( - app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 -) - -# Configuration is now loaded from config module - -# Scheduler für automatische Backups -scheduler = BackgroundScheduler() -scheduler.start() - -# Logging konfigurieren -logging.basicConfig(level=logging.INFO) - - -# Login decorator -def login_required(f): - @wraps(f) - def decorated_function(*args, **kwargs): - if 'logged_in' not in session: - return redirect(url_for('login')) - - # Prüfe ob Session abgelaufen ist - if 'last_activity' in session: - last_activity = datetime.fromisoformat(session['last_activity']) - time_since_activity = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) - last_activity - - # Debug-Logging - app.logger.info(f"Session check for {session.get('username', 'unknown')}: " - f"Last activity: {last_activity}, " - f"Time since: {time_since_activity.total_seconds()} seconds") - - if time_since_activity > timedelta(minutes=5): - # Session abgelaufen - Logout - username = session.get('username', 'unbekannt') - app.logger.info(f"Session timeout for user {username} - auto logout") - # Audit-Log für automatischen Logout (vor session.clear()!) - try: - log_audit('AUTO_LOGOUT', 'session', additional_info={'reason': 'Session timeout (5 minutes)', 'username': username}) - except: - pass - session.clear() - flash('Ihre Sitzung ist abgelaufen. Bitte melden Sie sich erneut an.', 'warning') - return redirect(url_for('login')) - - # Aktivität NICHT automatisch aktualisieren - # Nur bei expliziten Benutzeraktionen (wird vom Heartbeat gemacht) - return f(*args, **kwargs) - return decorated_function - -# DB-Verbindung mit UTF-8 Encoding -def get_connection(): - conn = psycopg2.connect( - host=os.getenv("POSTGRES_HOST", "postgres"), - port=os.getenv("POSTGRES_PORT", "5432"), - dbname=os.getenv("POSTGRES_DB"), - user=os.getenv("POSTGRES_USER"), - password=os.getenv("POSTGRES_PASSWORD"), - options='-c client_encoding=UTF8' - ) - conn.set_client_encoding('UTF8') - return conn - -# User Authentication Helper Functions -def hash_password(password): - """Hash a password using bcrypt""" - return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') - -def verify_password(password, hashed): - """Verify a password against its hash""" - return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8')) - -def get_user_by_username(username): - """Get user from database by username""" - conn = get_connection() - cur = conn.cursor() - try: - cur.execute(""" - SELECT id, username, password_hash, email, totp_secret, totp_enabled, - backup_codes, last_password_change, failed_2fa_attempts - FROM users WHERE username = %s - """, (username,)) - user = cur.fetchone() - if user: - return { - 'id': user[0], - 'username': user[1], - 'password_hash': user[2], - 'email': user[3], - 'totp_secret': user[4], - 'totp_enabled': user[5], - 'backup_codes': user[6], - 'last_password_change': user[7], - 'failed_2fa_attempts': user[8] - } - return None - finally: - cur.close() - conn.close() - -def generate_totp_secret(): - """Generate a new TOTP secret""" - return pyotp.random_base32() - -def generate_qr_code(username, totp_secret): - """Generate QR code for TOTP setup""" - totp_uri = pyotp.totp.TOTP(totp_secret).provisioning_uri( - name=username, - issuer_name='V2 Admin Panel' - ) - - qr = qrcode.QRCode(version=1, box_size=10, border=5) - qr.add_data(totp_uri) - qr.make(fit=True) - - img = qr.make_image(fill_color="black", back_color="white") - buf = BytesIO() - img.save(buf, format='PNG') - buf.seek(0) - - return base64.b64encode(buf.getvalue()).decode() - -def verify_totp(totp_secret, token): - """Verify a TOTP token""" - totp = pyotp.TOTP(totp_secret) - return totp.verify(token, valid_window=1) - -def generate_backup_codes(count=8): - """Generate backup codes for 2FA recovery""" - codes = [] - for _ in range(count): - code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8)) - codes.append(code) - return codes - -def hash_backup_code(code): - """Hash a backup code for storage""" - return hashlib.sha256(code.encode()).hexdigest() - -def verify_backup_code(code, hashed_codes): - """Verify a backup code against stored hashes""" - code_hash = hashlib.sha256(code.encode()).hexdigest() - return code_hash in hashed_codes - -# Audit-Log-Funktion -def log_audit(action, entity_type, entity_id=None, old_values=None, new_values=None, additional_info=None): - """Protokolliert Änderungen im Audit-Log""" - conn = get_connection() - cur = conn.cursor() - - try: - username = session.get('username', 'system') - ip_address = get_client_ip() if request else None - user_agent = request.headers.get('User-Agent') if request else None - - # Debug logging - app.logger.info(f"Audit log - IP address captured: {ip_address}, Action: {action}, User: {username}") - - # Konvertiere Dictionaries zu JSONB - old_json = Json(old_values) if old_values else None - new_json = Json(new_values) if new_values else None - - cur.execute(""" - INSERT INTO audit_log - (username, action, entity_type, entity_id, old_values, new_values, - ip_address, user_agent, additional_info) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) - """, (username, action, entity_type, entity_id, old_json, new_json, - ip_address, user_agent, additional_info)) - - conn.commit() - except Exception as e: - print(f"Audit log error: {e}") - conn.rollback() - finally: - cur.close() - conn.close() - -# Verschlüsselungs-Funktionen -def get_or_create_encryption_key(): - """Holt oder erstellt einen Verschlüsselungsschlüssel""" - key_file = BACKUP_DIR / ".backup_key" - - # Versuche Key aus Umgebungsvariable zu lesen - env_key = os.getenv("BACKUP_ENCRYPTION_KEY") - if env_key: - try: - # Validiere den Key - Fernet(env_key.encode()) - return env_key.encode() - except: - pass - - # Wenn kein gültiger Key in ENV, prüfe Datei - if key_file.exists(): - return key_file.read_bytes() - - # Erstelle neuen Key - key = Fernet.generate_key() - key_file.write_bytes(key) - logging.info("Neuer Backup-Verschlüsselungsschlüssel erstellt") - return key - -# Backup-Funktionen -def create_backup(backup_type="manual", created_by=None): - """Erstellt ein verschlüsseltes Backup der Datenbank""" - start_time = time.time() - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S") - filename = f"backup_v2docker_{timestamp}_encrypted.sql.gz.enc" - filepath = BACKUP_DIR / filename - - conn = get_connection() - cur = conn.cursor() - - # Backup-Eintrag erstellen - cur.execute(""" - INSERT INTO backup_history - (filename, filepath, backup_type, status, created_by, is_encrypted) - VALUES (%s, %s, %s, %s, %s, %s) - RETURNING id - """, (filename, str(filepath), backup_type, 'in_progress', - created_by or 'system', True)) - backup_id = cur.fetchone()[0] - conn.commit() - - try: - # PostgreSQL Dump erstellen - dump_command = [ - 'pg_dump', - '-h', os.getenv("POSTGRES_HOST", "postgres"), - '-p', os.getenv("POSTGRES_PORT", "5432"), - '-U', os.getenv("POSTGRES_USER"), - '-d', os.getenv("POSTGRES_DB"), - '--no-password', - '--verbose' - ] - - # PGPASSWORD setzen - env = os.environ.copy() - env['PGPASSWORD'] = os.getenv("POSTGRES_PASSWORD") - - # Dump ausführen - result = subprocess.run(dump_command, capture_output=True, text=True, env=env) - - if result.returncode != 0: - raise Exception(f"pg_dump failed: {result.stderr}") - - dump_data = result.stdout.encode('utf-8') - - # Komprimieren - compressed_data = gzip.compress(dump_data) - - # Verschlüsseln - key = get_or_create_encryption_key() - f = Fernet(key) - encrypted_data = f.encrypt(compressed_data) - - # Speichern - filepath.write_bytes(encrypted_data) - - # Statistiken sammeln - cur.execute("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public'") - tables_count = cur.fetchone()[0] - - cur.execute(""" - SELECT SUM(n_live_tup) - FROM pg_stat_user_tables - """) - records_count = cur.fetchone()[0] or 0 - - duration = time.time() - start_time - filesize = filepath.stat().st_size - - # Backup-Eintrag aktualisieren - cur.execute(""" - UPDATE backup_history - SET status = %s, filesize = %s, tables_count = %s, - records_count = %s, duration_seconds = %s - WHERE id = %s - """, ('success', filesize, tables_count, records_count, duration, backup_id)) - - conn.commit() - - # Audit-Log - log_audit('BACKUP', 'database', backup_id, - additional_info=f"Backup erstellt: {filename} ({filesize} bytes)") - - # E-Mail-Benachrichtigung (wenn konfiguriert) - send_backup_notification(True, filename, filesize, duration) - - logging.info(f"Backup erfolgreich erstellt: {filename}") - return True, filename - - except Exception as e: - # Fehler protokollieren - cur.execute(""" - UPDATE backup_history - SET status = %s, error_message = %s, duration_seconds = %s - WHERE id = %s - """, ('failed', str(e), time.time() - start_time, backup_id)) - conn.commit() - - logging.error(f"Backup fehlgeschlagen: {e}") - send_backup_notification(False, filename, error=str(e)) - - return False, str(e) - - finally: - cur.close() - conn.close() - -def restore_backup(backup_id, encryption_key=None): - """Stellt ein Backup wieder her""" - conn = get_connection() - cur = conn.cursor() - - try: - # Backup-Info abrufen - cur.execute(""" - SELECT filename, filepath, is_encrypted - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - if not backup_info: - raise Exception("Backup nicht gefunden") - - filename, filepath, is_encrypted = backup_info - filepath = Path(filepath) - - if not filepath.exists(): - raise Exception("Backup-Datei nicht gefunden") - - # Datei lesen - encrypted_data = filepath.read_bytes() - - # Entschlüsseln - if is_encrypted: - key = encryption_key.encode() if encryption_key else get_or_create_encryption_key() - try: - f = Fernet(key) - compressed_data = f.decrypt(encrypted_data) - except: - raise Exception("Entschlüsselung fehlgeschlagen. Falsches Passwort?") - else: - compressed_data = encrypted_data - - # Dekomprimieren - dump_data = gzip.decompress(compressed_data) - sql_commands = dump_data.decode('utf-8') - - # Bestehende Verbindungen schließen - cur.close() - conn.close() - - # Datenbank wiederherstellen - restore_command = [ - 'psql', - '-h', os.getenv("POSTGRES_HOST", "postgres"), - '-p', os.getenv("POSTGRES_PORT", "5432"), - '-U', os.getenv("POSTGRES_USER"), - '-d', os.getenv("POSTGRES_DB"), - '--no-password' - ] - - env = os.environ.copy() - env['PGPASSWORD'] = os.getenv("POSTGRES_PASSWORD") - - result = subprocess.run(restore_command, input=sql_commands, - capture_output=True, text=True, env=env) - - if result.returncode != 0: - raise Exception(f"Wiederherstellung fehlgeschlagen: {result.stderr}") - - # Audit-Log (neue Verbindung) - log_audit('RESTORE', 'database', backup_id, - additional_info=f"Backup wiederhergestellt: {filename}") - - return True, "Backup erfolgreich wiederhergestellt" - - except Exception as e: - logging.error(f"Wiederherstellung fehlgeschlagen: {e}") - return False, str(e) - -def send_backup_notification(success, filename, filesize=None, duration=None, error=None): - """Sendet E-Mail-Benachrichtigung (wenn konfiguriert)""" - if not os.getenv("EMAIL_ENABLED", "false").lower() == "true": - return - - # E-Mail-Funktion vorbereitet aber deaktiviert - # TODO: Implementieren wenn E-Mail-Server konfiguriert ist - logging.info(f"E-Mail-Benachrichtigung vorbereitet: Backup {'erfolgreich' if success else 'fehlgeschlagen'}") - -# Scheduled Backup Job -def scheduled_backup(): - """Führt ein geplantes Backup aus""" - logging.info("Starte geplantes Backup...") - create_backup(backup_type="scheduled", created_by="scheduler") - -# Scheduler konfigurieren - täglich um 3:00 Uhr -scheduler.add_job( - scheduled_backup, - 'cron', - hour=3, - minute=0, - id='daily_backup', - replace_existing=True -) - -# Rate-Limiting Funktionen -def get_client_ip(): - """Ermittelt die echte IP-Adresse des Clients""" - # Debug logging - app.logger.info(f"Headers - X-Real-IP: {request.headers.get('X-Real-IP')}, X-Forwarded-For: {request.headers.get('X-Forwarded-For')}, Remote-Addr: {request.remote_addr}") - - # Try X-Real-IP first (set by nginx) - if request.headers.get('X-Real-IP'): - return request.headers.get('X-Real-IP') - # Then X-Forwarded-For - elif request.headers.get('X-Forwarded-For'): - # X-Forwarded-For can contain multiple IPs, take the first one - return request.headers.get('X-Forwarded-For').split(',')[0].strip() - # Fallback to remote_addr - else: - return request.remote_addr - -def check_ip_blocked(ip_address): - """Prüft ob eine IP-Adresse gesperrt ist""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT blocked_until FROM login_attempts - WHERE ip_address = %s AND blocked_until IS NOT NULL - """, (ip_address,)) - - result = cur.fetchone() - cur.close() - conn.close() - - if result and result[0]: - if result[0] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None): - return True, result[0] - return False, None - -def record_failed_attempt(ip_address, username): - """Zeichnet einen fehlgeschlagenen Login-Versuch auf""" - conn = get_connection() - cur = conn.cursor() - - # Random Fehlermeldung - error_message = random.choice(FAIL_MESSAGES) - - try: - # Prüfen ob IP bereits existiert - cur.execute(""" - SELECT attempt_count FROM login_attempts - WHERE ip_address = %s - """, (ip_address,)) - - result = cur.fetchone() - - if result: - # Update bestehenden Eintrag - new_count = result[0] + 1 - blocked_until = None - - if new_count >= MAX_LOGIN_ATTEMPTS: - blocked_until = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) + timedelta(hours=BLOCK_DURATION_HOURS) - # E-Mail-Benachrichtigung (wenn aktiviert) - if os.getenv("EMAIL_ENABLED", "false").lower() == "true": - send_security_alert_email(ip_address, username, new_count) - - cur.execute(""" - UPDATE login_attempts - SET attempt_count = %s, - last_attempt = CURRENT_TIMESTAMP, - blocked_until = %s, - last_username_tried = %s, - last_error_message = %s - WHERE ip_address = %s - """, (new_count, blocked_until, username, error_message, ip_address)) - else: - # Neuen Eintrag erstellen - cur.execute(""" - INSERT INTO login_attempts - (ip_address, attempt_count, last_username_tried, last_error_message) - VALUES (%s, 1, %s, %s) - """, (ip_address, username, error_message)) - - conn.commit() - - # Audit-Log - log_audit('LOGIN_FAILED', 'user', - additional_info=f"IP: {ip_address}, User: {username}, Message: {error_message}") - - except Exception as e: - print(f"Rate limiting error: {e}") - conn.rollback() - finally: - cur.close() - conn.close() - - return error_message - -def reset_login_attempts(ip_address): - """Setzt die Login-Versuche für eine IP zurück""" - conn = get_connection() - cur = conn.cursor() - - try: - cur.execute(""" - DELETE FROM login_attempts - WHERE ip_address = %s - """, (ip_address,)) - conn.commit() - except Exception as e: - print(f"Reset attempts error: {e}") - conn.rollback() - finally: - cur.close() - conn.close() - -def get_login_attempts(ip_address): - """Gibt die Anzahl der Login-Versuche für eine IP zurück""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT attempt_count FROM login_attempts - WHERE ip_address = %s - """, (ip_address,)) - - result = cur.fetchone() - cur.close() - conn.close() - - return result[0] if result else 0 - -def send_security_alert_email(ip_address, username, attempt_count): - """Sendet eine Sicherheitswarnung per E-Mail""" - subject = f"⚠️ SICHERHEITSWARNUNG: {attempt_count} fehlgeschlagene Login-Versuche" - body = f""" - WARNUNG: Mehrere fehlgeschlagene Login-Versuche erkannt! - - IP-Adresse: {ip_address} - Versuchter Benutzername: {username} - Anzahl Versuche: {attempt_count} - Zeit: {datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y-%m-%d %H:%M:%S')} - - Die IP-Adresse wurde für 24 Stunden gesperrt. - - Dies ist eine automatische Nachricht vom v2-Docker Admin Panel. - """ - - # TODO: E-Mail-Versand implementieren wenn SMTP konfiguriert - logging.warning(f"Sicherheitswarnung: {attempt_count} fehlgeschlagene Versuche von IP {ip_address}") - print(f"E-Mail würde gesendet: {subject}") - -def verify_recaptcha(response): - """Verifiziert die reCAPTCHA v2 Response mit Google""" - secret_key = os.getenv('RECAPTCHA_SECRET_KEY') - - # Wenn kein Secret Key konfiguriert ist, CAPTCHA als bestanden werten (für PoC) - if not secret_key: - logging.warning("RECAPTCHA_SECRET_KEY nicht konfiguriert - CAPTCHA wird übersprungen") - return True - - # Verifizierung bei Google - try: - verify_url = 'https://www.google.com/recaptcha/api/siteverify' - data = { - 'secret': secret_key, - 'response': response - } - - # Timeout für Request setzen - r = requests.post(verify_url, data=data, timeout=5) - result = r.json() - - # Log für Debugging - if not result.get('success'): - logging.warning(f"reCAPTCHA Validierung fehlgeschlagen: {result.get('error-codes', [])}") - - return result.get('success', False) - - except requests.exceptions.RequestException as e: - logging.error(f"reCAPTCHA Verifizierung fehlgeschlagen: {str(e)}") - # Bei Netzwerkfehlern CAPTCHA als bestanden werten - return True - except Exception as e: - logging.error(f"Unerwarteter Fehler bei reCAPTCHA: {str(e)}") - return False - -def generate_license_key(license_type='full'): - """ - Generiert einen Lizenzschlüssel im Format: AF-F-YYYYMM-XXXX-YYYY-ZZZZ - - AF = Account Factory (Produktkennung) - F/T = F für Fullversion, T für Testversion - YYYY = Jahr - MM = Monat - XXXX-YYYY-ZZZZ = Zufällige alphanumerische Zeichen - """ - # Erlaubte Zeichen (ohne verwirrende wie 0/O, 1/I/l) - chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' - - # Datum-Teil - now = datetime.now(ZoneInfo("Europe/Berlin")) - date_part = now.strftime('%Y%m') - type_char = 'F' if license_type == 'full' else 'T' - - # Zufällige Teile generieren (3 Blöcke à 4 Zeichen) - parts = [] - for _ in range(3): - part = ''.join(secrets.choice(chars) for _ in range(4)) - parts.append(part) - - # Key zusammensetzen - key = f"AF-{type_char}-{date_part}-{parts[0]}-{parts[1]}-{parts[2]}" - - return key - -def validate_license_key(key): - """ - Validiert das License Key Format - Erwartet: AF-F-YYYYMM-XXXX-YYYY-ZZZZ oder AF-T-YYYYMM-XXXX-YYYY-ZZZZ - """ - if not key: - return False - - # Pattern für das neue Format - # AF- (fest) + F oder T + - + 6 Ziffern (YYYYMM) + - + 4 Zeichen + - + 4 Zeichen + - + 4 Zeichen - pattern = r'^AF-[FT]-\d{6}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$' - - # Großbuchstaben für Vergleich - return bool(re.match(pattern, key.upper())) - -@app.route("/login", methods=["GET", "POST"]) -def login(): - # Timing-Attack Schutz - Start Zeit merken - start_time = time.time() - - # IP-Adresse ermitteln - ip_address = get_client_ip() - - # Prüfen ob IP gesperrt ist - is_blocked, blocked_until = check_ip_blocked(ip_address) - if is_blocked: - time_remaining = (blocked_until - datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None)).total_seconds() / 3600 - error_msg = f"IP GESPERRT! Noch {time_remaining:.1f} Stunden warten." - return render_template("login.html", error=error_msg, error_type="blocked") - - # Anzahl bisheriger Versuche - attempt_count = get_login_attempts(ip_address) - - if request.method == "POST": - username = request.form.get("username") - password = request.form.get("password") - captcha_response = request.form.get("g-recaptcha-response") - - # CAPTCHA-Prüfung nur wenn Keys konfiguriert sind - recaptcha_site_key = os.getenv('RECAPTCHA_SITE_KEY') - if attempt_count >= CAPTCHA_AFTER_ATTEMPTS and recaptcha_site_key: - if not captcha_response: - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA ERFORDERLICH!", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # CAPTCHA validieren - if not verify_recaptcha(captcha_response): - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA UNGÜLTIG! Bitte erneut versuchen.", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # Check user in database first, fallback to env vars - user = get_user_by_username(username) - login_success = False - needs_2fa = False - - if user: - # Database user authentication - if verify_password(password, user['password_hash']): - login_success = True - needs_2fa = user['totp_enabled'] - else: - # Fallback to environment variables for backward compatibility - admin1_user = os.getenv("ADMIN1_USERNAME") - admin1_pass = os.getenv("ADMIN1_PASSWORD") - admin2_user = os.getenv("ADMIN2_USERNAME") - admin2_pass = os.getenv("ADMIN2_PASSWORD") - - if ((username == admin1_user and password == admin1_pass) or - (username == admin2_user and password == admin2_pass)): - login_success = True - - # Timing-Attack Schutz - Mindestens 1 Sekunde warten - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - - if login_success: - # Erfolgreicher Login - if needs_2fa: - # Store temporary session for 2FA verification - session['temp_username'] = username - session['temp_user_id'] = user['id'] - session['awaiting_2fa'] = True - return redirect(url_for('verify_2fa')) - else: - # Complete login without 2FA - session.permanent = True # Aktiviert das Timeout - session['logged_in'] = True - session['username'] = username - session['user_id'] = user['id'] if user else None - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - reset_login_attempts(ip_address) - log_audit('LOGIN_SUCCESS', 'user', - additional_info=f"Erfolgreiche Anmeldung von IP: {ip_address}") - return redirect(url_for('dashboard')) - else: - # Fehlgeschlagener Login - error_message = record_failed_attempt(ip_address, username) - new_attempt_count = get_login_attempts(ip_address) - - # Prüfen ob jetzt gesperrt - is_now_blocked, _ = check_ip_blocked(ip_address) - if is_now_blocked: - log_audit('LOGIN_BLOCKED', 'security', - additional_info=f"IP {ip_address} wurde nach {MAX_LOGIN_ATTEMPTS} Versuchen gesperrt") - - return render_template("login.html", - error=error_message, - show_captcha=(new_attempt_count >= CAPTCHA_AFTER_ATTEMPTS and os.getenv('RECAPTCHA_SITE_KEY')), - error_type="failed", - attempts_left=max(0, MAX_LOGIN_ATTEMPTS - new_attempt_count), - recaptcha_site_key=os.getenv('RECAPTCHA_SITE_KEY')) - - # GET Request - return render_template("login.html", - show_captcha=(attempt_count >= CAPTCHA_AFTER_ATTEMPTS and os.getenv('RECAPTCHA_SITE_KEY')), - attempts_left=max(0, MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=os.getenv('RECAPTCHA_SITE_KEY')) - -@app.route("/logout") -def logout(): - username = session.get('username', 'unknown') - log_audit('LOGOUT', 'user', additional_info=f"Abmeldung") - session.pop('logged_in', None) - session.pop('username', None) - session.pop('user_id', None) - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - return redirect(url_for('login')) - -@app.route("/verify-2fa", methods=["GET", "POST"]) -def verify_2fa(): - if not session.get('awaiting_2fa'): - return redirect(url_for('login')) - - if request.method == "POST": - token = request.form.get('token', '').replace(' ', '') - username = session.get('temp_username') - user_id = session.get('temp_user_id') - - if not username or not user_id: - flash('Session expired. Please login again.', 'error') - return redirect(url_for('login')) - - user = get_user_by_username(username) - if not user: - flash('User not found.', 'error') - return redirect(url_for('login')) - - # Check if it's a backup code - if len(token) == 8 and token.isupper(): - # Try backup code - backup_codes = json.loads(user['backup_codes']) if user['backup_codes'] else [] - if verify_backup_code(token, backup_codes): - # Remove used backup code - code_hash = hash_backup_code(token) - backup_codes.remove(code_hash) - - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET backup_codes = %s WHERE id = %s", - (json.dumps(backup_codes), user_id)) - conn.commit() - cur.close() - conn.close() - - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - flash('Login successful using backup code. Please generate new backup codes.', 'warning') - log_audit('LOGIN_2FA_BACKUP', 'user', additional_info=f"2FA login with backup code") - return redirect(url_for('dashboard')) - else: - # Try TOTP token - if verify_totp(user['totp_secret'], token): - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - log_audit('LOGIN_2FA_SUCCESS', 'user', additional_info=f"2FA login successful") - return redirect(url_for('dashboard')) - - # Failed verification - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET failed_2fa_attempts = failed_2fa_attempts + 1, last_failed_2fa = %s WHERE id = %s", - (datetime.now(), user_id)) - conn.commit() - cur.close() - conn.close() - - flash('Invalid authentication code. Please try again.', 'error') - log_audit('LOGIN_2FA_FAILED', 'user', additional_info=f"Failed 2FA attempt") - - return render_template('verify_2fa.html') - -@app.route("/profile") -@login_required -def profile(): - user = get_user_by_username(session['username']) - if not user: - # For environment-based users, redirect with message - flash('Bitte führen Sie das Migrations-Script aus, um Passwort-Änderung und 2FA zu aktivieren.', 'info') - return redirect(url_for('dashboard')) - return render_template('profile.html', user=user) - -@app.route("/profile/change-password", methods=["POST"]) -@login_required -def change_password(): - current_password = request.form.get('current_password') - new_password = request.form.get('new_password') - confirm_password = request.form.get('confirm_password') - - user = get_user_by_username(session['username']) - - # Verify current password - if not verify_password(current_password, user['password_hash']): - flash('Current password is incorrect.', 'error') - return redirect(url_for('profile')) - - # Check new password - if new_password != confirm_password: - flash('New passwords do not match.', 'error') - return redirect(url_for('profile')) - - if len(new_password) < 8: - flash('Password must be at least 8 characters long.', 'error') - return redirect(url_for('profile')) - - # Update password - new_hash = hash_password(new_password) - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET password_hash = %s, last_password_change = %s WHERE id = %s", - (new_hash, datetime.now(), user['id'])) - conn.commit() - cur.close() - conn.close() - - log_audit('PASSWORD_CHANGE', 'user', entity_id=user['id'], - additional_info="Password changed successfully") - flash('Password changed successfully.', 'success') - return redirect(url_for('profile')) - -@app.route("/profile/setup-2fa") -@login_required -def setup_2fa(): - user = get_user_by_username(session['username']) - - if user['totp_enabled']: - flash('2FA is already enabled for your account.', 'info') - return redirect(url_for('profile')) - - # Generate new TOTP secret - totp_secret = generate_totp_secret() - session['temp_totp_secret'] = totp_secret - - # Generate QR code - qr_code = generate_qr_code(user['username'], totp_secret) - - return render_template('setup_2fa.html', - totp_secret=totp_secret, - qr_code=qr_code) - -@app.route("/profile/enable-2fa", methods=["POST"]) -@login_required -def enable_2fa(): - token = request.form.get('token', '').replace(' ', '') - totp_secret = session.get('temp_totp_secret') - - if not totp_secret: - flash('2FA setup session expired. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Verify the token - if not verify_totp(totp_secret, token): - flash('Invalid authentication code. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Generate backup codes - backup_codes = generate_backup_codes() - hashed_codes = [hash_backup_code(code) for code in backup_codes] - - # Enable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_secret = %s, totp_enabled = TRUE, backup_codes = %s - WHERE username = %s - """, (totp_secret, json.dumps(hashed_codes), session['username'])) - conn.commit() - cur.close() - conn.close() - - session.pop('temp_totp_secret', None) - - log_audit('2FA_ENABLED', 'user', additional_info="2FA enabled successfully") - - # Show backup codes - return render_template('backup_codes.html', backup_codes=backup_codes) - -@app.route("/profile/disable-2fa", methods=["POST"]) -@login_required -def disable_2fa(): - password = request.form.get('password') - user = get_user_by_username(session['username']) - - # Verify password - if not verify_password(password, user['password_hash']): - flash('Incorrect password.', 'error') - return redirect(url_for('profile')) - - # Disable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_enabled = FALSE, totp_secret = NULL, backup_codes = NULL - WHERE username = %s - """, (session['username'],)) - conn.commit() - cur.close() - conn.close() - - log_audit('2FA_DISABLED', 'user', additional_info="2FA disabled") - flash('2FA has been disabled for your account.', 'success') - return redirect(url_for('profile')) - -@app.route("/heartbeat", methods=['POST']) -@login_required -def heartbeat(): - """Endpoint für Session Keep-Alive - aktualisiert last_activity""" - # Aktualisiere last_activity nur wenn explizit angefordert - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # Force session save - session.modified = True - - return jsonify({ - 'status': 'ok', - 'last_activity': session['last_activity'], - 'username': session.get('username') - }) - -@app.route("/api/generate-license-key", methods=['POST']) -@login_required -def api_generate_key(): - """API Endpoint zur Generierung eines neuen Lizenzschlüssels""" - try: - # Lizenztyp aus Request holen (default: full) - data = request.get_json() or {} - license_type = data.get('type', 'full') - - # Key generieren - key = generate_license_key(license_type) - - # Prüfen ob Key bereits existiert (sehr unwahrscheinlich aber sicher ist sicher) - conn = get_connection() - cur = conn.cursor() - - # Wiederhole bis eindeutiger Key gefunden - attempts = 0 - while attempts < 10: # Max 10 Versuche - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (key,)) - if not cur.fetchone(): - break # Key ist eindeutig - key = generate_license_key(license_type) - attempts += 1 - - cur.close() - conn.close() - - # Log für Audit - log_audit('GENERATE_KEY', 'license', - additional_info={'type': license_type, 'key': key}) - - return jsonify({ - 'success': True, - 'key': key, - 'type': license_type - }) - - except Exception as e: - logging.error(f"Fehler bei Key-Generierung: {str(e)}") - return jsonify({ - 'success': False, - 'error': 'Fehler bei der Key-Generierung' - }), 500 - -@app.route("/api/customers", methods=['GET']) -@login_required -def api_customers(): - """API Endpoint für die Kundensuche mit Select2""" - try: - # Suchparameter - search = request.args.get('q', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - customer_id = request.args.get('id', type=int) - - conn = get_connection() - cur = conn.cursor() - - # Einzelnen Kunden per ID abrufen - if customer_id: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.id = %s - GROUP BY c.id, c.name, c.email - """, (customer_id,)) - - customer = cur.fetchone() - results = [] - if customer: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} ({customer[2]})", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - cur.close() - conn.close() - - return jsonify({ - 'results': results, - 'pagination': {'more': False} - }) - - # SQL Query mit optionaler Suche - elif search: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE LOWER(c.name) LIKE LOWER(%s) - OR LOWER(c.email) LIKE LOWER(%s) - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (f'%{search}%', f'%{search}%', per_page, (page - 1) * per_page)) - else: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (per_page, (page - 1) * per_page)) - - customers = cur.fetchall() - - # Format für Select2 - results = [] - for customer in customers: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} - {customer[2]} ({customer[3]} Lizenzen)", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - # Gesamtanzahl für Pagination - if search: - cur.execute(""" - SELECT COUNT(*) FROM customers - WHERE LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - """, (f'%{search}%', f'%{search}%')) - else: - cur.execute("SELECT COUNT(*) FROM customers") - - total_count = cur.fetchone()[0] - - cur.close() - conn.close() - - # Select2 Response Format - return jsonify({ - 'results': results, - 'pagination': { - 'more': (page * per_page) < total_count - } - }) - - except Exception as e: - logging.error(f"Fehler bei Kundensuche: {str(e)}") - return jsonify({ - 'results': [], - 'error': 'Fehler bei der Kundensuche' - }), 500 - -@app.route("/") -@login_required -def dashboard(): - conn = get_connection() - cur = conn.cursor() - - # Statistiken abrufen - # Gesamtanzahl Kunden (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = FALSE") - total_customers = cur.fetchone()[0] - - # Gesamtanzahl Lizenzen (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = FALSE") - total_licenses = cur.fetchone()[0] - - # Aktive Lizenzen (nicht abgelaufen und is_active = true, ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE AND is_active = TRUE AND is_test = FALSE - """) - active_licenses = cur.fetchone()[0] - - # Aktive Sessions - cur.execute("SELECT COUNT(*) FROM sessions WHERE is_active = TRUE") - active_sessions_count = cur.fetchone()[0] - - # Abgelaufene Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until < CURRENT_DATE AND is_test = FALSE - """) - expired_licenses = cur.fetchone()[0] - - # Deaktivierte Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE is_active = FALSE AND is_test = FALSE - """) - inactive_licenses = cur.fetchone()[0] - - # Lizenzen die in den nächsten 30 Tagen ablaufen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE - AND valid_until < CURRENT_DATE + INTERVAL '30 days' - AND is_active = TRUE - AND is_test = FALSE - """) - expiring_soon = cur.fetchone()[0] - - # Testlizenzen vs Vollversionen (ohne Testdaten) - cur.execute(""" - SELECT license_type, COUNT(*) - FROM licenses - WHERE is_test = FALSE - GROUP BY license_type - """) - license_types = dict(cur.fetchall()) - - # Anzahl Testdaten - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = TRUE") - test_data_count = cur.fetchone()[0] - - # Anzahl Test-Kunden - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = TRUE") - test_customers_count = cur.fetchone()[0] - - # Anzahl Test-Ressourcen - cur.execute("SELECT COUNT(*) FROM resource_pools WHERE is_test = TRUE") - test_resources_count = cur.fetchone()[0] - - # Letzte 5 erstellten Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.is_test = FALSE - ORDER BY l.id DESC - LIMIT 5 - """) - recent_licenses = cur.fetchall() - - # Bald ablaufende Lizenzen (nächste 30 Tage, ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - l.valid_until - CURRENT_DATE as days_left - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.valid_until >= CURRENT_DATE - AND l.valid_until < CURRENT_DATE + INTERVAL '30 days' - AND l.is_active = TRUE - AND l.is_test = FALSE - ORDER BY l.valid_until - LIMIT 10 - """) - expiring_licenses = cur.fetchall() - - # Letztes Backup - cur.execute(""" - SELECT created_at, filesize, duration_seconds, backup_type, status - FROM backup_history - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup_info = cur.fetchone() - - # Sicherheitsstatistiken - # Gesperrte IPs - cur.execute(""" - SELECT COUNT(*) FROM login_attempts - WHERE blocked_until IS NOT NULL AND blocked_until > CURRENT_TIMESTAMP - """) - blocked_ips_count = cur.fetchone()[0] - - # Fehlversuche heute - cur.execute(""" - SELECT COALESCE(SUM(attempt_count), 0) FROM login_attempts - WHERE last_attempt::date = CURRENT_DATE - """) - failed_attempts_today = cur.fetchone()[0] - - # Letzte 5 Sicherheitsereignisse - cur.execute(""" - SELECT - la.ip_address, - la.attempt_count, - la.last_attempt, - la.blocked_until, - la.last_username_tried, - la.last_error_message - FROM login_attempts la - ORDER BY la.last_attempt DESC - LIMIT 5 - """) - recent_security_events = [] - for event in cur.fetchall(): - recent_security_events.append({ - 'ip_address': event[0], - 'attempt_count': event[1], - 'last_attempt': event[2].strftime('%d.%m %H:%M'), - 'blocked_until': event[3].strftime('%d.%m %H:%M') if event[3] and event[3] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) else None, - 'username_tried': event[4], - 'error_message': event[5] - }) - - # Sicherheitslevel berechnen - if blocked_ips_count > 5 or failed_attempts_today > 50: - security_level = 'danger' - security_level_text = 'KRITISCH' - elif blocked_ips_count > 2 or failed_attempts_today > 20: - security_level = 'warning' - security_level_text = 'ERHÖHT' - else: - security_level = 'success' - security_level_text = 'NORMAL' - - # Resource Pool Statistiken (nur Live-Daten, keine Testdaten) - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = FALSE - GROUP BY resource_type - """) - - resource_stats = {} - resource_warning = None - - for row in cur.fetchall(): - available_percent = round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - resource_stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': available_percent, - 'warning_level': 'danger' if row[1] < 50 else 'warning' if row[1] < 100 else 'success' - } - - # Warnung bei niedrigem Bestand - if row[1] < 50: - if not resource_warning: - resource_warning = f"Niedriger Bestand bei {row[0].upper()}: nur noch {row[1]} verfügbar!" - else: - resource_warning += f" | {row[0].upper()}: {row[1]}" - - cur.close() - conn.close() - - stats = { - 'total_customers': total_customers, - 'total_licenses': total_licenses, - 'active_licenses': active_licenses, - 'expired_licenses': expired_licenses, - 'inactive_licenses': inactive_licenses, - 'expiring_soon': expiring_soon, - 'full_licenses': license_types.get('full', 0), - 'test_licenses': license_types.get('test', 0), - 'test_data_count': test_data_count, - 'test_customers_count': test_customers_count, - 'test_resources_count': test_resources_count, - 'recent_licenses': recent_licenses, - 'expiring_licenses': expiring_licenses, - 'active_sessions': active_sessions_count, - 'last_backup': last_backup_info, - # Sicherheitsstatistiken - 'blocked_ips_count': blocked_ips_count, - 'failed_attempts_today': failed_attempts_today, - 'recent_security_events': recent_security_events, - 'security_level': security_level, - 'security_level_text': security_level_text, - 'resource_stats': resource_stats - } - - return render_template("dashboard.html", - stats=stats, - resource_stats=resource_stats, - resource_warning=resource_warning, - username=session.get('username')) - -@app.route("/create", methods=["GET", "POST"]) -@login_required -def create_license(): - if request.method == "POST": - customer_id = request.form.get("customer_id") - license_key = request.form["license_key"].upper() # Immer Großbuchstaben - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Validiere License Key Format - if not validate_license_key(license_key): - flash('Ungültiges License Key Format! Erwartet: AF-YYYYMMFT-XXXX-YYYY-ZZZZ', 'error') - return redirect(url_for('create_license')) - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('create_license')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('create_license')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - customer_info = {'name': name, 'email': email, 'is_test': is_test} - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos für Audit-Log - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('create_license')) - customer_info = {'name': customer_data[0], 'email': customer_data[1]} - - # Wenn Kunde Test-Kunde ist, Lizenz auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Lizenz hinzufügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit, is_test) - VALUES (%s, %s, %s, %s, %s, TRUE, %s, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit, is_test)) - license_id = cur.fetchone()[0] - - # Ressourcen zuweisen - try: - # Prüfe Verfügbarkeit - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {available[0]})") - if available[1] < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {ipv4_count}, verfügbar: {available[1]})") - if available[2] < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar (benötigt: {phone_count}, verfügbar: {available[2]})") - - # Domains zuweisen - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s zuweisen - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern zuweisen - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - except ValueError as e: - conn.rollback() - flash(str(e), 'error') - return redirect(url_for('create_license')) - - conn.commit() - - # Audit-Log - log_audit('CREATE', 'license', license_id, - new_values={ - 'license_key': license_key, - 'customer_name': customer_info['name'], - 'customer_email': customer_info['email'], - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'device_limit': device_limit, - 'is_test': is_test - }) - - flash(f'Lizenz {license_key} erfolgreich erstellt!', 'success') - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Erstellen der Lizenz: {str(e)}") - flash('Fehler beim Erstellen der Lizenz!', 'error') - finally: - cur.close() - conn.close() - - # Preserve show_test parameter if present - redirect_url = "/create" - if request.args.get('show_test') == 'true': - redirect_url += "?show_test=true" - return redirect(redirect_url) - - # Unterstützung für vorausgewählten Kunden - preselected_customer_id = request.args.get('customer_id', type=int) - return render_template("index.html", username=session.get('username'), preselected_customer_id=preselected_customer_id) - -@app.route("/batch", methods=["GET", "POST"]) -@login_required -def batch_licenses(): - """Batch-Generierung mehrerer Lizenzen für einen Kunden""" - if request.method == "POST": - # Formulardaten - customer_id = request.form.get("customer_id") - license_type = request.form["license_type"] - quantity = int(request.form["quantity"]) - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - # Sicherheitslimit - if quantity < 1 or quantity > 100: - flash('Anzahl muss zwischen 1 und 100 liegen!', 'error') - return redirect(url_for('batch_licenses')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('batch_licenses')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('batch_licenses')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('batch_licenses')) - name = customer_data[0] - email = customer_data[1] - - # Wenn Kunde Test-Kunde ist, Lizenzen auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Prüfe Ressourcen-Verfügbarkeit für gesamten Batch - total_domains_needed = domain_count * quantity - total_ipv4s_needed = ipv4_count * quantity - total_phones_needed = phone_count * quantity - - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < total_domains_needed: - flash(f"Nicht genügend Domains verfügbar (benötigt: {total_domains_needed}, verfügbar: {available[0]})", 'error') - return redirect(url_for('batch_licenses')) - if available[1] < total_ipv4s_needed: - flash(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {total_ipv4s_needed}, verfügbar: {available[1]})", 'error') - return redirect(url_for('batch_licenses')) - if available[2] < total_phones_needed: - flash(f"Nicht genügend Telefonnummern verfügbar (benötigt: {total_phones_needed}, verfügbar: {available[2]})", 'error') - return redirect(url_for('batch_licenses')) - - # Lizenzen generieren und speichern - generated_licenses = [] - for i in range(quantity): - # Eindeutigen Key generieren - attempts = 0 - while attempts < 10: - license_key = generate_license_key(license_type) - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (license_key,)) - if not cur.fetchone(): - break - attempts += 1 - - # Lizenz einfügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, is_test, - valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit) - VALUES (%s, %s, %s, %s, %s, %s, true, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, is_test, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit)) - license_id = cur.fetchone()[0] - - # Ressourcen für diese Lizenz zuweisen - # Domains - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - generated_licenses.append({ - 'id': license_id, - 'key': license_key, - 'type': license_type - }) - - conn.commit() - - # Audit-Log - log_audit('CREATE_BATCH', 'license', - new_values={'customer': name, 'quantity': quantity, 'type': license_type}, - additional_info=f"Batch-Generierung von {quantity} Lizenzen") - - # Session für Export speichern - session['batch_export'] = { - 'customer': name, - 'email': email, - 'licenses': generated_licenses, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'timestamp': datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - } - - flash(f'{quantity} Lizenzen erfolgreich generiert!', 'success') - return render_template("batch_result.html", - customer=name, - email=email, - licenses=generated_licenses, - valid_from=valid_from, - valid_until=valid_until) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler bei Batch-Generierung: {str(e)}") - flash('Fehler bei der Batch-Generierung!', 'error') - return redirect(url_for('batch_licenses')) - finally: - cur.close() - conn.close() - - # GET Request - return render_template("batch_form.html") - -@app.route("/batch/export") -@login_required -def export_batch(): - """Exportiert die zuletzt generierten Batch-Lizenzen""" - batch_data = session.get('batch_export') - if not batch_data: - flash('Keine Batch-Daten zum Exportieren vorhanden!', 'error') - return redirect(url_for('batch_licenses')) - - # CSV generieren - output = io.StringIO() - output.write('\ufeff') # UTF-8 BOM für Excel - - # Header - output.write(f"Kunde: {batch_data['customer']}\n") - output.write(f"E-Mail: {batch_data['email']}\n") - output.write(f"Generiert am: {datetime.fromisoformat(batch_data['timestamp']).strftime('%d.%m.%Y %H:%M')}\n") - output.write(f"Gültig von: {batch_data['valid_from']} bis {batch_data['valid_until']}\n") - output.write("\n") - output.write("Nr;Lizenzschlüssel;Typ\n") - - # Lizenzen - for i, license in enumerate(batch_data['licenses'], 1): - typ_text = "Vollversion" if license['type'] == 'full' else "Testversion" - output.write(f"{i};{license['key']};{typ_text}\n") - - output.seek(0) - - # Audit-Log - log_audit('EXPORT', 'batch_licenses', - additional_info=f"Export von {len(batch_data['licenses'])} Batch-Lizenzen") - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f"batch_licenses_{batch_data['customer'].replace(' ', '_')}_{datetime.now(ZoneInfo('Europe/Berlin')).strftime('%Y%m%d_%H%M%S')}.csv" - ) - -@app.route("/licenses") -@login_required -def licenses(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/license/edit/", methods=["GET", "POST"]) -@login_required -def edit_license(license_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute(""" - SELECT license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit - FROM licenses WHERE id = %s - """, (license_id,)) - old_license = cur.fetchone() - - # Update license - license_key = request.form["license_key"] - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - valid_until = request.form["valid_until"] - is_active = request.form.get("is_active") == "on" - is_test = request.form.get("is_test") == "on" - device_limit = int(request.form.get("device_limit", 3)) - - cur.execute(""" - UPDATE licenses - SET license_key = %s, license_type = %s, valid_from = %s, - valid_until = %s, is_active = %s, is_test = %s, device_limit = %s - WHERE id = %s - """, (license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit, license_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'license_key': old_license[0], - 'license_type': old_license[1], - 'valid_from': str(old_license[2]), - 'valid_until': str(old_license[3]), - 'is_active': old_license[4], - 'is_test': old_license[5], - 'device_limit': old_license[6] - }, - new_values={ - 'license_key': license_key, - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'is_active': is_active, - 'is_test': is_test, - 'device_limit': device_limit - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei wenn vorhanden - if request.referrer and 'customer_id=' in request.referrer: - import re - match = re.search(r'customer_id=(\d+)', request.referrer) - if match: - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={match.group(1)}" - - return redirect(redirect_url) - - # Get license data - cur.execute(""" - SELECT l.id, l.license_key, c.name, c.email, l.license_type, - l.valid_from, l.valid_until, l.is_active, c.id, l.is_test, l.device_limit - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - - license = cur.fetchone() - cur.close() - conn.close() - - if not license: - return redirect("/licenses") - - return render_template("edit_license.html", license=license, username=session.get('username')) - -@app.route("/license/delete/", methods=["POST"]) -@login_required -def delete_license(license_id): - conn = get_connection() - cur = conn.cursor() - - # Lizenzdetails für Audit-Log abrufen - cur.execute(""" - SELECT l.license_key, c.name, l.license_type - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - license_info = cur.fetchone() - - cur.execute("DELETE FROM licenses WHERE id = %s", (license_id,)) - - conn.commit() - - # Audit-Log - if license_info: - log_audit('DELETE', 'license', license_id, - old_values={ - 'license_key': license_info[0], - 'customer_name': license_info[1], - 'license_type': license_info[2] - }) - - cur.close() - conn.close() - - return redirect("/licenses") - -@app.route("/customers") -@login_required -def customers(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/customer/edit/", methods=["GET", "POST"]) -@login_required -def edit_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - old_customer = cur.fetchone() - - # Update customer - name = request.form["name"] - email = request.form["email"] - is_test = request.form.get("is_test") == "on" - - cur.execute(""" - UPDATE customers - SET name = %s, email = %s, is_test = %s - WHERE id = %s - """, (name, email, is_test, customer_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'customer', customer_id, - old_values={ - 'name': old_customer[0], - 'email': old_customer[1], - 'is_test': old_customer[2] - }, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei (immer der aktuelle Kunde) - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={customer_id}" - - return redirect(redirect_url) - - # Get customer data with licenses - cur.execute(""" - SELECT id, name, email, created_at, is_test FROM customers WHERE id = %s - """, (customer_id,)) - - customer = cur.fetchone() - if not customer: - cur.close() - conn.close() - return "Kunde nicht gefunden", 404 - - - # Get customer's licenses - cur.execute(""" - SELECT id, license_key, license_type, valid_from, valid_until, is_active - FROM licenses - WHERE customer_id = %s - ORDER BY valid_until DESC - """, (customer_id,)) - - licenses = cur.fetchall() - - cur.close() - conn.close() - - if not customer: - return redirect("/customers-licenses") - - return render_template("edit_customer.html", customer=customer, licenses=licenses, username=session.get('username')) - -@app.route("/customer/create", methods=["GET", "POST"]) -@login_required -def create_customer(): - """Erstellt einen neuen Kunden ohne Lizenz""" - if request.method == "POST": - name = request.form.get('name') - email = request.form.get('email') - is_test = request.form.get('is_test') == 'on' - - if not name or not email: - flash("Name und E-Mail sind Pflichtfelder!", "error") - return render_template("create_customer.html", username=session.get('username')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfen ob E-Mail bereits existiert - cur.execute("SELECT id, name FROM customers WHERE email = %s", (email,)) - existing = cur.fetchone() - if existing: - flash(f"Ein Kunde mit der E-Mail '{email}' existiert bereits: {existing[1]}", "error") - return render_template("create_customer.html", username=session.get('username')) - - # Kunde erstellen - cur.execute(""" - INSERT INTO customers (name, email, created_at, is_test) - VALUES (%s, %s, %s, %s) RETURNING id - """, (name, email, datetime.now(), is_test)) - - customer_id = cur.fetchone()[0] - conn.commit() - - # Audit-Log - log_audit('CREATE', 'customer', customer_id, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - flash(f"Kunde '{name}' wurde erfolgreich angelegt!", "success") - return redirect(f"/customer/edit/{customer_id}") - - except Exception as e: - conn.rollback() - flash(f"Fehler beim Anlegen des Kunden: {str(e)}", "error") - return render_template("create_customer.html", username=session.get('username')) - finally: - cur.close() - conn.close() - - # GET Request - Formular anzeigen - return render_template("create_customer.html", username=session.get('username')) - -@app.route("/customer/delete/", methods=["POST"]) -@login_required -def delete_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - # Prüfen ob Kunde Lizenzen hat - cur.execute("SELECT COUNT(*) FROM licenses WHERE customer_id = %s", (customer_id,)) - license_count = cur.fetchone()[0] - - if license_count > 0: - # Kunde hat Lizenzen - nicht löschen - cur.close() - conn.close() - return redirect("/customers") - - # Kundendetails für Audit-Log abrufen - cur.execute("SELECT name, email FROM customers WHERE id = %s", (customer_id,)) - customer_info = cur.fetchone() - - # Kunde löschen wenn keine Lizenzen vorhanden - cur.execute("DELETE FROM customers WHERE id = %s", (customer_id,)) - - conn.commit() - - # Audit-Log - if customer_info: - log_audit('DELETE', 'customer', customer_id, - old_values={ - 'name': customer_info[0], - 'email': customer_info[1] - }) - - cur.close() - conn.close() - - return redirect("/customers") - -@app.route("/customers-licenses") -@login_required -def customers_licenses(): - """Kombinierte Ansicht für Kunden und deren Lizenzen""" - conn = get_connection() - cur = conn.cursor() - - # Hole alle Kunden mit Lizenzstatistiken (inkl. Testkunden wenn gewünscht) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - query = """ - SELECT - c.id, - c.name, - c.email, - c.created_at, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - """ - - if not show_test: - query += " WHERE c.is_test = FALSE" - - query += """ - GROUP BY c.id, c.name, c.email, c.created_at - ORDER BY c.name - """ - - cur.execute(query) - customers = cur.fetchall() - - # Hole ausgewählten Kunden nur wenn explizit in URL angegeben - selected_customer_id = request.args.get('customer_id', type=int) - licenses = [] - selected_customer = None - - if customers and selected_customer_id: - # Hole Daten des ausgewählten Kunden - for customer in customers: - if customer[0] == selected_customer_id: - selected_customer = customer - break - - # Hole Lizenzen des ausgewählten Kunden - if selected_customer: - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (selected_customer_id,)) - licenses = cur.fetchall() - - cur.close() - conn.close() - - return render_template("customers_licenses.html", - customers=customers, - selected_customer=selected_customer, - selected_customer_id=selected_customer_id, - licenses=licenses, - show_test=show_test) - -@app.route("/api/customer//licenses") -@login_required -def api_customer_licenses(customer_id): - """API-Endpoint für AJAX-Abruf der Lizenzen eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Lizenzen des Kunden - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (customer_id,)) - - licenses = [] - for row in cur.fetchall(): - license_id = row[0] - - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for res_row in cur.fetchall(): - resource_info = { - 'id': res_row[0], - 'value': res_row[2], - 'assigned_at': res_row[3].strftime('%d.%m.%Y') if res_row[3] else '' - } - - if res_row[1] == 'domain': - resources['domains'].append(resource_info) - elif res_row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif res_row[1] == 'phone': - resources['phones'].append(resource_info) - - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'license_type': row[2], - 'valid_from': row[3].strftime('%d.%m.%Y') if row[3] else '', - 'valid_until': row[4].strftime('%d.%m.%Y') if row[4] else '', - 'is_active': row[5], - 'status': row[6], - 'domain_count': row[7], # limit - 'ipv4_count': row[8], # limit - 'phone_count': row[9], # limit - 'device_limit': row[10], - 'active_devices': row[11], - 'actual_domain_count': row[12], # actual count - 'actual_ipv4_count': row[13], # actual count - 'actual_phone_count': row[14], # actual count - 'resources': resources - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'licenses': licenses, - 'count': len(licenses) - }) - -@app.route("/api/customer//quick-stats") -@login_required -def api_customer_quick_stats(customer_id): - """API-Endpoint für Schnellstatistiken eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Kundenstatistiken - cur.execute(""" - SELECT - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' AND l.valid_until >= CURRENT_DATE THEN 1 END) as expiring_soon - FROM licenses l - WHERE l.customer_id = %s - """, (customer_id,)) - - stats = cur.fetchone() - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'stats': { - 'total': stats[0], - 'active': stats[1], - 'expired': stats[2], - 'expiring_soon': stats[3] - } - }) - -@app.route("/api/license//quick-edit", methods=['POST']) -@login_required -def api_license_quick_edit(license_id): - """API-Endpoint für schnelle Lizenz-Bearbeitung""" - conn = get_connection() - cur = conn.cursor() - - try: - data = request.get_json() - - # Hole alte Werte für Audit-Log - cur.execute(""" - SELECT is_active, valid_until, license_type - FROM licenses WHERE id = %s - """, (license_id,)) - old_values = cur.fetchone() - - if not old_values: - return jsonify({'success': False, 'error': 'Lizenz nicht gefunden'}), 404 - - # Update-Felder vorbereiten - updates = [] - params = [] - new_values = {} - - if 'is_active' in data: - updates.append("is_active = %s") - params.append(data['is_active']) - new_values['is_active'] = data['is_active'] - - if 'valid_until' in data: - updates.append("valid_until = %s") - params.append(data['valid_until']) - new_values['valid_until'] = data['valid_until'] - - if 'license_type' in data: - updates.append("license_type = %s") - params.append(data['license_type']) - new_values['license_type'] = data['license_type'] - - if updates: - params.append(license_id) - cur.execute(f""" - UPDATE licenses - SET {', '.join(updates)} - WHERE id = %s - """, params) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'is_active': old_values[0], - 'valid_until': old_values[1].isoformat() if old_values[1] else None, - 'license_type': old_values[2] - }, - new_values=new_values) - - cur.close() - conn.close() - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/api/license//resources") -@login_required -def api_license_resources(license_id): - """API-Endpoint für detaillierte Ressourcen-Informationen einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for row in cur.fetchall(): - resource_info = { - 'id': row[0], - 'value': row[2], - 'assigned_at': row[3].strftime('%d.%m.%Y') if row[3] else '' - } - - if row[1] == 'domain': - resources['domains'].append(resource_info) - elif row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif row[1] == 'phone': - resources['phones'].append(resource_info) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'resources': resources - }) - - except Exception as e: - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/sessions") -@login_required -def sessions(): - conn = get_connection() - cur = conn.cursor() - - # Sortierparameter - active_sort = request.args.get('active_sort', 'last_heartbeat') - active_order = request.args.get('active_order', 'desc') - ended_sort = request.args.get('ended_sort', 'ended_at') - ended_order = request.args.get('ended_order', 'desc') - - # Whitelist für erlaubte Sortierfelder - Aktive Sessions - active_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'last_heartbeat': 's.last_heartbeat', - 'inactive': 'minutes_inactive' - } - - # Whitelist für erlaubte Sortierfelder - Beendete Sessions - ended_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'ended_at': 's.ended_at', - 'duration': 'duration_minutes' - } - - # Validierung - if active_sort not in active_sort_fields: - active_sort = 'last_heartbeat' - if ended_sort not in ended_sort_fields: - ended_sort = 'ended_at' - if active_order not in ['asc', 'desc']: - active_order = 'desc' - if ended_order not in ['asc', 'desc']: - ended_order = 'desc' - - # Aktive Sessions abrufen - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.user_agent, s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.last_heartbeat))/60 as minutes_inactive - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = TRUE - ORDER BY {active_sort_fields[active_sort]} {active_order.upper()} - """) - active_sessions = cur.fetchall() - - # Inaktive Sessions der letzten 24 Stunden - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))/60 as duration_minutes - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = FALSE - AND s.ended_at > NOW() - INTERVAL '24 hours' - ORDER BY {ended_sort_fields[ended_sort]} {ended_order.upper()} - LIMIT 50 - """) - recent_sessions = cur.fetchall() - - cur.close() - conn.close() - - return render_template("sessions.html", - active_sessions=active_sessions, - recent_sessions=recent_sessions, - active_sort=active_sort, - active_order=active_order, - ended_sort=ended_sort, - ended_order=ended_order, - username=session.get('username')) - -@app.route("/session/end/", methods=["POST"]) -@login_required -def end_session(session_id): - conn = get_connection() - cur = conn.cursor() - - # Session beenden - cur.execute(""" - UPDATE sessions - SET is_active = FALSE, ended_at = NOW() - WHERE id = %s AND is_active = TRUE - """, (session_id,)) - - conn.commit() - cur.close() - conn.close() - - return redirect("/sessions") - -@app.route("/export/licenses") -@login_required -def export_licenses(): - conn = get_connection() - cur = conn.cursor() - - # Alle Lizenzen mit Kundeninformationen abrufen (ohne Testdaten, außer explizit gewünscht) - include_test = request.args.get('include_test', 'false').lower() == 'true' - customer_id = request.args.get('customer_id', type=int) - - query = """ - SELECT l.id, l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type, l.valid_from, l.valid_until, l.is_active, l.is_test, - CASE - WHEN l.is_active = FALSE THEN 'Deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'Abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'Läuft bald ab' - ELSE 'Aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - """ - - # Build WHERE clause - where_conditions = [] - params = [] - - if not include_test: - where_conditions.append("l.is_test = FALSE") - - if customer_id: - where_conditions.append("l.customer_id = %s") - params.append(customer_id) - - if where_conditions: - query += " WHERE " + " AND ".join(where_conditions) - - query += " ORDER BY l.id" - - cur.execute(query, params) - - # Spaltennamen - columns = ['ID', 'Lizenzschlüssel', 'Kunde', 'E-Mail', 'Typ', - 'Gültig von', 'Gültig bis', 'Aktiv', 'Testdaten', 'Status'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Gültig von'] = pd.to_datetime(df['Gültig von']).dt.strftime('%d.%m.%Y') - df['Gültig bis'] = pd.to_datetime(df['Gültig bis']).dt.strftime('%d.%m.%Y') - - # Typ und Aktiv Status anpassen - df['Typ'] = df['Typ'].replace({'full': 'Vollversion', 'test': 'Testversion'}) - df['Aktiv'] = df['Aktiv'].replace({True: 'Ja', False: 'Nein'}) - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'license', - additional_info=f"Export aller Lizenzen als {export_format.upper()}") - filename = f'lizenzen_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Lizenzen', index=False) - - # Formatierung - worksheet = writer.sheets['Lizenzen'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/audit") -@login_required -def export_audit(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_user = request.args.get('user', '') - filter_action = request.args.get('action', '') - filter_entity = request.args.get('entity', '') - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - params = [] - - if filter_user: - query += " AND username ILIKE %s" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - query += " ORDER BY timestamp DESC" - - cur.execute(query, params) - audit_logs = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for log in audit_logs: - action_text = { - 'CREATE': 'Erstellt', - 'UPDATE': 'Bearbeitet', - 'DELETE': 'Gelöscht', - 'LOGIN': 'Anmeldung', - 'LOGOUT': 'Abmeldung', - 'AUTO_LOGOUT': 'Auto-Logout', - 'EXPORT': 'Export', - 'GENERATE_KEY': 'Key generiert', - 'CREATE_BATCH': 'Batch erstellt', - 'BACKUP': 'Backup erstellt', - 'LOGIN_2FA_SUCCESS': '2FA-Anmeldung', - 'LOGIN_2FA_BACKUP': '2FA-Backup-Code', - 'LOGIN_2FA_FAILED': '2FA-Fehlgeschlagen', - 'LOGIN_BLOCKED': 'Login-Blockiert', - 'RESTORE': 'Wiederhergestellt', - 'PASSWORD_CHANGE': 'Passwort geändert', - '2FA_ENABLED': '2FA aktiviert', - '2FA_DISABLED': '2FA deaktiviert' - }.get(log[3], log[3]) - - data.append({ - 'ID': log[0], - 'Zeitstempel': log[1].strftime('%d.%m.%Y %H:%M:%S'), - 'Benutzer': log[2], - 'Aktion': action_text, - 'Entität': log[4], - 'Entität-ID': log[5] or '', - 'IP-Adresse': log[8] or '', - 'Zusatzinfo': log[10] or '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'audit_log_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'audit_log', - additional_info=f"{export_format.upper()} Export mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Audit Log') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Audit Log'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/customers") -@login_required -def export_customers(): - conn = get_connection() - cur = conn.cursor() - - # Check if test data should be included - include_test = request.args.get('include_test', 'false').lower() == 'true' - - # Build query based on test data filter - if include_test: - # Include all customers - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - else: - # Exclude test customers and test licenses - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(CASE WHEN l.is_test = FALSE THEN 1 END) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.is_test = FALSE - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - - cur.execute(query) - - # Spaltennamen - columns = ['ID', 'Name', 'E-Mail', 'Erstellt am', 'Testdaten', - 'Lizenzen gesamt', 'Aktive Lizenzen', 'Abgelaufene Lizenzen'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Erstellt am'] = pd.to_datetime(df['Erstellt am']).dt.strftime('%d.%m.%Y %H:%M') - - # Testdaten formatting - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'customer', - additional_info=f"Export aller Kunden als {export_format.upper()}") - filename = f'kunden_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Kunden', index=False) - - # Formatierung - worksheet = writer.sheets['Kunden'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/sessions") -@login_required -def export_sessions(): - conn = get_connection() - cur = conn.cursor() - - # Holen des Session-Typs (active oder ended) - session_type = request.args.get('type', 'active') - export_format = request.args.get('format', 'excel') - - # Daten je nach Typ abrufen - if session_type == 'active': - # Aktive Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = true - ORDER BY s.last_heartbeat DESC - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Letzte Aktivität': sess[5].strftime('%d.%m.%Y %H:%M:%S'), - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Aktive Sessions' - filename_prefix = 'aktive_sessions' - else: - # Beendete Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = false AND s.ended_at IS NOT NULL - ORDER BY s.ended_at DESC - LIMIT 1000 - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] if sess[6] else 0 - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Endzeit': sess[5].strftime('%d.%m.%Y %H:%M:%S') if sess[5] else '', - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Beendete Sessions' - filename_prefix = 'beendete_sessions' - - cur.close() - conn.close() - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'{filename_prefix}_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'sessions', - additional_info=f"{export_format.upper()} Export von {session_type} Sessions mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name=sheet_name) - - # Spaltenbreiten anpassen - worksheet = writer.sheets[sheet_name] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/resources") -@login_required -def export_resources(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_type = request.args.get('type', '') - filter_status = request.args.get('status', '') - search_query = request.args.get('search', '') - show_test = request.args.get('show_test', 'false').lower() == 'true' - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT r.id, r.resource_type, r.resource_value, r.status, r.allocated_to_license, - r.created_at, r.status_changed_at, - l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type - FROM resource_pools r - LEFT JOIN licenses l ON r.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE 1=1 - """ - params = [] - - # Filter für Testdaten - if not show_test: - query += " AND (r.is_test = false OR r.is_test IS NULL)" - - # Filter für Ressourcentyp - if filter_type: - query += " AND r.resource_type = %s" - params.append(filter_type) - - # Filter für Status - if filter_status: - query += " AND r.status = %s" - params.append(filter_status) - - # Suchfilter - if search_query: - query += " AND (r.resource_value ILIKE %s OR l.license_key ILIKE %s OR c.name ILIKE %s)" - params.extend([f'%{search_query}%', f'%{search_query}%', f'%{search_query}%']) - - query += " ORDER BY r.id DESC" - - cur.execute(query, params) - resources = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for res in resources: - status_text = { - 'available': 'Verfügbar', - 'allocated': 'Zugewiesen', - 'quarantine': 'Quarantäne' - }.get(res[3], res[3]) - - type_text = { - 'domain': 'Domain', - 'ipv4': 'IPv4', - 'phone': 'Telefon' - }.get(res[1], res[1]) - - data.append({ - 'ID': res[0], - 'Typ': type_text, - 'Ressource': res[2], - 'Status': status_text, - 'Lizenzschlüssel': res[7] or '', - 'Kunde': res[8] or '', - 'Kunden-Email': res[9] or '', - 'Lizenztyp': res[10] or '', - 'Erstellt am': res[5].strftime('%d.%m.%Y %H:%M:%S') if res[5] else '', - 'Zugewiesen am': res[6].strftime('%d.%m.%Y %H:%M:%S') if res[6] else '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'resources_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'resources', - additional_info=f"{export_format.upper()} Export mit {len(data)} Ressourcen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Resources') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Resources'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/audit") -@login_required -def audit_log(): - conn = get_connection() - cur = conn.cursor() - - # Parameter - filter_user = request.args.get('user', '').strip() - filter_action = request.args.get('action', '').strip() - filter_entity = request.args.get('entity', '').strip() - page = request.args.get('page', 1, type=int) - sort = request.args.get('sort', 'timestamp') - order = request.args.get('order', 'desc') - per_page = 50 - - # Whitelist für erlaubte Sortierfelder - allowed_sort_fields = { - 'timestamp': 'timestamp', - 'username': 'username', - 'action': 'action', - 'entity': 'entity_type', - 'ip': 'ip_address' - } - - # Validierung - if sort not in allowed_sort_fields: - sort = 'timestamp' - if order not in ['asc', 'desc']: - order = 'desc' - - sort_field = allowed_sort_fields[sort] - - # SQL Query mit optionalen Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - - params = [] - - # Filter - if filter_user: - query += " AND LOWER(username) LIKE LOWER(%s)" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - # Gesamtanzahl für Pagination - count_query = "SELECT COUNT(*) FROM (" + query + ") as count_table" - cur.execute(count_query, params) - total = cur.fetchone()[0] - - # Pagination - offset = (page - 1) * per_page - query += f" ORDER BY {sort_field} {order.upper()} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - logs = cur.fetchall() - - # JSON-Werte parsen - parsed_logs = [] - for log in logs: - parsed_log = list(log) - # old_values und new_values sind bereits Dictionaries (JSONB) - # Keine Konvertierung nötig - parsed_logs.append(parsed_log) - - # Pagination Info - total_pages = (total + per_page - 1) // per_page - - cur.close() - conn.close() - - return render_template("audit_log.html", - logs=parsed_logs, - filter_user=filter_user, - filter_action=filter_action, - filter_entity=filter_entity, - page=page, - total_pages=total_pages, - total=total, - sort=sort, - order=order, - username=session.get('username')) - -@app.route("/backups") -@login_required -def backups(): - """Zeigt die Backup-Historie an""" - conn = get_connection() - cur = conn.cursor() - - # Letztes erfolgreiches Backup für Dashboard - cur.execute(""" - SELECT created_at, filesize, duration_seconds - FROM backup_history - WHERE status = 'success' - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup = cur.fetchone() - - # Alle Backups abrufen - cur.execute(""" - SELECT id, filename, filesize, backup_type, status, error_message, - created_at, created_by, tables_count, records_count, - duration_seconds, is_encrypted - FROM backup_history - ORDER BY created_at DESC - """) - backups = cur.fetchall() - - cur.close() - conn.close() - - return render_template("backups.html", - backups=backups, - last_backup=last_backup, - username=session.get('username')) - -@app.route("/backup/create", methods=["POST"]) -@login_required -def create_backup_route(): - """Erstellt ein manuelles Backup""" - username = session.get('username') - success, result = create_backup(backup_type="manual", created_by=username) - - if success: - return jsonify({ - 'success': True, - 'message': f'Backup erfolgreich erstellt: {result}' - }) - else: - return jsonify({ - 'success': False, - 'message': f'Backup fehlgeschlagen: {result}' - }), 500 - -@app.route("/backup/restore/", methods=["POST"]) -@login_required -def restore_backup_route(backup_id): - """Stellt ein Backup wieder her""" - encryption_key = request.form.get('encryption_key') - - success, message = restore_backup(backup_id, encryption_key) - - if success: - return jsonify({ - 'success': True, - 'message': message - }) - else: - return jsonify({ - 'success': False, - 'message': message - }), 500 - -@app.route("/backup/download/") -@login_required -def download_backup(backup_id): - """Lädt eine Backup-Datei herunter""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - cur.close() - conn.close() - - if not backup_info: - return "Backup nicht gefunden", 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - if not filepath.exists(): - return "Backup-Datei nicht gefunden", 404 - - # Audit-Log - log_audit('DOWNLOAD', 'backup', backup_id, - additional_info=f"Backup heruntergeladen: {filename}") - - return send_file(filepath, as_attachment=True, download_name=filename) - -@app.route("/backup/delete/", methods=["DELETE"]) -@login_required -def delete_backup(backup_id): - """Löscht ein Backup""" - conn = get_connection() - cur = conn.cursor() - - try: - # Backup-Informationen abrufen - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - if not backup_info: - return jsonify({ - 'success': False, - 'message': 'Backup nicht gefunden' - }), 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - # Datei löschen, wenn sie existiert - if filepath.exists(): - filepath.unlink() - - # Aus Datenbank löschen - cur.execute(""" - DELETE FROM backup_history - WHERE id = %s - """, (backup_id,)) - - conn.commit() - - # Audit-Log - log_audit('DELETE', 'backup', backup_id, - additional_info=f"Backup gelöscht: {filename}") - - return jsonify({ - 'success': True, - 'message': f'Backup "{filename}" wurde erfolgreich gelöscht' - }) - - except Exception as e: - conn.rollback() - return jsonify({ - 'success': False, - 'message': f'Fehler beim Löschen des Backups: {str(e)}' - }), 500 - finally: - cur.close() - conn.close() - -@app.route("/security/blocked-ips") -@login_required -def blocked_ips(): - """Zeigt alle gesperrten IPs an""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT - ip_address, - attempt_count, - first_attempt, - last_attempt, - blocked_until, - last_username_tried, - last_error_message - FROM login_attempts - WHERE blocked_until IS NOT NULL - ORDER BY blocked_until DESC - """) - - blocked_ips_list = [] - for ip in cur.fetchall(): - blocked_ips_list.append({ - 'ip_address': ip[0], - 'attempt_count': ip[1], - 'first_attempt': ip[2].strftime('%d.%m.%Y %H:%M'), - 'last_attempt': ip[3].strftime('%d.%m.%Y %H:%M'), - 'blocked_until': ip[4].strftime('%d.%m.%Y %H:%M'), - 'is_active': ip[4] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None), - 'last_username': ip[5], - 'last_error': ip[6] - }) - - cur.close() - conn.close() - - return render_template("blocked_ips.html", - blocked_ips=blocked_ips_list, - username=session.get('username')) - -@app.route("/security/unblock-ip", methods=["POST"]) -@login_required -def unblock_ip(): - """Entsperrt eine IP-Adresse""" - ip_address = request.form.get('ip_address') - - if ip_address: - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - UPDATE login_attempts - SET blocked_until = NULL - WHERE ip_address = %s - """, (ip_address,)) - - conn.commit() - cur.close() - conn.close() - - # Audit-Log - log_audit('UNBLOCK_IP', 'security', - additional_info=f"IP {ip_address} manuell entsperrt") - - return redirect(url_for('blocked_ips')) - -@app.route("/security/clear-attempts", methods=["POST"]) -@login_required -def clear_attempts(): - """Löscht alle Login-Versuche für eine IP""" - ip_address = request.form.get('ip_address') - - if ip_address: - reset_login_attempts(ip_address) - - # Audit-Log - log_audit('CLEAR_ATTEMPTS', 'security', - additional_info=f"Login-Versuche für IP {ip_address} zurückgesetzt") - - return redirect(url_for('blocked_ips')) - -# API Endpoints for License Management -@app.route("/api/license//toggle", methods=["POST"]) -@login_required -def toggle_license_api(license_id): - """Toggle license active status via API""" - try: - data = request.get_json() - is_active = data.get('is_active', False) - - conn = get_connection() - cur = conn.cursor() - - # Update license status - cur.execute(""" - UPDATE licenses - SET is_active = %s - WHERE id = %s - """, (is_active, license_id)) - - conn.commit() - - # Log the action - log_audit('UPDATE', 'license', license_id, - new_values={'is_active': is_active}, - additional_info=f"Lizenz {'aktiviert' if is_active else 'deaktiviert'} via Toggle") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Status erfolgreich geändert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-activate", methods=["POST"]) -@login_required -def bulk_activate_licenses(): - """Activate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = TRUE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': True, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen aktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen aktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-deactivate", methods=["POST"]) -@login_required -def bulk_deactivate_licenses(): - """Deactivate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = FALSE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': False, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen deaktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen deaktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/license//devices") -@login_required -def get_license_devices(license_id): - """Hole alle registrierten Geräte einer Lizenz""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und hole device_limit - cur.execute(""" - SELECT device_limit FROM licenses WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit = license_data[0] - - # Hole alle Geräte für diese Lizenz - cur.execute(""" - SELECT id, hardware_id, device_name, operating_system, - first_seen, last_seen, is_active, ip_address - FROM device_registrations - WHERE license_id = %s - ORDER BY is_active DESC, last_seen DESC - """, (license_id,)) - - devices = [] - for row in cur.fetchall(): - devices.append({ - 'id': row[0], - 'hardware_id': row[1], - 'device_name': row[2] or 'Unbekanntes Gerät', - 'operating_system': row[3] or 'Unbekannt', - 'first_seen': row[4].strftime('%d.%m.%Y %H:%M') if row[4] else '', - 'last_seen': row[5].strftime('%d.%m.%Y %H:%M') if row[5] else '', - 'is_active': row[6], - 'ip_address': row[7] or '-' - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'devices': devices, - 'device_limit': device_limit, - 'active_count': sum(1 for d in devices if d['is_active']) - }) - - except Exception as e: - logging.error(f"Fehler beim Abrufen der Geräte: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Abrufen der Geräte'}), 500 - -@app.route("/api/license//register-device", methods=["POST"]) -def register_device(license_id): - """Registriere ein neues Gerät für eine Lizenz""" - try: - data = request.get_json() - hardware_id = data.get('hardware_id') - device_name = data.get('device_name', '') - operating_system = data.get('operating_system', '') - - if not hardware_id: - return jsonify({'success': False, 'message': 'Hardware-ID fehlt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und aktiv ist - cur.execute(""" - SELECT device_limit, is_active, valid_until - FROM licenses - WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit, is_active, valid_until = license_data - - # Prüfe ob Lizenz aktiv und gültig ist - if not is_active: - return jsonify({'success': False, 'message': 'Lizenz ist deaktiviert'}), 403 - - if valid_until < datetime.now(ZoneInfo("Europe/Berlin")).date(): - return jsonify({'success': False, 'message': 'Lizenz ist abgelaufen'}), 403 - - # Prüfe ob Gerät bereits registriert ist - cur.execute(""" - SELECT id, is_active FROM device_registrations - WHERE license_id = %s AND hardware_id = %s - """, (license_id, hardware_id)) - existing_device = cur.fetchone() - - if existing_device: - device_id, is_device_active = existing_device - if is_device_active: - # Gerät ist bereits aktiv, update last_seen - cur.execute(""" - UPDATE device_registrations - SET last_seen = CURRENT_TIMESTAMP, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät bereits registriert', 'device_id': device_id}) - else: - # Gerät war deaktiviert, prüfe ob wir es reaktivieren können - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Reaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = TRUE, - last_seen = CURRENT_TIMESTAMP, - deactivated_at = NULL, - deactivated_by = NULL, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät reaktiviert', 'device_id': device_id}) - - # Neues Gerät - prüfe Gerätelimit - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Registriere neues Gerät - cur.execute(""" - INSERT INTO device_registrations - (license_id, hardware_id, device_name, operating_system, ip_address, user_agent) - VALUES (%s, %s, %s, %s, %s, %s) - RETURNING id - """, (license_id, hardware_id, device_name, operating_system, - get_client_ip(), request.headers.get('User-Agent', ''))) - device_id = cur.fetchone()[0] - - conn.commit() - - # Audit Log - log_audit('DEVICE_REGISTER', 'device', device_id, - new_values={'license_id': license_id, 'hardware_id': hardware_id}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich registriert', 'device_id': device_id}) - - except Exception as e: - logging.error(f"Fehler bei Geräte-Registrierung: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler bei der Registrierung'}), 500 - -@app.route("/api/license//deactivate-device/", methods=["POST"]) -@login_required -def deactivate_device(license_id, device_id): - """Deaktiviere ein registriertes Gerät""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob das Gerät zu dieser Lizenz gehört - cur.execute(""" - SELECT id FROM device_registrations - WHERE id = %s AND license_id = %s AND is_active = TRUE - """, (device_id, license_id)) - - if not cur.fetchone(): - return jsonify({'success': False, 'message': 'Gerät nicht gefunden oder bereits deaktiviert'}), 404 - - # Deaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = FALSE, - deactivated_at = CURRENT_TIMESTAMP, - deactivated_by = %s - WHERE id = %s - """, (session['username'], device_id)) - - conn.commit() - - # Audit Log - log_audit('DEVICE_DEACTIVATE', 'device', device_id, - old_values={'is_active': True}, - new_values={'is_active': False}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich deaktiviert'}) - - except Exception as e: - logging.error(f"Fehler beim Deaktivieren des Geräts: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Deaktivieren'}), 500 - -@app.route("/api/licenses/bulk-delete", methods=["POST"]) -@login_required -def bulk_delete_licenses(): - """Delete multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Get license info for audit log (nur Live-Daten) - cur.execute(""" - SELECT license_key - FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - license_keys = [row[0] for row in cur.fetchall()] - - # Delete all selected licenses (nur Live-Daten) - cur.execute(""" - DELETE FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_DELETE', 'licenses', None, - old_values={'license_keys': license_keys, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen gelöscht") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen gelöscht'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# ===================== RESOURCE POOL MANAGEMENT ===================== - -@app.route('/resources') -@login_required -def resources(): - """Resource Pool Hauptübersicht""" - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Testdaten angezeigt werden sollen (gleiche Logik wie bei Kunden) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - # Statistiken abrufen - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = %s - GROUP BY resource_type - """, (show_test,)) - - stats = {} - for row in cur.fetchall(): - stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - } - - # Letzte Aktivitäten (gefiltert nach Test/Live) - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rp.resource_type, - rp.resource_value, - rh.details - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - WHERE rp.is_test = %s - ORDER BY rh.action_at DESC - LIMIT 10 - """, (show_test,)) - recent_activities = cur.fetchall() - - # Ressourcen-Liste mit Pagination - page = request.args.get('page', 1, type=int) - per_page = 50 - offset = (page - 1) * per_page - - resource_type = request.args.get('type', '') - status_filter = request.args.get('status', '') - search = request.args.get('search', '') - - # Sortierung - sort_by = request.args.get('sort', 'id') - sort_order = request.args.get('order', 'desc') - - # Base Query - query = """ - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - rp.allocated_to_license, - l.license_key, - c.name as customer_name, - rp.status_changed_at, - rp.quarantine_reason, - rp.quarantine_until, - c.id as customer_id - FROM resource_pools rp - LEFT JOIN licenses l ON rp.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rp.is_test = %s - """ - params = [show_test] - - if resource_type: - query += " AND rp.resource_type = %s" - params.append(resource_type) - - if status_filter: - query += " AND rp.status = %s" - params.append(status_filter) - - if search: - query += " AND rp.resource_value ILIKE %s" - params.append(f'%{search}%') - - # Count total - count_query = f"SELECT COUNT(*) FROM ({query}) as cnt" - cur.execute(count_query, params) - total = cur.fetchone()[0] - total_pages = (total + per_page - 1) // per_page - - # Get paginated results with dynamic sorting - sort_column_map = { - 'id': 'rp.id', - 'type': 'rp.resource_type', - 'resource': 'rp.resource_value', - 'status': 'rp.status', - 'assigned': 'c.name', - 'changed': 'rp.status_changed_at' - } - - sort_column = sort_column_map.get(sort_by, 'rp.id') - sort_direction = 'ASC' if sort_order == 'asc' else 'DESC' - - query += f" ORDER BY {sort_column} {sort_direction} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - resources = cur.fetchall() - - cur.close() - conn.close() - - return render_template('resources.html', - stats=stats, - resources=resources, - recent_activities=recent_activities, - page=page, - total_pages=total_pages, - total=total, - resource_type=resource_type, - status_filter=status_filter, - search=search, - show_test=show_test, - sort_by=sort_by, - sort_order=sort_order, - datetime=datetime, - timedelta=timedelta) - -@app.route('/resources/add', methods=['GET', 'POST']) -@login_required -def add_resources(): - """Ressourcen zum Pool hinzufügen""" - # Hole show_test Parameter für die Anzeige - show_test = request.args.get('show_test', 'false').lower() == 'true' - - if request.method == 'POST': - resource_type = request.form.get('resource_type') - resources_text = request.form.get('resources_text', '') - is_test = request.form.get('is_test') == 'on' # Checkbox für Testdaten - - # Parse resources (one per line) - resources = [r.strip() for r in resources_text.split('\n') if r.strip()] - - if not resources: - flash('Keine Ressourcen angegeben', 'error') - return redirect(url_for('add_resources', show_test=show_test)) - - conn = get_connection() - cur = conn.cursor() - - added = 0 - duplicates = 0 - - for resource_value in resources: - try: - cur.execute(""" - INSERT INTO resource_pools (resource_type, resource_value, status_changed_by, is_test) - VALUES (%s, %s, %s, %s) - ON CONFLICT (resource_type, resource_value) DO NOTHING - """, (resource_type, resource_value, session['username'], is_test)) - - if cur.rowcount > 0: - added += 1 - # Get the inserted ID - cur.execute("SELECT id FROM resource_pools WHERE resource_type = %s AND resource_value = %s", - (resource_type, resource_value)) - resource_id = cur.fetchone()[0] - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'created', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - else: - duplicates += 1 - - except Exception as e: - app.logger.error(f"Error adding resource {resource_value}: {e}") - - conn.commit() - cur.close() - conn.close() - - log_audit('CREATE', 'resource_pool', None, - new_values={'type': resource_type, 'added': added, 'duplicates': duplicates, 'is_test': is_test}, - additional_info=f"{added} {'Test-' if is_test else ''}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen") - - flash(f'{added} {"Test-" if is_test else ""}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen', 'success') - return redirect(url_for('resources', show_test=show_test)) - - return render_template('add_resources.html', show_test=show_test) - -@app.route('/resources/quarantine/', methods=['POST']) -@login_required -def quarantine_resource(resource_id): - """Ressource in Quarantäne setzen""" - reason = request.form.get('reason', 'review') - until_date = request.form.get('until_date') - notes = request.form.get('notes', '') - - conn = get_connection() - cur = conn.cursor() - - # Get current resource info - cur.execute("SELECT resource_type, resource_value, status FROM resource_pools WHERE id = %s", (resource_id,)) - resource = cur.fetchone() - - if not resource: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - old_status = resource[2] - - # Update resource - cur.execute(""" - UPDATE resource_pools - SET status = 'quarantine', - quarantine_reason = %s, - quarantine_until = %s, - notes = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (reason, until_date if until_date else None, notes, session['username'], resource_id)) - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address, details) - VALUES (%s, 'quarantined', %s, %s, %s) - """, (resource_id, session['username'], get_client_ip(), - Json({'reason': reason, 'until': until_date, 'notes': notes, 'old_status': old_status}))) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource', resource_id, - old_values={'status': old_status}, - new_values={'status': 'quarantine', 'reason': reason}, - additional_info=f"Ressource {resource[0]}: {resource[1]} in Quarantäne") - - flash('Ressource in Quarantäne gesetzt', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/resources/release', methods=['POST']) -@login_required -def release_resources(): - """Ressourcen aus Quarantäne freigeben""" - resource_ids = request.form.getlist('resource_ids') - - if not resource_ids: - flash('Keine Ressourcen ausgewählt', 'error') - return redirect(url_for('resources')) - - conn = get_connection() - cur = conn.cursor() - - released = 0 - for resource_id in resource_ids: - cur.execute(""" - UPDATE resource_pools - SET status = 'available', - quarantine_reason = NULL, - quarantine_until = NULL, - allocated_to_license = NULL, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s AND status = 'quarantine' - """, (session['username'], resource_id)) - - if cur.rowcount > 0: - released += 1 - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'released', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource_pool', None, - new_values={'released': released}, - additional_info=f"{released} Ressourcen aus Quarantäne freigegeben") - - flash(f'{released} Ressourcen freigegeben', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/api/resources/allocate', methods=['POST']) -@login_required -def allocate_resources_api(): - """API für Ressourcen-Zuweisung bei Lizenzerstellung""" - data = request.json - license_id = data.get('license_id') - domain_count = data.get('domain_count', 1) - ipv4_count = data.get('ipv4_count', 1) - phone_count = data.get('phone_count', 1) - - conn = get_connection() - cur = conn.cursor() - - try: - allocated = {'domains': [], 'ipv4s': [], 'phones': []} - - # Allocate domains - if domain_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' - LIMIT %s FOR UPDATE - """, (domain_count,)) - domains = cur.fetchall() - - if len(domains) < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {len(domains)})") - - for domain_id, domain_value in domains: - # Update resource status - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], domain_id)) - - # Create assignment - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, domain_id, session['username'])) - - # Log history - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (domain_id, license_id, session['username'], get_client_ip())) - - allocated['domains'].append(domain_value) - - # Allocate IPv4s (similar logic) - if ipv4_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' - LIMIT %s FOR UPDATE - """, (ipv4_count,)) - ipv4s = cur.fetchall() - - if len(ipv4s) < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar") - - for ipv4_id, ipv4_value in ipv4s: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], ipv4_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, ipv4_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (ipv4_id, license_id, session['username'], get_client_ip())) - - allocated['ipv4s'].append(ipv4_value) - - # Allocate phones (similar logic) - if phone_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' - LIMIT %s FOR UPDATE - """, (phone_count,)) - phones = cur.fetchall() - - if len(phones) < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar") - - for phone_id, phone_value in phones: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], phone_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, phone_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (phone_id, license_id, session['username'], get_client_ip())) - - allocated['phones'].append(phone_value) - - # Update license resource counts - cur.execute(""" - UPDATE licenses - SET domain_count = %s, - ipv4_count = %s, - phone_count = %s - WHERE id = %s - """, (domain_count, ipv4_count, phone_count, license_id)) - - conn.commit() - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'allocated': allocated - }) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({ - 'success': False, - 'error': str(e) - }), 400 - -@app.route('/api/resources/check-availability', methods=['GET']) -@login_required -def check_resource_availability(): - """Prüft verfügbare Ressourcen""" - resource_type = request.args.get('type', '') - count = request.args.get('count', 10, type=int) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - conn = get_connection() - cur = conn.cursor() - - if resource_type: - # Spezifische Ressourcen für einen Typ - cur.execute(""" - SELECT id, resource_value - FROM resource_pools - WHERE status = 'available' - AND resource_type = %s - AND is_test = %s - ORDER BY resource_value - LIMIT %s - """, (resource_type, show_test, count)) - - resources = [] - for row in cur.fetchall(): - resources.append({ - 'id': row[0], - 'value': row[1] - }) - - cur.close() - conn.close() - - return jsonify({ - 'available': resources, - 'type': resource_type, - 'count': len(resources) - }) - else: - # Zusammenfassung aller Typen - cur.execute(""" - SELECT - resource_type, - COUNT(*) as available - FROM resource_pools - WHERE status = 'available' - AND is_test = %s - GROUP BY resource_type - """, (show_test,)) - - availability = {} - for row in cur.fetchall(): - availability[row[0]] = row[1] - - cur.close() - conn.close() - - return jsonify(availability) - -@app.route('/api/global-search', methods=['GET']) -@login_required -def global_search(): - """Global search API endpoint for searching customers and licenses""" - query = request.args.get('q', '').strip() - - if not query or len(query) < 2: - return jsonify({'customers': [], 'licenses': []}) - - conn = get_connection() - cur = conn.cursor() - - # Search pattern with wildcards - search_pattern = f'%{query}%' - - # Search customers - cur.execute(""" - SELECT id, name, email, company_name - FROM customers - WHERE (LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - OR LOWER(company_name) LIKE LOWER(%s)) - AND is_test = FALSE - ORDER BY name - LIMIT 5 - """, (search_pattern, search_pattern, search_pattern)) - - customers = [] - for row in cur.fetchall(): - customers.append({ - 'id': row[0], - 'name': row[1], - 'email': row[2], - 'company_name': row[3] - }) - - # Search licenses - cur.execute(""" - SELECT l.id, l.license_key, c.name as customer_name - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE LOWER(l.license_key) LIKE LOWER(%s) - AND l.is_test = FALSE - ORDER BY l.created_at DESC - LIMIT 5 - """, (search_pattern,)) - - licenses = [] - for row in cur.fetchall(): - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'customer_name': row[2] - }) - - cur.close() - conn.close() - - return jsonify({ - 'customers': customers, - 'licenses': licenses - }) - -@app.route('/resources/history/') -@login_required -def resource_history(resource_id): - """Zeigt die komplette Historie einer Ressource""" - conn = get_connection() - cur = conn.cursor() - - # Get complete resource info using named columns - cur.execute(""" - SELECT id, resource_type, resource_value, status, allocated_to_license, - status_changed_at, status_changed_by, quarantine_reason, - quarantine_until, created_at, notes - FROM resource_pools - WHERE id = %s - """, (resource_id,)) - row = cur.fetchone() - - if not row: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - # Create resource object with named attributes - resource = { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'allocated_to_license': row[4], - 'status_changed_at': row[5], - 'status_changed_by': row[6], - 'quarantine_reason': row[7], - 'quarantine_until': row[8], - 'created_at': row[9], - 'notes': row[10] - } - - # Get license info if allocated - license_info = None - if resource['allocated_to_license']: - cur.execute("SELECT license_key FROM licenses WHERE id = %s", - (resource['allocated_to_license'],)) - lic = cur.fetchone() - if lic: - license_info = {'license_key': lic[0]} - - # Get history with named columns - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rh.details, - rh.license_id, - rh.ip_address - FROM resource_history rh - WHERE rh.resource_id = %s - ORDER BY rh.action_at DESC - """, (resource_id,)) - - history = [] - for row in cur.fetchall(): - history.append({ - 'action': row[0], - 'action_by': row[1], - 'action_at': row[2], - 'details': row[3], - 'license_id': row[4], - 'ip_address': row[5] - }) - - cur.close() - conn.close() - - # Convert to object-like for template - class ResourceObj: - def __init__(self, data): - for key, value in data.items(): - setattr(self, key, value) - - resource_obj = ResourceObj(resource) - history_objs = [ResourceObj(h) for h in history] - - return render_template('resource_history.html', - resource=resource_obj, - license_info=license_info, - history=history_objs) - -@app.route('/resources/metrics') -@login_required -def resources_metrics(): - """Dashboard für Resource Metrics und Reports""" - conn = get_connection() - cur = conn.cursor() - - # Overall stats with fallback values - cur.execute(""" - SELECT - COUNT(DISTINCT resource_id) as total_resources, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(cost), 0) as total_cost, - COALESCE(SUM(revenue), 0) as total_revenue, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - """) - row = cur.fetchone() - - # Calculate ROI - roi = 0 - if row[2] > 0: # if total_cost > 0 - roi = row[3] / row[2] # revenue / cost - - stats = { - 'total_resources': row[0] or 0, - 'avg_performance': row[1] or 0, - 'total_cost': row[2] or 0, - 'total_revenue': row[3] or 0, - 'total_issues': row[4] or 0, - 'roi': roi - } - - # Performance by type - cur.execute(""" - SELECT - rp.resource_type, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COUNT(DISTINCT rp.id) as resource_count - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY rp.resource_type - ORDER BY rp.resource_type - """) - performance_by_type = cur.fetchall() - - # Utilization data - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) as total, - ROUND(COUNT(*) FILTER (WHERE status = 'allocated') * 100.0 / COUNT(*), 1) as allocated_percent - FROM resource_pools - GROUP BY resource_type - """) - utilization_rows = cur.fetchall() - utilization_data = [ - { - 'type': row[0].upper(), - 'allocated': row[1], - 'total': row[2], - 'allocated_percent': row[3] - } - for row in utilization_rows - ] - - # Top performing resources - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COALESCE(SUM(rm.revenue), 0) as total_revenue, - COALESCE(SUM(rm.cost), 1) as total_cost, - CASE - WHEN COALESCE(SUM(rm.cost), 0) = 0 THEN 0 - ELSE COALESCE(SUM(rm.revenue), 0) / COALESCE(SUM(rm.cost), 1) - END as roi - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rp.status != 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value - HAVING AVG(rm.performance_score) IS NOT NULL - ORDER BY avg_score DESC - LIMIT 10 - """) - top_rows = cur.fetchall() - top_performers = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'avg_score': row[3], - 'roi': row[6] - } - for row in top_rows - ] - - # Resources with issues - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - COALESCE(SUM(rm.issues_count), 0) as total_issues - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rm.issues_count > 0 OR rp.status = 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - HAVING SUM(rm.issues_count) > 0 - ORDER BY total_issues DESC - LIMIT 10 - """) - problem_rows = cur.fetchall() - problem_resources = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'total_issues': row[4] - } - for row in problem_rows - ] - - # Daily metrics for trend chart (last 30 days) - cur.execute(""" - SELECT - metric_date, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY metric_date - ORDER BY metric_date - """) - daily_rows = cur.fetchall() - daily_metrics = [ - { - 'date': row[0].strftime('%d.%m'), - 'performance': float(row[1]), - 'issues': int(row[2]) - } - for row in daily_rows - ] - - cur.close() - conn.close() - - return render_template('resource_metrics.html', - stats=stats, - performance_by_type=performance_by_type, - utilization_data=utilization_data, - top_performers=top_performers, - problem_resources=problem_resources, - daily_metrics=daily_metrics) - -@app.route('/resources/report', methods=['GET']) -@login_required -def resources_report(): - """Generiert Ressourcen-Reports oder zeigt Report-Formular""" - # Prüfe ob Download angefordert wurde - if request.args.get('download') == 'true': - report_type = request.args.get('type', 'usage') - format_type = request.args.get('format', 'excel') - date_from = request.args.get('from', (datetime.now(ZoneInfo("Europe/Berlin")) - timedelta(days=30)).strftime('%Y-%m-%d')) - date_to = request.args.get('to', datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y-%m-%d')) - - conn = get_connection() - cur = conn.cursor() - - if report_type == 'usage': - # Auslastungsreport - query = """ - SELECT - rp.resource_type, - rp.resource_value, - rp.status, - COUNT(DISTINCT rh.license_id) as unique_licenses, - COUNT(rh.id) as total_allocations, - MIN(rh.action_at) as first_used, - MAX(rh.action_at) as last_used - FROM resource_pools rp - LEFT JOIN resource_history rh ON rp.id = rh.resource_id - AND rh.action = 'allocated' - AND rh.action_at BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - ORDER BY rp.resource_type, total_allocations DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Status', 'Unique Lizenzen', 'Gesamt Zuweisungen', 'Erste Nutzung', 'Letzte Nutzung'] - - elif report_type == 'performance': - # Performance-Report - query = """ - SELECT - rp.resource_type, - rp.resource_value, - AVG(rm.performance_score) as avg_performance, - SUM(rm.usage_count) as total_usage, - SUM(rm.revenue) as total_revenue, - SUM(rm.cost) as total_cost, - SUM(rm.revenue - rm.cost) as profit, - SUM(rm.issues_count) as total_issues - FROM resource_pools rp - JOIN resource_metrics rm ON rp.id = rm.resource_id - WHERE rm.metric_date BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value - ORDER BY profit DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Durchschn. Performance', 'Gesamt Nutzung', 'Umsatz', 'Kosten', 'Gewinn', 'Issues'] - - elif report_type == 'compliance': - # Compliance-Report - query = """ - SELECT - rh.action_at, - rh.action, - rh.action_by, - rp.resource_type, - rp.resource_value, - l.license_key, - c.name as customer_name, - rh.ip_address - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - LEFT JOIN licenses l ON rh.license_id = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rh.action_at BETWEEN %s AND %s - ORDER BY rh.action_at DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Zeit', 'Aktion', 'Von', 'Typ', 'Ressource', 'Lizenz', 'Kunde', 'IP-Adresse'] - - else: # inventory report - # Inventar-Report - query = """ - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - GROUP BY resource_type - ORDER BY resource_type - """ - cur.execute(query) - columns = ['Typ', 'Verfügbar', 'Zugeteilt', 'Quarantäne', 'Gesamt'] - - # Convert to DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - cur.close() - conn.close() - - # Generate file - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f"resource_report_{report_type}_{timestamp}" - - if format_type == 'excel': - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Report', index=False) - - # Auto-adjust columns width - worksheet = writer.sheets['Report'] - for column in worksheet.columns: - max_length = 0 - column = [cell for cell in column] - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = (max_length + 2) - worksheet.column_dimensions[column[0].column_letter].width = adjusted_width - - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'excel', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx') - - else: # CSV - output = io.StringIO() - df.to_csv(output, index=False, sep=';', encoding='utf-8-sig') - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'csv', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv') - - # Wenn kein Download, zeige Report-Formular - return render_template('resource_report.html', - datetime=datetime, - timedelta=timedelta, - username=session.get('username')) - -if __name__ == "__main__": - app.run(host="0.0.0.0", port=5000) diff --git a/v2_adminpanel/app_before_blueprint.py b/v2_adminpanel/app_before_blueprint.py deleted file mode 100644 index f4a9bf2..0000000 --- a/v2_adminpanel/app_before_blueprint.py +++ /dev/null @@ -1,4460 +0,0 @@ -import os -import sys -import time -import json -import logging -import requests -import re -import random -import base64 -from io import BytesIO -from datetime import datetime, timedelta -from zoneinfo import ZoneInfo -from pathlib import Path - -# Add current directory to Python path to ensure modules can be imported -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from flask import Flask, render_template, request, redirect, session, url_for, send_file, jsonify, flash -from flask_session import Session -from werkzeug.middleware.proxy_fix import ProxyFix -from apscheduler.schedulers.background import BackgroundScheduler -import pandas as pd -from psycopg2.extras import Json - -# Import our new modules -import config -from db import get_connection, get_db_connection, get_db_cursor, execute_query -from auth.decorators import login_required -from auth.password import hash_password, verify_password -from auth.two_factor import ( - generate_totp_secret, generate_qr_code, verify_totp, - generate_backup_codes, hash_backup_code, verify_backup_code -) -from auth.rate_limiting import ( - check_ip_blocked, record_failed_attempt, - reset_login_attempts, get_login_attempts -) -from utils.network import get_client_ip -from utils.audit import log_audit -from utils.license import generate_license_key, validate_license_key -from utils.backup import create_backup, restore_backup, get_or_create_encryption_key -from utils.export import ( - create_excel_export, format_datetime_for_export, - prepare_license_export_data, prepare_customer_export_data, - prepare_session_export_data, prepare_audit_export_data -) -from models import get_user_by_username - -app = Flask(__name__) -# Load configuration from config module -app.config['SECRET_KEY'] = config.SECRET_KEY -app.config['SESSION_TYPE'] = config.SESSION_TYPE -app.config['JSON_AS_ASCII'] = config.JSON_AS_ASCII -app.config['JSONIFY_MIMETYPE'] = config.JSONIFY_MIMETYPE -app.config['PERMANENT_SESSION_LIFETIME'] = config.PERMANENT_SESSION_LIFETIME -app.config['SESSION_COOKIE_HTTPONLY'] = config.SESSION_COOKIE_HTTPONLY -app.config['SESSION_COOKIE_SECURE'] = config.SESSION_COOKIE_SECURE -app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE -app.config['SESSION_COOKIE_NAME'] = config.SESSION_COOKIE_NAME -app.config['SESSION_REFRESH_EACH_REQUEST'] = config.SESSION_REFRESH_EACH_REQUEST -Session(app) - -# ProxyFix für korrekte IP-Adressen hinter Nginx -app.wsgi_app = ProxyFix( - app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 -) - -# Configuration is now loaded from config module - -# Scheduler für automatische Backups -scheduler = BackgroundScheduler() -scheduler.start() - -# Logging konfigurieren -logging.basicConfig(level=logging.INFO) - -# Import and register blueprints -from routes.auth_routes import auth_bp -from routes.admin_routes import admin_bp - -app.register_blueprint(auth_bp) -app.register_blueprint(admin_bp) - - -# Scheduled Backup Job -def scheduled_backup(): - """Führt ein geplantes Backup aus""" - logging.info("Starte geplantes Backup...") - create_backup(backup_type="scheduled", created_by="scheduler") - -# Scheduler konfigurieren - täglich um 3:00 Uhr -scheduler.add_job( - scheduled_backup, - 'cron', - hour=config.SCHEDULER_CONFIG['backup_hour'], - minute=config.SCHEDULER_CONFIG['backup_minute'], - id='daily_backup', - replace_existing=True -) - - -def verify_recaptcha(response): - """Verifiziert die reCAPTCHA v2 Response mit Google""" - secret_key = config.RECAPTCHA_SECRET_KEY - - # Wenn kein Secret Key konfiguriert ist, CAPTCHA als bestanden werten (für PoC) - if not secret_key: - logging.warning("RECAPTCHA_SECRET_KEY nicht konfiguriert - CAPTCHA wird übersprungen") - return True - - # Verifizierung bei Google - try: - verify_url = 'https://www.google.com/recaptcha/api/siteverify' - data = { - 'secret': secret_key, - 'response': response - } - - # Timeout für Request setzen - r = requests.post(verify_url, data=data, timeout=5) - result = r.json() - - # Log für Debugging - if not result.get('success'): - logging.warning(f"reCAPTCHA Validierung fehlgeschlagen: {result.get('error-codes', [])}") - - return result.get('success', False) - - except requests.exceptions.RequestException as e: - logging.error(f"reCAPTCHA Verifizierung fehlgeschlagen: {str(e)}") - # Bei Netzwerkfehlern CAPTCHA als bestanden werten - return True - except Exception as e: - logging.error(f"Unerwarteter Fehler bei reCAPTCHA: {str(e)}") - return False - - -@app.route("/login", methods=["GET", "POST"]) -def login(): - # Timing-Attack Schutz - Start Zeit merken - start_time = time.time() - - # IP-Adresse ermitteln - ip_address = get_client_ip() - - # Prüfen ob IP gesperrt ist - is_blocked, blocked_until = check_ip_blocked(ip_address) - if is_blocked: - time_remaining = (blocked_until - datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None)).total_seconds() / 3600 - error_msg = f"IP GESPERRT! Noch {time_remaining:.1f} Stunden warten." - return render_template("login.html", error=error_msg, error_type="blocked") - - # Anzahl bisheriger Versuche - attempt_count = get_login_attempts(ip_address) - - if request.method == "POST": - username = request.form.get("username") - password = request.form.get("password") - captcha_response = request.form.get("g-recaptcha-response") - - # CAPTCHA-Prüfung nur wenn Keys konfiguriert sind - recaptcha_site_key = config.RECAPTCHA_SITE_KEY - if attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and recaptcha_site_key: - if not captcha_response: - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA ERFORDERLICH!", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # CAPTCHA validieren - if not verify_recaptcha(captcha_response): - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA UNGÜLTIG! Bitte erneut versuchen.", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # Check user in database first, fallback to env vars - user = get_user_by_username(username) - login_success = False - needs_2fa = False - - if user: - # Database user authentication - if verify_password(password, user['password_hash']): - login_success = True - needs_2fa = user['totp_enabled'] - else: - # Fallback to environment variables for backward compatibility - if username in config.ADMIN_USERS and password == config.ADMIN_USERS[username]: - login_success = True - - # Timing-Attack Schutz - Mindestens 1 Sekunde warten - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - - if login_success: - # Erfolgreicher Login - if needs_2fa: - # Store temporary session for 2FA verification - session['temp_username'] = username - session['temp_user_id'] = user['id'] - session['awaiting_2fa'] = True - return redirect(url_for('verify_2fa')) - else: - # Complete login without 2FA - session.permanent = True # Aktiviert das Timeout - session['logged_in'] = True - session['username'] = username - session['user_id'] = user['id'] if user else None - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - reset_login_attempts(ip_address) - log_audit('LOGIN_SUCCESS', 'user', - additional_info=f"Erfolgreiche Anmeldung von IP: {ip_address}") - return redirect(url_for('dashboard')) - else: - # Fehlgeschlagener Login - error_message = record_failed_attempt(ip_address, username) - new_attempt_count = get_login_attempts(ip_address) - - # Prüfen ob jetzt gesperrt - is_now_blocked, _ = check_ip_blocked(ip_address) - if is_now_blocked: - log_audit('LOGIN_BLOCKED', 'security', - additional_info=f"IP {ip_address} wurde nach {config.MAX_LOGIN_ATTEMPTS} Versuchen gesperrt") - - return render_template("login.html", - error=error_message, - show_captcha=(new_attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - error_type="failed", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - new_attempt_count), - recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - - # GET Request - return render_template("login.html", - show_captcha=(attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - -@app.route("/logout") -def logout(): - username = session.get('username', 'unknown') - log_audit('LOGOUT', 'user', additional_info=f"Abmeldung") - session.pop('logged_in', None) - session.pop('username', None) - session.pop('user_id', None) - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - return redirect(url_for('login')) - -@app.route("/verify-2fa", methods=["GET", "POST"]) -def verify_2fa(): - if not session.get('awaiting_2fa'): - return redirect(url_for('login')) - - if request.method == "POST": - token = request.form.get('token', '').replace(' ', '') - username = session.get('temp_username') - user_id = session.get('temp_user_id') - - if not username or not user_id: - flash('Session expired. Please login again.', 'error') - return redirect(url_for('login')) - - user = get_user_by_username(username) - if not user: - flash('User not found.', 'error') - return redirect(url_for('login')) - - # Check if it's a backup code - if len(token) == 8 and token.isupper(): - # Try backup code - backup_codes = json.loads(user['backup_codes']) if user['backup_codes'] else [] - if verify_backup_code(token, backup_codes): - # Remove used backup code - code_hash = hash_backup_code(token) - backup_codes.remove(code_hash) - - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET backup_codes = %s WHERE id = %s", - (json.dumps(backup_codes), user_id)) - conn.commit() - cur.close() - conn.close() - - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - flash('Login successful using backup code. Please generate new backup codes.', 'warning') - log_audit('LOGIN_2FA_BACKUP', 'user', additional_info=f"2FA login with backup code") - return redirect(url_for('dashboard')) - else: - # Try TOTP token - if verify_totp(user['totp_secret'], token): - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - log_audit('LOGIN_2FA_SUCCESS', 'user', additional_info=f"2FA login successful") - return redirect(url_for('dashboard')) - - # Failed verification - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET failed_2fa_attempts = failed_2fa_attempts + 1, last_failed_2fa = %s WHERE id = %s", - (datetime.now(), user_id)) - conn.commit() - cur.close() - conn.close() - - flash('Invalid authentication code. Please try again.', 'error') - log_audit('LOGIN_2FA_FAILED', 'user', additional_info=f"Failed 2FA attempt") - - return render_template('verify_2fa.html') - -@app.route("/profile") -@login_required -def profile(): - user = get_user_by_username(session['username']) - if not user: - # For environment-based users, redirect with message - flash('Bitte führen Sie das Migrations-Script aus, um Passwort-Änderung und 2FA zu aktivieren.', 'info') - return redirect(url_for('dashboard')) - return render_template('profile.html', user=user) - -@app.route("/profile/change-password", methods=["POST"]) -@login_required -def change_password(): - current_password = request.form.get('current_password') - new_password = request.form.get('new_password') - confirm_password = request.form.get('confirm_password') - - user = get_user_by_username(session['username']) - - # Verify current password - if not verify_password(current_password, user['password_hash']): - flash('Current password is incorrect.', 'error') - return redirect(url_for('profile')) - - # Check new password - if new_password != confirm_password: - flash('New passwords do not match.', 'error') - return redirect(url_for('profile')) - - if len(new_password) < 8: - flash('Password must be at least 8 characters long.', 'error') - return redirect(url_for('profile')) - - # Update password - new_hash = hash_password(new_password) - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET password_hash = %s, last_password_change = %s WHERE id = %s", - (new_hash, datetime.now(), user['id'])) - conn.commit() - cur.close() - conn.close() - - log_audit('PASSWORD_CHANGE', 'user', entity_id=user['id'], - additional_info="Password changed successfully") - flash('Password changed successfully.', 'success') - return redirect(url_for('profile')) - -@app.route("/profile/setup-2fa") -@login_required -def setup_2fa(): - user = get_user_by_username(session['username']) - - if user['totp_enabled']: - flash('2FA is already enabled for your account.', 'info') - return redirect(url_for('profile')) - - # Generate new TOTP secret - totp_secret = generate_totp_secret() - session['temp_totp_secret'] = totp_secret - - # Generate QR code - qr_code = generate_qr_code(user['username'], totp_secret) - - return render_template('setup_2fa.html', - totp_secret=totp_secret, - qr_code=qr_code) - -@app.route("/profile/enable-2fa", methods=["POST"]) -@login_required -def enable_2fa(): - token = request.form.get('token', '').replace(' ', '') - totp_secret = session.get('temp_totp_secret') - - if not totp_secret: - flash('2FA setup session expired. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Verify the token - if not verify_totp(totp_secret, token): - flash('Invalid authentication code. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Generate backup codes - backup_codes = generate_backup_codes() - hashed_codes = [hash_backup_code(code) for code in backup_codes] - - # Enable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_secret = %s, totp_enabled = TRUE, backup_codes = %s - WHERE username = %s - """, (totp_secret, json.dumps(hashed_codes), session['username'])) - conn.commit() - cur.close() - conn.close() - - session.pop('temp_totp_secret', None) - - log_audit('2FA_ENABLED', 'user', additional_info="2FA enabled successfully") - - # Show backup codes - return render_template('backup_codes.html', backup_codes=backup_codes) - -@app.route("/profile/disable-2fa", methods=["POST"]) -@login_required -def disable_2fa(): - password = request.form.get('password') - user = get_user_by_username(session['username']) - - # Verify password - if not verify_password(password, user['password_hash']): - flash('Incorrect password.', 'error') - return redirect(url_for('profile')) - - # Disable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_enabled = FALSE, totp_secret = NULL, backup_codes = NULL - WHERE username = %s - """, (session['username'],)) - conn.commit() - cur.close() - conn.close() - - log_audit('2FA_DISABLED', 'user', additional_info="2FA disabled") - flash('2FA has been disabled for your account.', 'success') - return redirect(url_for('profile')) - -@app.route("/heartbeat", methods=['POST']) -@login_required -def heartbeat(): - """Endpoint für Session Keep-Alive - aktualisiert last_activity""" - # Aktualisiere last_activity nur wenn explizit angefordert - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # Force session save - session.modified = True - - return jsonify({ - 'status': 'ok', - 'last_activity': session['last_activity'], - 'username': session.get('username') - }) - -@app.route("/api/generate-license-key", methods=['POST']) -@login_required -def api_generate_key(): - """API Endpoint zur Generierung eines neuen Lizenzschlüssels""" - try: - # Lizenztyp aus Request holen (default: full) - data = request.get_json() or {} - license_type = data.get('type', 'full') - - # Key generieren - key = generate_license_key(license_type) - - # Prüfen ob Key bereits existiert (sehr unwahrscheinlich aber sicher ist sicher) - conn = get_connection() - cur = conn.cursor() - - # Wiederhole bis eindeutiger Key gefunden - attempts = 0 - while attempts < 10: # Max 10 Versuche - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (key,)) - if not cur.fetchone(): - break # Key ist eindeutig - key = generate_license_key(license_type) - attempts += 1 - - cur.close() - conn.close() - - # Log für Audit - log_audit('GENERATE_KEY', 'license', - additional_info={'type': license_type, 'key': key}) - - return jsonify({ - 'success': True, - 'key': key, - 'type': license_type - }) - - except Exception as e: - logging.error(f"Fehler bei Key-Generierung: {str(e)}") - return jsonify({ - 'success': False, - 'error': 'Fehler bei der Key-Generierung' - }), 500 - -@app.route("/api/customers", methods=['GET']) -@login_required -def api_customers(): - """API Endpoint für die Kundensuche mit Select2""" - try: - # Suchparameter - search = request.args.get('q', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - customer_id = request.args.get('id', type=int) - - conn = get_connection() - cur = conn.cursor() - - # Einzelnen Kunden per ID abrufen - if customer_id: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.id = %s - GROUP BY c.id, c.name, c.email - """, (customer_id,)) - - customer = cur.fetchone() - results = [] - if customer: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} ({customer[2]})", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - cur.close() - conn.close() - - return jsonify({ - 'results': results, - 'pagination': {'more': False} - }) - - # SQL Query mit optionaler Suche - elif search: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE LOWER(c.name) LIKE LOWER(%s) - OR LOWER(c.email) LIKE LOWER(%s) - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (f'%{search}%', f'%{search}%', per_page, (page - 1) * per_page)) - else: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (per_page, (page - 1) * per_page)) - - customers = cur.fetchall() - - # Format für Select2 - results = [] - for customer in customers: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} - {customer[2]} ({customer[3]} Lizenzen)", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - # Gesamtanzahl für Pagination - if search: - cur.execute(""" - SELECT COUNT(*) FROM customers - WHERE LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - """, (f'%{search}%', f'%{search}%')) - else: - cur.execute("SELECT COUNT(*) FROM customers") - - total_count = cur.fetchone()[0] - - cur.close() - conn.close() - - # Select2 Response Format - return jsonify({ - 'results': results, - 'pagination': { - 'more': (page * per_page) < total_count - } - }) - - except Exception as e: - logging.error(f"Fehler bei Kundensuche: {str(e)}") - return jsonify({ - 'results': [], - 'error': 'Fehler bei der Kundensuche' - }), 500 - -@app.route("/") -@login_required -def dashboard(): - conn = get_connection() - cur = conn.cursor() - - # Statistiken abrufen - # Gesamtanzahl Kunden (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = FALSE") - total_customers = cur.fetchone()[0] - - # Gesamtanzahl Lizenzen (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = FALSE") - total_licenses = cur.fetchone()[0] - - # Aktive Lizenzen (nicht abgelaufen und is_active = true, ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE AND is_active = TRUE AND is_test = FALSE - """) - active_licenses = cur.fetchone()[0] - - # Aktive Sessions - cur.execute("SELECT COUNT(*) FROM sessions WHERE is_active = TRUE") - active_sessions_count = cur.fetchone()[0] - - # Abgelaufene Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until < CURRENT_DATE AND is_test = FALSE - """) - expired_licenses = cur.fetchone()[0] - - # Deaktivierte Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE is_active = FALSE AND is_test = FALSE - """) - inactive_licenses = cur.fetchone()[0] - - # Lizenzen die in den nächsten 30 Tagen ablaufen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE - AND valid_until < CURRENT_DATE + INTERVAL '30 days' - AND is_active = TRUE - AND is_test = FALSE - """) - expiring_soon = cur.fetchone()[0] - - # Testlizenzen vs Vollversionen (ohne Testdaten) - cur.execute(""" - SELECT license_type, COUNT(*) - FROM licenses - WHERE is_test = FALSE - GROUP BY license_type - """) - license_types = dict(cur.fetchall()) - - # Anzahl Testdaten - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = TRUE") - test_data_count = cur.fetchone()[0] - - # Anzahl Test-Kunden - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = TRUE") - test_customers_count = cur.fetchone()[0] - - # Anzahl Test-Ressourcen - cur.execute("SELECT COUNT(*) FROM resource_pools WHERE is_test = TRUE") - test_resources_count = cur.fetchone()[0] - - # Letzte 5 erstellten Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.is_test = FALSE - ORDER BY l.id DESC - LIMIT 5 - """) - recent_licenses = cur.fetchall() - - # Bald ablaufende Lizenzen (nächste 30 Tage, ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - l.valid_until - CURRENT_DATE as days_left - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.valid_until >= CURRENT_DATE - AND l.valid_until < CURRENT_DATE + INTERVAL '30 days' - AND l.is_active = TRUE - AND l.is_test = FALSE - ORDER BY l.valid_until - LIMIT 10 - """) - expiring_licenses = cur.fetchall() - - # Letztes Backup - cur.execute(""" - SELECT created_at, filesize, duration_seconds, backup_type, status - FROM backup_history - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup_info = cur.fetchone() - - # Sicherheitsstatistiken - # Gesperrte IPs - cur.execute(""" - SELECT COUNT(*) FROM login_attempts - WHERE blocked_until IS NOT NULL AND blocked_until > CURRENT_TIMESTAMP - """) - blocked_ips_count = cur.fetchone()[0] - - # Fehlversuche heute - cur.execute(""" - SELECT COALESCE(SUM(attempt_count), 0) FROM login_attempts - WHERE last_attempt::date = CURRENT_DATE - """) - failed_attempts_today = cur.fetchone()[0] - - # Letzte 5 Sicherheitsereignisse - cur.execute(""" - SELECT - la.ip_address, - la.attempt_count, - la.last_attempt, - la.blocked_until, - la.last_username_tried, - la.last_error_message - FROM login_attempts la - ORDER BY la.last_attempt DESC - LIMIT 5 - """) - recent_security_events = [] - for event in cur.fetchall(): - recent_security_events.append({ - 'ip_address': event[0], - 'attempt_count': event[1], - 'last_attempt': event[2].strftime('%d.%m %H:%M'), - 'blocked_until': event[3].strftime('%d.%m %H:%M') if event[3] and event[3] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) else None, - 'username_tried': event[4], - 'error_message': event[5] - }) - - # Sicherheitslevel berechnen - if blocked_ips_count > 5 or failed_attempts_today > 50: - security_level = 'danger' - security_level_text = 'KRITISCH' - elif blocked_ips_count > 2 or failed_attempts_today > 20: - security_level = 'warning' - security_level_text = 'ERHÖHT' - else: - security_level = 'success' - security_level_text = 'NORMAL' - - # Resource Pool Statistiken (nur Live-Daten, keine Testdaten) - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = FALSE - GROUP BY resource_type - """) - - resource_stats = {} - resource_warning = None - - for row in cur.fetchall(): - available_percent = round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - resource_stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': available_percent, - 'warning_level': 'danger' if row[1] < 50 else 'warning' if row[1] < 100 else 'success' - } - - # Warnung bei niedrigem Bestand - if row[1] < 50: - if not resource_warning: - resource_warning = f"Niedriger Bestand bei {row[0].upper()}: nur noch {row[1]} verfügbar!" - else: - resource_warning += f" | {row[0].upper()}: {row[1]}" - - cur.close() - conn.close() - - stats = { - 'total_customers': total_customers, - 'total_licenses': total_licenses, - 'active_licenses': active_licenses, - 'expired_licenses': expired_licenses, - 'inactive_licenses': inactive_licenses, - 'expiring_soon': expiring_soon, - 'full_licenses': license_types.get('full', 0), - 'test_licenses': license_types.get('test', 0), - 'test_data_count': test_data_count, - 'test_customers_count': test_customers_count, - 'test_resources_count': test_resources_count, - 'recent_licenses': recent_licenses, - 'expiring_licenses': expiring_licenses, - 'active_sessions': active_sessions_count, - 'last_backup': last_backup_info, - # Sicherheitsstatistiken - 'blocked_ips_count': blocked_ips_count, - 'failed_attempts_today': failed_attempts_today, - 'recent_security_events': recent_security_events, - 'security_level': security_level, - 'security_level_text': security_level_text, - 'resource_stats': resource_stats - } - - return render_template("dashboard.html", - stats=stats, - resource_stats=resource_stats, - resource_warning=resource_warning, - username=session.get('username')) - -@app.route("/create", methods=["GET", "POST"]) -@login_required -def create_license(): - if request.method == "POST": - customer_id = request.form.get("customer_id") - license_key = request.form["license_key"].upper() # Immer Großbuchstaben - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Validiere License Key Format - if not validate_license_key(license_key): - flash('Ungültiges License Key Format! Erwartet: AF-YYYYMMFT-XXXX-YYYY-ZZZZ', 'error') - return redirect(url_for('create_license')) - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('create_license')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('create_license')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - customer_info = {'name': name, 'email': email, 'is_test': is_test} - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos für Audit-Log - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('create_license')) - customer_info = {'name': customer_data[0], 'email': customer_data[1]} - - # Wenn Kunde Test-Kunde ist, Lizenz auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Lizenz hinzufügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit, is_test) - VALUES (%s, %s, %s, %s, %s, TRUE, %s, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit, is_test)) - license_id = cur.fetchone()[0] - - # Ressourcen zuweisen - try: - # Prüfe Verfügbarkeit - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {available[0]})") - if available[1] < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {ipv4_count}, verfügbar: {available[1]})") - if available[2] < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar (benötigt: {phone_count}, verfügbar: {available[2]})") - - # Domains zuweisen - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s zuweisen - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern zuweisen - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - except ValueError as e: - conn.rollback() - flash(str(e), 'error') - return redirect(url_for('create_license')) - - conn.commit() - - # Audit-Log - log_audit('CREATE', 'license', license_id, - new_values={ - 'license_key': license_key, - 'customer_name': customer_info['name'], - 'customer_email': customer_info['email'], - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'device_limit': device_limit, - 'is_test': is_test - }) - - flash(f'Lizenz {license_key} erfolgreich erstellt!', 'success') - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Erstellen der Lizenz: {str(e)}") - flash('Fehler beim Erstellen der Lizenz!', 'error') - finally: - cur.close() - conn.close() - - # Preserve show_test parameter if present - redirect_url = "/create" - if request.args.get('show_test') == 'true': - redirect_url += "?show_test=true" - return redirect(redirect_url) - - # Unterstützung für vorausgewählten Kunden - preselected_customer_id = request.args.get('customer_id', type=int) - return render_template("index.html", username=session.get('username'), preselected_customer_id=preselected_customer_id) - -@app.route("/batch", methods=["GET", "POST"]) -@login_required -def batch_licenses(): - """Batch-Generierung mehrerer Lizenzen für einen Kunden""" - if request.method == "POST": - # Formulardaten - customer_id = request.form.get("customer_id") - license_type = request.form["license_type"] - quantity = int(request.form["quantity"]) - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - # Sicherheitslimit - if quantity < 1 or quantity > 100: - flash('Anzahl muss zwischen 1 und 100 liegen!', 'error') - return redirect(url_for('batch_licenses')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('batch_licenses')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('batch_licenses')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('batch_licenses')) - name = customer_data[0] - email = customer_data[1] - - # Wenn Kunde Test-Kunde ist, Lizenzen auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Prüfe Ressourcen-Verfügbarkeit für gesamten Batch - total_domains_needed = domain_count * quantity - total_ipv4s_needed = ipv4_count * quantity - total_phones_needed = phone_count * quantity - - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < total_domains_needed: - flash(f"Nicht genügend Domains verfügbar (benötigt: {total_domains_needed}, verfügbar: {available[0]})", 'error') - return redirect(url_for('batch_licenses')) - if available[1] < total_ipv4s_needed: - flash(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {total_ipv4s_needed}, verfügbar: {available[1]})", 'error') - return redirect(url_for('batch_licenses')) - if available[2] < total_phones_needed: - flash(f"Nicht genügend Telefonnummern verfügbar (benötigt: {total_phones_needed}, verfügbar: {available[2]})", 'error') - return redirect(url_for('batch_licenses')) - - # Lizenzen generieren und speichern - generated_licenses = [] - for i in range(quantity): - # Eindeutigen Key generieren - attempts = 0 - while attempts < 10: - license_key = generate_license_key(license_type) - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (license_key,)) - if not cur.fetchone(): - break - attempts += 1 - - # Lizenz einfügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, is_test, - valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit) - VALUES (%s, %s, %s, %s, %s, %s, true, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, is_test, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit)) - license_id = cur.fetchone()[0] - - # Ressourcen für diese Lizenz zuweisen - # Domains - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - generated_licenses.append({ - 'id': license_id, - 'key': license_key, - 'type': license_type - }) - - conn.commit() - - # Audit-Log - log_audit('CREATE_BATCH', 'license', - new_values={'customer': name, 'quantity': quantity, 'type': license_type}, - additional_info=f"Batch-Generierung von {quantity} Lizenzen") - - # Session für Export speichern - session['batch_export'] = { - 'customer': name, - 'email': email, - 'licenses': generated_licenses, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'timestamp': datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - } - - flash(f'{quantity} Lizenzen erfolgreich generiert!', 'success') - return render_template("batch_result.html", - customer=name, - email=email, - licenses=generated_licenses, - valid_from=valid_from, - valid_until=valid_until) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler bei Batch-Generierung: {str(e)}") - flash('Fehler bei der Batch-Generierung!', 'error') - return redirect(url_for('batch_licenses')) - finally: - cur.close() - conn.close() - - # GET Request - return render_template("batch_form.html") - -@app.route("/batch/export") -@login_required -def export_batch(): - """Exportiert die zuletzt generierten Batch-Lizenzen""" - batch_data = session.get('batch_export') - if not batch_data: - flash('Keine Batch-Daten zum Exportieren vorhanden!', 'error') - return redirect(url_for('batch_licenses')) - - # CSV generieren - output = io.StringIO() - output.write('\ufeff') # UTF-8 BOM für Excel - - # Header - output.write(f"Kunde: {batch_data['customer']}\n") - output.write(f"E-Mail: {batch_data['email']}\n") - output.write(f"Generiert am: {datetime.fromisoformat(batch_data['timestamp']).strftime('%d.%m.%Y %H:%M')}\n") - output.write(f"Gültig von: {batch_data['valid_from']} bis {batch_data['valid_until']}\n") - output.write("\n") - output.write("Nr;Lizenzschlüssel;Typ\n") - - # Lizenzen - for i, license in enumerate(batch_data['licenses'], 1): - typ_text = "Vollversion" if license['type'] == 'full' else "Testversion" - output.write(f"{i};{license['key']};{typ_text}\n") - - output.seek(0) - - # Audit-Log - log_audit('EXPORT', 'batch_licenses', - additional_info=f"Export von {len(batch_data['licenses'])} Batch-Lizenzen") - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f"batch_licenses_{batch_data['customer'].replace(' ', '_')}_{datetime.now(ZoneInfo('Europe/Berlin')).strftime('%Y%m%d_%H%M%S')}.csv" - ) - -@app.route("/licenses") -@login_required -def licenses(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/license/edit/", methods=["GET", "POST"]) -@login_required -def edit_license(license_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute(""" - SELECT license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit - FROM licenses WHERE id = %s - """, (license_id,)) - old_license = cur.fetchone() - - # Update license - license_key = request.form["license_key"] - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - valid_until = request.form["valid_until"] - is_active = request.form.get("is_active") == "on" - is_test = request.form.get("is_test") == "on" - device_limit = int(request.form.get("device_limit", 3)) - - cur.execute(""" - UPDATE licenses - SET license_key = %s, license_type = %s, valid_from = %s, - valid_until = %s, is_active = %s, is_test = %s, device_limit = %s - WHERE id = %s - """, (license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit, license_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'license_key': old_license[0], - 'license_type': old_license[1], - 'valid_from': str(old_license[2]), - 'valid_until': str(old_license[3]), - 'is_active': old_license[4], - 'is_test': old_license[5], - 'device_limit': old_license[6] - }, - new_values={ - 'license_key': license_key, - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'is_active': is_active, - 'is_test': is_test, - 'device_limit': device_limit - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei wenn vorhanden - if request.referrer and 'customer_id=' in request.referrer: - import re - match = re.search(r'customer_id=(\d+)', request.referrer) - if match: - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={match.group(1)}" - - return redirect(redirect_url) - - # Get license data - cur.execute(""" - SELECT l.id, l.license_key, c.name, c.email, l.license_type, - l.valid_from, l.valid_until, l.is_active, c.id, l.is_test, l.device_limit - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - - license = cur.fetchone() - cur.close() - conn.close() - - if not license: - return redirect("/licenses") - - return render_template("edit_license.html", license=license, username=session.get('username')) - -@app.route("/license/delete/", methods=["POST"]) -@login_required -def delete_license(license_id): - conn = get_connection() - cur = conn.cursor() - - # Lizenzdetails für Audit-Log abrufen - cur.execute(""" - SELECT l.license_key, c.name, l.license_type - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - license_info = cur.fetchone() - - cur.execute("DELETE FROM licenses WHERE id = %s", (license_id,)) - - conn.commit() - - # Audit-Log - if license_info: - log_audit('DELETE', 'license', license_id, - old_values={ - 'license_key': license_info[0], - 'customer_name': license_info[1], - 'license_type': license_info[2] - }) - - cur.close() - conn.close() - - return redirect("/licenses") - -@app.route("/customers") -@login_required -def customers(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/customer/edit/", methods=["GET", "POST"]) -@login_required -def edit_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - old_customer = cur.fetchone() - - # Update customer - name = request.form["name"] - email = request.form["email"] - is_test = request.form.get("is_test") == "on" - - cur.execute(""" - UPDATE customers - SET name = %s, email = %s, is_test = %s - WHERE id = %s - """, (name, email, is_test, customer_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'customer', customer_id, - old_values={ - 'name': old_customer[0], - 'email': old_customer[1], - 'is_test': old_customer[2] - }, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei (immer der aktuelle Kunde) - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={customer_id}" - - return redirect(redirect_url) - - # Get customer data with licenses - cur.execute(""" - SELECT id, name, email, created_at, is_test FROM customers WHERE id = %s - """, (customer_id,)) - - customer = cur.fetchone() - if not customer: - cur.close() - conn.close() - return "Kunde nicht gefunden", 404 - - - # Get customer's licenses - cur.execute(""" - SELECT id, license_key, license_type, valid_from, valid_until, is_active - FROM licenses - WHERE customer_id = %s - ORDER BY valid_until DESC - """, (customer_id,)) - - licenses = cur.fetchall() - - cur.close() - conn.close() - - if not customer: - return redirect("/customers-licenses") - - return render_template("edit_customer.html", customer=customer, licenses=licenses, username=session.get('username')) - -@app.route("/customer/create", methods=["GET", "POST"]) -@login_required -def create_customer(): - """Erstellt einen neuen Kunden ohne Lizenz""" - if request.method == "POST": - name = request.form.get('name') - email = request.form.get('email') - is_test = request.form.get('is_test') == 'on' - - if not name or not email: - flash("Name und E-Mail sind Pflichtfelder!", "error") - return render_template("create_customer.html", username=session.get('username')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfen ob E-Mail bereits existiert - cur.execute("SELECT id, name FROM customers WHERE email = %s", (email,)) - existing = cur.fetchone() - if existing: - flash(f"Ein Kunde mit der E-Mail '{email}' existiert bereits: {existing[1]}", "error") - return render_template("create_customer.html", username=session.get('username')) - - # Kunde erstellen - cur.execute(""" - INSERT INTO customers (name, email, created_at, is_test) - VALUES (%s, %s, %s, %s) RETURNING id - """, (name, email, datetime.now(), is_test)) - - customer_id = cur.fetchone()[0] - conn.commit() - - # Audit-Log - log_audit('CREATE', 'customer', customer_id, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - flash(f"Kunde '{name}' wurde erfolgreich angelegt!", "success") - return redirect(f"/customer/edit/{customer_id}") - - except Exception as e: - conn.rollback() - flash(f"Fehler beim Anlegen des Kunden: {str(e)}", "error") - return render_template("create_customer.html", username=session.get('username')) - finally: - cur.close() - conn.close() - - # GET Request - Formular anzeigen - return render_template("create_customer.html", username=session.get('username')) - -@app.route("/customer/delete/", methods=["POST"]) -@login_required -def delete_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - # Prüfen ob Kunde Lizenzen hat - cur.execute("SELECT COUNT(*) FROM licenses WHERE customer_id = %s", (customer_id,)) - license_count = cur.fetchone()[0] - - if license_count > 0: - # Kunde hat Lizenzen - nicht löschen - cur.close() - conn.close() - return redirect("/customers") - - # Kundendetails für Audit-Log abrufen - cur.execute("SELECT name, email FROM customers WHERE id = %s", (customer_id,)) - customer_info = cur.fetchone() - - # Kunde löschen wenn keine Lizenzen vorhanden - cur.execute("DELETE FROM customers WHERE id = %s", (customer_id,)) - - conn.commit() - - # Audit-Log - if customer_info: - log_audit('DELETE', 'customer', customer_id, - old_values={ - 'name': customer_info[0], - 'email': customer_info[1] - }) - - cur.close() - conn.close() - - return redirect("/customers") - -@app.route("/customers-licenses") -@login_required -def customers_licenses(): - """Kombinierte Ansicht für Kunden und deren Lizenzen""" - conn = get_connection() - cur = conn.cursor() - - # Hole alle Kunden mit Lizenzstatistiken (inkl. Testkunden wenn gewünscht) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - query = """ - SELECT - c.id, - c.name, - c.email, - c.created_at, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - """ - - if not show_test: - query += " WHERE c.is_test = FALSE" - - query += """ - GROUP BY c.id, c.name, c.email, c.created_at - ORDER BY c.name - """ - - cur.execute(query) - customers = cur.fetchall() - - # Hole ausgewählten Kunden nur wenn explizit in URL angegeben - selected_customer_id = request.args.get('customer_id', type=int) - licenses = [] - selected_customer = None - - if customers and selected_customer_id: - # Hole Daten des ausgewählten Kunden - for customer in customers: - if customer[0] == selected_customer_id: - selected_customer = customer - break - - # Hole Lizenzen des ausgewählten Kunden - if selected_customer: - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (selected_customer_id,)) - licenses = cur.fetchall() - - cur.close() - conn.close() - - return render_template("customers_licenses.html", - customers=customers, - selected_customer=selected_customer, - selected_customer_id=selected_customer_id, - licenses=licenses, - show_test=show_test) - -@app.route("/api/customer//licenses") -@login_required -def api_customer_licenses(customer_id): - """API-Endpoint für AJAX-Abruf der Lizenzen eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Lizenzen des Kunden - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (customer_id,)) - - licenses = [] - for row in cur.fetchall(): - license_id = row[0] - - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for res_row in cur.fetchall(): - resource_info = { - 'id': res_row[0], - 'value': res_row[2], - 'assigned_at': res_row[3].strftime('%d.%m.%Y') if res_row[3] else '' - } - - if res_row[1] == 'domain': - resources['domains'].append(resource_info) - elif res_row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif res_row[1] == 'phone': - resources['phones'].append(resource_info) - - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'license_type': row[2], - 'valid_from': row[3].strftime('%d.%m.%Y') if row[3] else '', - 'valid_until': row[4].strftime('%d.%m.%Y') if row[4] else '', - 'is_active': row[5], - 'status': row[6], - 'domain_count': row[7], # limit - 'ipv4_count': row[8], # limit - 'phone_count': row[9], # limit - 'device_limit': row[10], - 'active_devices': row[11], - 'actual_domain_count': row[12], # actual count - 'actual_ipv4_count': row[13], # actual count - 'actual_phone_count': row[14], # actual count - 'resources': resources - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'licenses': licenses, - 'count': len(licenses) - }) - -@app.route("/api/customer//quick-stats") -@login_required -def api_customer_quick_stats(customer_id): - """API-Endpoint für Schnellstatistiken eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Kundenstatistiken - cur.execute(""" - SELECT - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' AND l.valid_until >= CURRENT_DATE THEN 1 END) as expiring_soon - FROM licenses l - WHERE l.customer_id = %s - """, (customer_id,)) - - stats = cur.fetchone() - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'stats': { - 'total': stats[0], - 'active': stats[1], - 'expired': stats[2], - 'expiring_soon': stats[3] - } - }) - -@app.route("/api/license//quick-edit", methods=['POST']) -@login_required -def api_license_quick_edit(license_id): - """API-Endpoint für schnelle Lizenz-Bearbeitung""" - conn = get_connection() - cur = conn.cursor() - - try: - data = request.get_json() - - # Hole alte Werte für Audit-Log - cur.execute(""" - SELECT is_active, valid_until, license_type - FROM licenses WHERE id = %s - """, (license_id,)) - old_values = cur.fetchone() - - if not old_values: - return jsonify({'success': False, 'error': 'Lizenz nicht gefunden'}), 404 - - # Update-Felder vorbereiten - updates = [] - params = [] - new_values = {} - - if 'is_active' in data: - updates.append("is_active = %s") - params.append(data['is_active']) - new_values['is_active'] = data['is_active'] - - if 'valid_until' in data: - updates.append("valid_until = %s") - params.append(data['valid_until']) - new_values['valid_until'] = data['valid_until'] - - if 'license_type' in data: - updates.append("license_type = %s") - params.append(data['license_type']) - new_values['license_type'] = data['license_type'] - - if updates: - params.append(license_id) - cur.execute(f""" - UPDATE licenses - SET {', '.join(updates)} - WHERE id = %s - """, params) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'is_active': old_values[0], - 'valid_until': old_values[1].isoformat() if old_values[1] else None, - 'license_type': old_values[2] - }, - new_values=new_values) - - cur.close() - conn.close() - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/api/license//resources") -@login_required -def api_license_resources(license_id): - """API-Endpoint für detaillierte Ressourcen-Informationen einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for row in cur.fetchall(): - resource_info = { - 'id': row[0], - 'value': row[2], - 'assigned_at': row[3].strftime('%d.%m.%Y') if row[3] else '' - } - - if row[1] == 'domain': - resources['domains'].append(resource_info) - elif row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif row[1] == 'phone': - resources['phones'].append(resource_info) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'resources': resources - }) - - except Exception as e: - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/sessions") -@login_required -def sessions(): - conn = get_connection() - cur = conn.cursor() - - # Sortierparameter - active_sort = request.args.get('active_sort', 'last_heartbeat') - active_order = request.args.get('active_order', 'desc') - ended_sort = request.args.get('ended_sort', 'ended_at') - ended_order = request.args.get('ended_order', 'desc') - - # Whitelist für erlaubte Sortierfelder - Aktive Sessions - active_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'last_heartbeat': 's.last_heartbeat', - 'inactive': 'minutes_inactive' - } - - # Whitelist für erlaubte Sortierfelder - Beendete Sessions - ended_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'ended_at': 's.ended_at', - 'duration': 'duration_minutes' - } - - # Validierung - if active_sort not in active_sort_fields: - active_sort = 'last_heartbeat' - if ended_sort not in ended_sort_fields: - ended_sort = 'ended_at' - if active_order not in ['asc', 'desc']: - active_order = 'desc' - if ended_order not in ['asc', 'desc']: - ended_order = 'desc' - - # Aktive Sessions abrufen - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.user_agent, s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.last_heartbeat))/60 as minutes_inactive - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = TRUE - ORDER BY {active_sort_fields[active_sort]} {active_order.upper()} - """) - active_sessions = cur.fetchall() - - # Inaktive Sessions der letzten 24 Stunden - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))/60 as duration_minutes - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = FALSE - AND s.ended_at > NOW() - INTERVAL '24 hours' - ORDER BY {ended_sort_fields[ended_sort]} {ended_order.upper()} - LIMIT 50 - """) - recent_sessions = cur.fetchall() - - cur.close() - conn.close() - - return render_template("sessions.html", - active_sessions=active_sessions, - recent_sessions=recent_sessions, - active_sort=active_sort, - active_order=active_order, - ended_sort=ended_sort, - ended_order=ended_order, - username=session.get('username')) - -@app.route("/session/end/", methods=["POST"]) -@login_required -def end_session(session_id): - conn = get_connection() - cur = conn.cursor() - - # Session beenden - cur.execute(""" - UPDATE sessions - SET is_active = FALSE, ended_at = NOW() - WHERE id = %s AND is_active = TRUE - """, (session_id,)) - - conn.commit() - cur.close() - conn.close() - - return redirect("/sessions") - -@app.route("/export/licenses") -@login_required -def export_licenses(): - conn = get_connection() - cur = conn.cursor() - - # Alle Lizenzen mit Kundeninformationen abrufen (ohne Testdaten, außer explizit gewünscht) - include_test = request.args.get('include_test', 'false').lower() == 'true' - customer_id = request.args.get('customer_id', type=int) - - query = """ - SELECT l.id, l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type, l.valid_from, l.valid_until, l.is_active, l.is_test, - CASE - WHEN l.is_active = FALSE THEN 'Deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'Abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'Läuft bald ab' - ELSE 'Aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - """ - - # Build WHERE clause - where_conditions = [] - params = [] - - if not include_test: - where_conditions.append("l.is_test = FALSE") - - if customer_id: - where_conditions.append("l.customer_id = %s") - params.append(customer_id) - - if where_conditions: - query += " WHERE " + " AND ".join(where_conditions) - - query += " ORDER BY l.id" - - cur.execute(query, params) - - # Spaltennamen - columns = ['ID', 'Lizenzschlüssel', 'Kunde', 'E-Mail', 'Typ', - 'Gültig von', 'Gültig bis', 'Aktiv', 'Testdaten', 'Status'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Gültig von'] = pd.to_datetime(df['Gültig von']).dt.strftime('%d.%m.%Y') - df['Gültig bis'] = pd.to_datetime(df['Gültig bis']).dt.strftime('%d.%m.%Y') - - # Typ und Aktiv Status anpassen - df['Typ'] = df['Typ'].replace({'full': 'Vollversion', 'test': 'Testversion'}) - df['Aktiv'] = df['Aktiv'].replace({True: 'Ja', False: 'Nein'}) - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'license', - additional_info=f"Export aller Lizenzen als {export_format.upper()}") - filename = f'lizenzen_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Lizenzen', index=False) - - # Formatierung - worksheet = writer.sheets['Lizenzen'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/audit") -@login_required -def export_audit(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_user = request.args.get('user', '') - filter_action = request.args.get('action', '') - filter_entity = request.args.get('entity', '') - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - params = [] - - if filter_user: - query += " AND username ILIKE %s" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - query += " ORDER BY timestamp DESC" - - cur.execute(query, params) - audit_logs = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for log in audit_logs: - action_text = { - 'CREATE': 'Erstellt', - 'UPDATE': 'Bearbeitet', - 'DELETE': 'Gelöscht', - 'LOGIN': 'Anmeldung', - 'LOGOUT': 'Abmeldung', - 'AUTO_LOGOUT': 'Auto-Logout', - 'EXPORT': 'Export', - 'GENERATE_KEY': 'Key generiert', - 'CREATE_BATCH': 'Batch erstellt', - 'BACKUP': 'Backup erstellt', - 'LOGIN_2FA_SUCCESS': '2FA-Anmeldung', - 'LOGIN_2FA_BACKUP': '2FA-Backup-Code', - 'LOGIN_2FA_FAILED': '2FA-Fehlgeschlagen', - 'LOGIN_BLOCKED': 'Login-Blockiert', - 'RESTORE': 'Wiederhergestellt', - 'PASSWORD_CHANGE': 'Passwort geändert', - '2FA_ENABLED': '2FA aktiviert', - '2FA_DISABLED': '2FA deaktiviert' - }.get(log[3], log[3]) - - data.append({ - 'ID': log[0], - 'Zeitstempel': log[1].strftime('%d.%m.%Y %H:%M:%S'), - 'Benutzer': log[2], - 'Aktion': action_text, - 'Entität': log[4], - 'Entität-ID': log[5] or '', - 'IP-Adresse': log[8] or '', - 'Zusatzinfo': log[10] or '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'audit_log_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'audit_log', - additional_info=f"{export_format.upper()} Export mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Audit Log') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Audit Log'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/customers") -@login_required -def export_customers(): - conn = get_connection() - cur = conn.cursor() - - # Check if test data should be included - include_test = request.args.get('include_test', 'false').lower() == 'true' - - # Build query based on test data filter - if include_test: - # Include all customers - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - else: - # Exclude test customers and test licenses - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(CASE WHEN l.is_test = FALSE THEN 1 END) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.is_test = FALSE - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - - cur.execute(query) - - # Spaltennamen - columns = ['ID', 'Name', 'E-Mail', 'Erstellt am', 'Testdaten', - 'Lizenzen gesamt', 'Aktive Lizenzen', 'Abgelaufene Lizenzen'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Erstellt am'] = pd.to_datetime(df['Erstellt am']).dt.strftime('%d.%m.%Y %H:%M') - - # Testdaten formatting - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'customer', - additional_info=f"Export aller Kunden als {export_format.upper()}") - filename = f'kunden_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Kunden', index=False) - - # Formatierung - worksheet = writer.sheets['Kunden'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/sessions") -@login_required -def export_sessions(): - conn = get_connection() - cur = conn.cursor() - - # Holen des Session-Typs (active oder ended) - session_type = request.args.get('type', 'active') - export_format = request.args.get('format', 'excel') - - # Daten je nach Typ abrufen - if session_type == 'active': - # Aktive Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = true - ORDER BY s.last_heartbeat DESC - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Letzte Aktivität': sess[5].strftime('%d.%m.%Y %H:%M:%S'), - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Aktive Sessions' - filename_prefix = 'aktive_sessions' - else: - # Beendete Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = false AND s.ended_at IS NOT NULL - ORDER BY s.ended_at DESC - LIMIT 1000 - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] if sess[6] else 0 - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Endzeit': sess[5].strftime('%d.%m.%Y %H:%M:%S') if sess[5] else '', - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Beendete Sessions' - filename_prefix = 'beendete_sessions' - - cur.close() - conn.close() - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'{filename_prefix}_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'sessions', - additional_info=f"{export_format.upper()} Export von {session_type} Sessions mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name=sheet_name) - - # Spaltenbreiten anpassen - worksheet = writer.sheets[sheet_name] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/resources") -@login_required -def export_resources(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_type = request.args.get('type', '') - filter_status = request.args.get('status', '') - search_query = request.args.get('search', '') - show_test = request.args.get('show_test', 'false').lower() == 'true' - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT r.id, r.resource_type, r.resource_value, r.status, r.allocated_to_license, - r.created_at, r.status_changed_at, - l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type - FROM resource_pools r - LEFT JOIN licenses l ON r.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE 1=1 - """ - params = [] - - # Filter für Testdaten - if not show_test: - query += " AND (r.is_test = false OR r.is_test IS NULL)" - - # Filter für Ressourcentyp - if filter_type: - query += " AND r.resource_type = %s" - params.append(filter_type) - - # Filter für Status - if filter_status: - query += " AND r.status = %s" - params.append(filter_status) - - # Suchfilter - if search_query: - query += " AND (r.resource_value ILIKE %s OR l.license_key ILIKE %s OR c.name ILIKE %s)" - params.extend([f'%{search_query}%', f'%{search_query}%', f'%{search_query}%']) - - query += " ORDER BY r.id DESC" - - cur.execute(query, params) - resources = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for res in resources: - status_text = { - 'available': 'Verfügbar', - 'allocated': 'Zugewiesen', - 'quarantine': 'Quarantäne' - }.get(res[3], res[3]) - - type_text = { - 'domain': 'Domain', - 'ipv4': 'IPv4', - 'phone': 'Telefon' - }.get(res[1], res[1]) - - data.append({ - 'ID': res[0], - 'Typ': type_text, - 'Ressource': res[2], - 'Status': status_text, - 'Lizenzschlüssel': res[7] or '', - 'Kunde': res[8] or '', - 'Kunden-Email': res[9] or '', - 'Lizenztyp': res[10] or '', - 'Erstellt am': res[5].strftime('%d.%m.%Y %H:%M:%S') if res[5] else '', - 'Zugewiesen am': res[6].strftime('%d.%m.%Y %H:%M:%S') if res[6] else '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'resources_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'resources', - additional_info=f"{export_format.upper()} Export mit {len(data)} Ressourcen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Resources') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Resources'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/audit") -@login_required -def audit_log(): - conn = get_connection() - cur = conn.cursor() - - # Parameter - filter_user = request.args.get('user', '').strip() - filter_action = request.args.get('action', '').strip() - filter_entity = request.args.get('entity', '').strip() - page = request.args.get('page', 1, type=int) - sort = request.args.get('sort', 'timestamp') - order = request.args.get('order', 'desc') - per_page = 50 - - # Whitelist für erlaubte Sortierfelder - allowed_sort_fields = { - 'timestamp': 'timestamp', - 'username': 'username', - 'action': 'action', - 'entity': 'entity_type', - 'ip': 'ip_address' - } - - # Validierung - if sort not in allowed_sort_fields: - sort = 'timestamp' - if order not in ['asc', 'desc']: - order = 'desc' - - sort_field = allowed_sort_fields[sort] - - # SQL Query mit optionalen Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - - params = [] - - # Filter - if filter_user: - query += " AND LOWER(username) LIKE LOWER(%s)" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - # Gesamtanzahl für Pagination - count_query = "SELECT COUNT(*) FROM (" + query + ") as count_table" - cur.execute(count_query, params) - total = cur.fetchone()[0] - - # Pagination - offset = (page - 1) * per_page - query += f" ORDER BY {sort_field} {order.upper()} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - logs = cur.fetchall() - - # JSON-Werte parsen - parsed_logs = [] - for log in logs: - parsed_log = list(log) - # old_values und new_values sind bereits Dictionaries (JSONB) - # Keine Konvertierung nötig - parsed_logs.append(parsed_log) - - # Pagination Info - total_pages = (total + per_page - 1) // per_page - - cur.close() - conn.close() - - return render_template("audit_log.html", - logs=parsed_logs, - filter_user=filter_user, - filter_action=filter_action, - filter_entity=filter_entity, - page=page, - total_pages=total_pages, - total=total, - sort=sort, - order=order, - username=session.get('username')) - -@app.route("/backups") -@login_required -def backups(): - """Zeigt die Backup-Historie an""" - conn = get_connection() - cur = conn.cursor() - - # Letztes erfolgreiches Backup für Dashboard - cur.execute(""" - SELECT created_at, filesize, duration_seconds - FROM backup_history - WHERE status = 'success' - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup = cur.fetchone() - - # Alle Backups abrufen - cur.execute(""" - SELECT id, filename, filesize, backup_type, status, error_message, - created_at, created_by, tables_count, records_count, - duration_seconds, is_encrypted - FROM backup_history - ORDER BY created_at DESC - """) - backups = cur.fetchall() - - cur.close() - conn.close() - - return render_template("backups.html", - backups=backups, - last_backup=last_backup, - username=session.get('username')) - -@app.route("/backup/create", methods=["POST"]) -@login_required -def create_backup_route(): - """Erstellt ein manuelles Backup""" - username = session.get('username') - success, result = create_backup(backup_type="manual", created_by=username) - - if success: - return jsonify({ - 'success': True, - 'message': f'Backup erfolgreich erstellt: {result}' - }) - else: - return jsonify({ - 'success': False, - 'message': f'Backup fehlgeschlagen: {result}' - }), 500 - -@app.route("/backup/restore/", methods=["POST"]) -@login_required -def restore_backup_route(backup_id): - """Stellt ein Backup wieder her""" - encryption_key = request.form.get('encryption_key') - - success, message = restore_backup(backup_id, encryption_key) - - if success: - return jsonify({ - 'success': True, - 'message': message - }) - else: - return jsonify({ - 'success': False, - 'message': message - }), 500 - -@app.route("/backup/download/") -@login_required -def download_backup(backup_id): - """Lädt eine Backup-Datei herunter""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - cur.close() - conn.close() - - if not backup_info: - return "Backup nicht gefunden", 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - if not filepath.exists(): - return "Backup-Datei nicht gefunden", 404 - - # Audit-Log - log_audit('DOWNLOAD', 'backup', backup_id, - additional_info=f"Backup heruntergeladen: {filename}") - - return send_file(filepath, as_attachment=True, download_name=filename) - -@app.route("/backup/delete/", methods=["DELETE"]) -@login_required -def delete_backup(backup_id): - """Löscht ein Backup""" - conn = get_connection() - cur = conn.cursor() - - try: - # Backup-Informationen abrufen - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - if not backup_info: - return jsonify({ - 'success': False, - 'message': 'Backup nicht gefunden' - }), 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - # Datei löschen, wenn sie existiert - if filepath.exists(): - filepath.unlink() - - # Aus Datenbank löschen - cur.execute(""" - DELETE FROM backup_history - WHERE id = %s - """, (backup_id,)) - - conn.commit() - - # Audit-Log - log_audit('DELETE', 'backup', backup_id, - additional_info=f"Backup gelöscht: {filename}") - - return jsonify({ - 'success': True, - 'message': f'Backup "{filename}" wurde erfolgreich gelöscht' - }) - - except Exception as e: - conn.rollback() - return jsonify({ - 'success': False, - 'message': f'Fehler beim Löschen des Backups: {str(e)}' - }), 500 - finally: - cur.close() - conn.close() - -@app.route("/security/blocked-ips") -@login_required -def blocked_ips(): - """Zeigt alle gesperrten IPs an""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT - ip_address, - attempt_count, - first_attempt, - last_attempt, - blocked_until, - last_username_tried, - last_error_message - FROM login_attempts - WHERE blocked_until IS NOT NULL - ORDER BY blocked_until DESC - """) - - blocked_ips_list = [] - for ip in cur.fetchall(): - blocked_ips_list.append({ - 'ip_address': ip[0], - 'attempt_count': ip[1], - 'first_attempt': ip[2].strftime('%d.%m.%Y %H:%M'), - 'last_attempt': ip[3].strftime('%d.%m.%Y %H:%M'), - 'blocked_until': ip[4].strftime('%d.%m.%Y %H:%M'), - 'is_active': ip[4] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None), - 'last_username': ip[5], - 'last_error': ip[6] - }) - - cur.close() - conn.close() - - return render_template("blocked_ips.html", - blocked_ips=blocked_ips_list, - username=session.get('username')) - -@app.route("/security/unblock-ip", methods=["POST"]) -@login_required -def unblock_ip(): - """Entsperrt eine IP-Adresse""" - ip_address = request.form.get('ip_address') - - if ip_address: - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - UPDATE login_attempts - SET blocked_until = NULL - WHERE ip_address = %s - """, (ip_address,)) - - conn.commit() - cur.close() - conn.close() - - # Audit-Log - log_audit('UNBLOCK_IP', 'security', - additional_info=f"IP {ip_address} manuell entsperrt") - - return redirect(url_for('blocked_ips')) - -@app.route("/security/clear-attempts", methods=["POST"]) -@login_required -def clear_attempts(): - """Löscht alle Login-Versuche für eine IP""" - ip_address = request.form.get('ip_address') - - if ip_address: - reset_login_attempts(ip_address) - - # Audit-Log - log_audit('CLEAR_ATTEMPTS', 'security', - additional_info=f"Login-Versuche für IP {ip_address} zurückgesetzt") - - return redirect(url_for('blocked_ips')) - -# API Endpoints for License Management -@app.route("/api/license//toggle", methods=["POST"]) -@login_required -def toggle_license_api(license_id): - """Toggle license active status via API""" - try: - data = request.get_json() - is_active = data.get('is_active', False) - - conn = get_connection() - cur = conn.cursor() - - # Update license status - cur.execute(""" - UPDATE licenses - SET is_active = %s - WHERE id = %s - """, (is_active, license_id)) - - conn.commit() - - # Log the action - log_audit('UPDATE', 'license', license_id, - new_values={'is_active': is_active}, - additional_info=f"Lizenz {'aktiviert' if is_active else 'deaktiviert'} via Toggle") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Status erfolgreich geändert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-activate", methods=["POST"]) -@login_required -def bulk_activate_licenses(): - """Activate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = TRUE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': True, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen aktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen aktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-deactivate", methods=["POST"]) -@login_required -def bulk_deactivate_licenses(): - """Deactivate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = FALSE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': False, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen deaktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen deaktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/license//devices") -@login_required -def get_license_devices(license_id): - """Hole alle registrierten Geräte einer Lizenz""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und hole device_limit - cur.execute(""" - SELECT device_limit FROM licenses WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit = license_data[0] - - # Hole alle Geräte für diese Lizenz - cur.execute(""" - SELECT id, hardware_id, device_name, operating_system, - first_seen, last_seen, is_active, ip_address - FROM device_registrations - WHERE license_id = %s - ORDER BY is_active DESC, last_seen DESC - """, (license_id,)) - - devices = [] - for row in cur.fetchall(): - devices.append({ - 'id': row[0], - 'hardware_id': row[1], - 'device_name': row[2] or 'Unbekanntes Gerät', - 'operating_system': row[3] or 'Unbekannt', - 'first_seen': row[4].strftime('%d.%m.%Y %H:%M') if row[4] else '', - 'last_seen': row[5].strftime('%d.%m.%Y %H:%M') if row[5] else '', - 'is_active': row[6], - 'ip_address': row[7] or '-' - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'devices': devices, - 'device_limit': device_limit, - 'active_count': sum(1 for d in devices if d['is_active']) - }) - - except Exception as e: - logging.error(f"Fehler beim Abrufen der Geräte: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Abrufen der Geräte'}), 500 - -@app.route("/api/license//register-device", methods=["POST"]) -def register_device(license_id): - """Registriere ein neues Gerät für eine Lizenz""" - try: - data = request.get_json() - hardware_id = data.get('hardware_id') - device_name = data.get('device_name', '') - operating_system = data.get('operating_system', '') - - if not hardware_id: - return jsonify({'success': False, 'message': 'Hardware-ID fehlt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und aktiv ist - cur.execute(""" - SELECT device_limit, is_active, valid_until - FROM licenses - WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit, is_active, valid_until = license_data - - # Prüfe ob Lizenz aktiv und gültig ist - if not is_active: - return jsonify({'success': False, 'message': 'Lizenz ist deaktiviert'}), 403 - - if valid_until < datetime.now(ZoneInfo("Europe/Berlin")).date(): - return jsonify({'success': False, 'message': 'Lizenz ist abgelaufen'}), 403 - - # Prüfe ob Gerät bereits registriert ist - cur.execute(""" - SELECT id, is_active FROM device_registrations - WHERE license_id = %s AND hardware_id = %s - """, (license_id, hardware_id)) - existing_device = cur.fetchone() - - if existing_device: - device_id, is_device_active = existing_device - if is_device_active: - # Gerät ist bereits aktiv, update last_seen - cur.execute(""" - UPDATE device_registrations - SET last_seen = CURRENT_TIMESTAMP, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät bereits registriert', 'device_id': device_id}) - else: - # Gerät war deaktiviert, prüfe ob wir es reaktivieren können - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Reaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = TRUE, - last_seen = CURRENT_TIMESTAMP, - deactivated_at = NULL, - deactivated_by = NULL, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät reaktiviert', 'device_id': device_id}) - - # Neues Gerät - prüfe Gerätelimit - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Registriere neues Gerät - cur.execute(""" - INSERT INTO device_registrations - (license_id, hardware_id, device_name, operating_system, ip_address, user_agent) - VALUES (%s, %s, %s, %s, %s, %s) - RETURNING id - """, (license_id, hardware_id, device_name, operating_system, - get_client_ip(), request.headers.get('User-Agent', ''))) - device_id = cur.fetchone()[0] - - conn.commit() - - # Audit Log - log_audit('DEVICE_REGISTER', 'device', device_id, - new_values={'license_id': license_id, 'hardware_id': hardware_id}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich registriert', 'device_id': device_id}) - - except Exception as e: - logging.error(f"Fehler bei Geräte-Registrierung: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler bei der Registrierung'}), 500 - -@app.route("/api/license//deactivate-device/", methods=["POST"]) -@login_required -def deactivate_device(license_id, device_id): - """Deaktiviere ein registriertes Gerät""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob das Gerät zu dieser Lizenz gehört - cur.execute(""" - SELECT id FROM device_registrations - WHERE id = %s AND license_id = %s AND is_active = TRUE - """, (device_id, license_id)) - - if not cur.fetchone(): - return jsonify({'success': False, 'message': 'Gerät nicht gefunden oder bereits deaktiviert'}), 404 - - # Deaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = FALSE, - deactivated_at = CURRENT_TIMESTAMP, - deactivated_by = %s - WHERE id = %s - """, (session['username'], device_id)) - - conn.commit() - - # Audit Log - log_audit('DEVICE_DEACTIVATE', 'device', device_id, - old_values={'is_active': True}, - new_values={'is_active': False}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich deaktiviert'}) - - except Exception as e: - logging.error(f"Fehler beim Deaktivieren des Geräts: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Deaktivieren'}), 500 - -@app.route("/api/licenses/bulk-delete", methods=["POST"]) -@login_required -def bulk_delete_licenses(): - """Delete multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Get license info for audit log (nur Live-Daten) - cur.execute(""" - SELECT license_key - FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - license_keys = [row[0] for row in cur.fetchall()] - - # Delete all selected licenses (nur Live-Daten) - cur.execute(""" - DELETE FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_DELETE', 'licenses', None, - old_values={'license_keys': license_keys, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen gelöscht") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen gelöscht'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# ===================== RESOURCE POOL MANAGEMENT ===================== - -@app.route('/resources') -@login_required -def resources(): - """Resource Pool Hauptübersicht""" - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Testdaten angezeigt werden sollen (gleiche Logik wie bei Kunden) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - # Statistiken abrufen - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = %s - GROUP BY resource_type - """, (show_test,)) - - stats = {} - for row in cur.fetchall(): - stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - } - - # Letzte Aktivitäten (gefiltert nach Test/Live) - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rp.resource_type, - rp.resource_value, - rh.details - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - WHERE rp.is_test = %s - ORDER BY rh.action_at DESC - LIMIT 10 - """, (show_test,)) - recent_activities = cur.fetchall() - - # Ressourcen-Liste mit Pagination - page = request.args.get('page', 1, type=int) - per_page = 50 - offset = (page - 1) * per_page - - resource_type = request.args.get('type', '') - status_filter = request.args.get('status', '') - search = request.args.get('search', '') - - # Sortierung - sort_by = request.args.get('sort', 'id') - sort_order = request.args.get('order', 'desc') - - # Base Query - query = """ - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - rp.allocated_to_license, - l.license_key, - c.name as customer_name, - rp.status_changed_at, - rp.quarantine_reason, - rp.quarantine_until, - c.id as customer_id - FROM resource_pools rp - LEFT JOIN licenses l ON rp.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rp.is_test = %s - """ - params = [show_test] - - if resource_type: - query += " AND rp.resource_type = %s" - params.append(resource_type) - - if status_filter: - query += " AND rp.status = %s" - params.append(status_filter) - - if search: - query += " AND rp.resource_value ILIKE %s" - params.append(f'%{search}%') - - # Count total - count_query = f"SELECT COUNT(*) FROM ({query}) as cnt" - cur.execute(count_query, params) - total = cur.fetchone()[0] - total_pages = (total + per_page - 1) // per_page - - # Get paginated results with dynamic sorting - sort_column_map = { - 'id': 'rp.id', - 'type': 'rp.resource_type', - 'resource': 'rp.resource_value', - 'status': 'rp.status', - 'assigned': 'c.name', - 'changed': 'rp.status_changed_at' - } - - sort_column = sort_column_map.get(sort_by, 'rp.id') - sort_direction = 'ASC' if sort_order == 'asc' else 'DESC' - - query += f" ORDER BY {sort_column} {sort_direction} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - resources = cur.fetchall() - - cur.close() - conn.close() - - return render_template('resources.html', - stats=stats, - resources=resources, - recent_activities=recent_activities, - page=page, - total_pages=total_pages, - total=total, - resource_type=resource_type, - status_filter=status_filter, - search=search, - show_test=show_test, - sort_by=sort_by, - sort_order=sort_order, - datetime=datetime, - timedelta=timedelta) - -@app.route('/resources/add', methods=['GET', 'POST']) -@login_required -def add_resources(): - """Ressourcen zum Pool hinzufügen""" - # Hole show_test Parameter für die Anzeige - show_test = request.args.get('show_test', 'false').lower() == 'true' - - if request.method == 'POST': - resource_type = request.form.get('resource_type') - resources_text = request.form.get('resources_text', '') - is_test = request.form.get('is_test') == 'on' # Checkbox für Testdaten - - # Parse resources (one per line) - resources = [r.strip() for r in resources_text.split('\n') if r.strip()] - - if not resources: - flash('Keine Ressourcen angegeben', 'error') - return redirect(url_for('add_resources', show_test=show_test)) - - conn = get_connection() - cur = conn.cursor() - - added = 0 - duplicates = 0 - - for resource_value in resources: - try: - cur.execute(""" - INSERT INTO resource_pools (resource_type, resource_value, status_changed_by, is_test) - VALUES (%s, %s, %s, %s) - ON CONFLICT (resource_type, resource_value) DO NOTHING - """, (resource_type, resource_value, session['username'], is_test)) - - if cur.rowcount > 0: - added += 1 - # Get the inserted ID - cur.execute("SELECT id FROM resource_pools WHERE resource_type = %s AND resource_value = %s", - (resource_type, resource_value)) - resource_id = cur.fetchone()[0] - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'created', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - else: - duplicates += 1 - - except Exception as e: - app.logger.error(f"Error adding resource {resource_value}: {e}") - - conn.commit() - cur.close() - conn.close() - - log_audit('CREATE', 'resource_pool', None, - new_values={'type': resource_type, 'added': added, 'duplicates': duplicates, 'is_test': is_test}, - additional_info=f"{added} {'Test-' if is_test else ''}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen") - - flash(f'{added} {"Test-" if is_test else ""}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen', 'success') - return redirect(url_for('resources', show_test=show_test)) - - return render_template('add_resources.html', show_test=show_test) - -@app.route('/resources/quarantine/', methods=['POST']) -@login_required -def quarantine_resource(resource_id): - """Ressource in Quarantäne setzen""" - reason = request.form.get('reason', 'review') - until_date = request.form.get('until_date') - notes = request.form.get('notes', '') - - conn = get_connection() - cur = conn.cursor() - - # Get current resource info - cur.execute("SELECT resource_type, resource_value, status FROM resource_pools WHERE id = %s", (resource_id,)) - resource = cur.fetchone() - - if not resource: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - old_status = resource[2] - - # Update resource - cur.execute(""" - UPDATE resource_pools - SET status = 'quarantine', - quarantine_reason = %s, - quarantine_until = %s, - notes = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (reason, until_date if until_date else None, notes, session['username'], resource_id)) - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address, details) - VALUES (%s, 'quarantined', %s, %s, %s) - """, (resource_id, session['username'], get_client_ip(), - Json({'reason': reason, 'until': until_date, 'notes': notes, 'old_status': old_status}))) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource', resource_id, - old_values={'status': old_status}, - new_values={'status': 'quarantine', 'reason': reason}, - additional_info=f"Ressource {resource[0]}: {resource[1]} in Quarantäne") - - flash('Ressource in Quarantäne gesetzt', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/resources/release', methods=['POST']) -@login_required -def release_resources(): - """Ressourcen aus Quarantäne freigeben""" - resource_ids = request.form.getlist('resource_ids') - - if not resource_ids: - flash('Keine Ressourcen ausgewählt', 'error') - return redirect(url_for('resources')) - - conn = get_connection() - cur = conn.cursor() - - released = 0 - for resource_id in resource_ids: - cur.execute(""" - UPDATE resource_pools - SET status = 'available', - quarantine_reason = NULL, - quarantine_until = NULL, - allocated_to_license = NULL, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s AND status = 'quarantine' - """, (session['username'], resource_id)) - - if cur.rowcount > 0: - released += 1 - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'released', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource_pool', None, - new_values={'released': released}, - additional_info=f"{released} Ressourcen aus Quarantäne freigegeben") - - flash(f'{released} Ressourcen freigegeben', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/api/resources/allocate', methods=['POST']) -@login_required -def allocate_resources_api(): - """API für Ressourcen-Zuweisung bei Lizenzerstellung""" - data = request.json - license_id = data.get('license_id') - domain_count = data.get('domain_count', 1) - ipv4_count = data.get('ipv4_count', 1) - phone_count = data.get('phone_count', 1) - - conn = get_connection() - cur = conn.cursor() - - try: - allocated = {'domains': [], 'ipv4s': [], 'phones': []} - - # Allocate domains - if domain_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' - LIMIT %s FOR UPDATE - """, (domain_count,)) - domains = cur.fetchall() - - if len(domains) < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {len(domains)})") - - for domain_id, domain_value in domains: - # Update resource status - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], domain_id)) - - # Create assignment - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, domain_id, session['username'])) - - # Log history - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (domain_id, license_id, session['username'], get_client_ip())) - - allocated['domains'].append(domain_value) - - # Allocate IPv4s (similar logic) - if ipv4_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' - LIMIT %s FOR UPDATE - """, (ipv4_count,)) - ipv4s = cur.fetchall() - - if len(ipv4s) < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar") - - for ipv4_id, ipv4_value in ipv4s: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], ipv4_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, ipv4_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (ipv4_id, license_id, session['username'], get_client_ip())) - - allocated['ipv4s'].append(ipv4_value) - - # Allocate phones (similar logic) - if phone_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' - LIMIT %s FOR UPDATE - """, (phone_count,)) - phones = cur.fetchall() - - if len(phones) < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar") - - for phone_id, phone_value in phones: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], phone_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, phone_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (phone_id, license_id, session['username'], get_client_ip())) - - allocated['phones'].append(phone_value) - - # Update license resource counts - cur.execute(""" - UPDATE licenses - SET domain_count = %s, - ipv4_count = %s, - phone_count = %s - WHERE id = %s - """, (domain_count, ipv4_count, phone_count, license_id)) - - conn.commit() - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'allocated': allocated - }) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({ - 'success': False, - 'error': str(e) - }), 400 - -@app.route('/api/resources/check-availability', methods=['GET']) -@login_required -def check_resource_availability(): - """Prüft verfügbare Ressourcen""" - resource_type = request.args.get('type', '') - count = request.args.get('count', 10, type=int) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - conn = get_connection() - cur = conn.cursor() - - if resource_type: - # Spezifische Ressourcen für einen Typ - cur.execute(""" - SELECT id, resource_value - FROM resource_pools - WHERE status = 'available' - AND resource_type = %s - AND is_test = %s - ORDER BY resource_value - LIMIT %s - """, (resource_type, show_test, count)) - - resources = [] - for row in cur.fetchall(): - resources.append({ - 'id': row[0], - 'value': row[1] - }) - - cur.close() - conn.close() - - return jsonify({ - 'available': resources, - 'type': resource_type, - 'count': len(resources) - }) - else: - # Zusammenfassung aller Typen - cur.execute(""" - SELECT - resource_type, - COUNT(*) as available - FROM resource_pools - WHERE status = 'available' - AND is_test = %s - GROUP BY resource_type - """, (show_test,)) - - availability = {} - for row in cur.fetchall(): - availability[row[0]] = row[1] - - cur.close() - conn.close() - - return jsonify(availability) - -@app.route('/api/global-search', methods=['GET']) -@login_required -def global_search(): - """Global search API endpoint for searching customers and licenses""" - query = request.args.get('q', '').strip() - - if not query or len(query) < 2: - return jsonify({'customers': [], 'licenses': []}) - - conn = get_connection() - cur = conn.cursor() - - # Search pattern with wildcards - search_pattern = f'%{query}%' - - # Search customers - cur.execute(""" - SELECT id, name, email, company_name - FROM customers - WHERE (LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - OR LOWER(company_name) LIKE LOWER(%s)) - AND is_test = FALSE - ORDER BY name - LIMIT 5 - """, (search_pattern, search_pattern, search_pattern)) - - customers = [] - for row in cur.fetchall(): - customers.append({ - 'id': row[0], - 'name': row[1], - 'email': row[2], - 'company_name': row[3] - }) - - # Search licenses - cur.execute(""" - SELECT l.id, l.license_key, c.name as customer_name - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE LOWER(l.license_key) LIKE LOWER(%s) - AND l.is_test = FALSE - ORDER BY l.created_at DESC - LIMIT 5 - """, (search_pattern,)) - - licenses = [] - for row in cur.fetchall(): - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'customer_name': row[2] - }) - - cur.close() - conn.close() - - return jsonify({ - 'customers': customers, - 'licenses': licenses - }) - -@app.route('/resources/history/') -@login_required -def resource_history(resource_id): - """Zeigt die komplette Historie einer Ressource""" - conn = get_connection() - cur = conn.cursor() - - # Get complete resource info using named columns - cur.execute(""" - SELECT id, resource_type, resource_value, status, allocated_to_license, - status_changed_at, status_changed_by, quarantine_reason, - quarantine_until, created_at, notes - FROM resource_pools - WHERE id = %s - """, (resource_id,)) - row = cur.fetchone() - - if not row: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - # Create resource object with named attributes - resource = { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'allocated_to_license': row[4], - 'status_changed_at': row[5], - 'status_changed_by': row[6], - 'quarantine_reason': row[7], - 'quarantine_until': row[8], - 'created_at': row[9], - 'notes': row[10] - } - - # Get license info if allocated - license_info = None - if resource['allocated_to_license']: - cur.execute("SELECT license_key FROM licenses WHERE id = %s", - (resource['allocated_to_license'],)) - lic = cur.fetchone() - if lic: - license_info = {'license_key': lic[0]} - - # Get history with named columns - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rh.details, - rh.license_id, - rh.ip_address - FROM resource_history rh - WHERE rh.resource_id = %s - ORDER BY rh.action_at DESC - """, (resource_id,)) - - history = [] - for row in cur.fetchall(): - history.append({ - 'action': row[0], - 'action_by': row[1], - 'action_at': row[2], - 'details': row[3], - 'license_id': row[4], - 'ip_address': row[5] - }) - - cur.close() - conn.close() - - # Convert to object-like for template - class ResourceObj: - def __init__(self, data): - for key, value in data.items(): - setattr(self, key, value) - - resource_obj = ResourceObj(resource) - history_objs = [ResourceObj(h) for h in history] - - return render_template('resource_history.html', - resource=resource_obj, - license_info=license_info, - history=history_objs) - -@app.route('/resources/metrics') -@login_required -def resources_metrics(): - """Dashboard für Resource Metrics und Reports""" - conn = get_connection() - cur = conn.cursor() - - # Overall stats with fallback values - cur.execute(""" - SELECT - COUNT(DISTINCT resource_id) as total_resources, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(cost), 0) as total_cost, - COALESCE(SUM(revenue), 0) as total_revenue, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - """) - row = cur.fetchone() - - # Calculate ROI - roi = 0 - if row[2] > 0: # if total_cost > 0 - roi = row[3] / row[2] # revenue / cost - - stats = { - 'total_resources': row[0] or 0, - 'avg_performance': row[1] or 0, - 'total_cost': row[2] or 0, - 'total_revenue': row[3] or 0, - 'total_issues': row[4] or 0, - 'roi': roi - } - - # Performance by type - cur.execute(""" - SELECT - rp.resource_type, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COUNT(DISTINCT rp.id) as resource_count - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY rp.resource_type - ORDER BY rp.resource_type - """) - performance_by_type = cur.fetchall() - - # Utilization data - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) as total, - ROUND(COUNT(*) FILTER (WHERE status = 'allocated') * 100.0 / COUNT(*), 1) as allocated_percent - FROM resource_pools - GROUP BY resource_type - """) - utilization_rows = cur.fetchall() - utilization_data = [ - { - 'type': row[0].upper(), - 'allocated': row[1], - 'total': row[2], - 'allocated_percent': row[3] - } - for row in utilization_rows - ] - - # Top performing resources - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COALESCE(SUM(rm.revenue), 0) as total_revenue, - COALESCE(SUM(rm.cost), 1) as total_cost, - CASE - WHEN COALESCE(SUM(rm.cost), 0) = 0 THEN 0 - ELSE COALESCE(SUM(rm.revenue), 0) / COALESCE(SUM(rm.cost), 1) - END as roi - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rp.status != 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value - HAVING AVG(rm.performance_score) IS NOT NULL - ORDER BY avg_score DESC - LIMIT 10 - """) - top_rows = cur.fetchall() - top_performers = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'avg_score': row[3], - 'roi': row[6] - } - for row in top_rows - ] - - # Resources with issues - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - COALESCE(SUM(rm.issues_count), 0) as total_issues - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rm.issues_count > 0 OR rp.status = 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - HAVING SUM(rm.issues_count) > 0 - ORDER BY total_issues DESC - LIMIT 10 - """) - problem_rows = cur.fetchall() - problem_resources = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'total_issues': row[4] - } - for row in problem_rows - ] - - # Daily metrics for trend chart (last 30 days) - cur.execute(""" - SELECT - metric_date, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY metric_date - ORDER BY metric_date - """) - daily_rows = cur.fetchall() - daily_metrics = [ - { - 'date': row[0].strftime('%d.%m'), - 'performance': float(row[1]), - 'issues': int(row[2]) - } - for row in daily_rows - ] - - cur.close() - conn.close() - - return render_template('resource_metrics.html', - stats=stats, - performance_by_type=performance_by_type, - utilization_data=utilization_data, - top_performers=top_performers, - problem_resources=problem_resources, - daily_metrics=daily_metrics) - -@app.route('/resources/report', methods=['GET']) -@login_required -def resources_report(): - """Generiert Ressourcen-Reports oder zeigt Report-Formular""" - # Prüfe ob Download angefordert wurde - if request.args.get('download') == 'true': - report_type = request.args.get('type', 'usage') - format_type = request.args.get('format', 'excel') - date_from = request.args.get('from', (datetime.now(ZoneInfo("Europe/Berlin")) - timedelta(days=30)).strftime('%Y-%m-%d')) - date_to = request.args.get('to', datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y-%m-%d')) - - conn = get_connection() - cur = conn.cursor() - - if report_type == 'usage': - # Auslastungsreport - query = """ - SELECT - rp.resource_type, - rp.resource_value, - rp.status, - COUNT(DISTINCT rh.license_id) as unique_licenses, - COUNT(rh.id) as total_allocations, - MIN(rh.action_at) as first_used, - MAX(rh.action_at) as last_used - FROM resource_pools rp - LEFT JOIN resource_history rh ON rp.id = rh.resource_id - AND rh.action = 'allocated' - AND rh.action_at BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - ORDER BY rp.resource_type, total_allocations DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Status', 'Unique Lizenzen', 'Gesamt Zuweisungen', 'Erste Nutzung', 'Letzte Nutzung'] - - elif report_type == 'performance': - # Performance-Report - query = """ - SELECT - rp.resource_type, - rp.resource_value, - AVG(rm.performance_score) as avg_performance, - SUM(rm.usage_count) as total_usage, - SUM(rm.revenue) as total_revenue, - SUM(rm.cost) as total_cost, - SUM(rm.revenue - rm.cost) as profit, - SUM(rm.issues_count) as total_issues - FROM resource_pools rp - JOIN resource_metrics rm ON rp.id = rm.resource_id - WHERE rm.metric_date BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value - ORDER BY profit DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Durchschn. Performance', 'Gesamt Nutzung', 'Umsatz', 'Kosten', 'Gewinn', 'Issues'] - - elif report_type == 'compliance': - # Compliance-Report - query = """ - SELECT - rh.action_at, - rh.action, - rh.action_by, - rp.resource_type, - rp.resource_value, - l.license_key, - c.name as customer_name, - rh.ip_address - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - LEFT JOIN licenses l ON rh.license_id = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rh.action_at BETWEEN %s AND %s - ORDER BY rh.action_at DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Zeit', 'Aktion', 'Von', 'Typ', 'Ressource', 'Lizenz', 'Kunde', 'IP-Adresse'] - - else: # inventory report - # Inventar-Report - query = """ - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - GROUP BY resource_type - ORDER BY resource_type - """ - cur.execute(query) - columns = ['Typ', 'Verfügbar', 'Zugeteilt', 'Quarantäne', 'Gesamt'] - - # Convert to DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - cur.close() - conn.close() - - # Generate file - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f"resource_report_{report_type}_{timestamp}" - - if format_type == 'excel': - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Report', index=False) - - # Auto-adjust columns width - worksheet = writer.sheets['Report'] - for column in worksheet.columns: - max_length = 0 - column = [cell for cell in column] - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = (max_length + 2) - worksheet.column_dimensions[column[0].column_letter].width = adjusted_width - - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'excel', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx') - - else: # CSV - output = io.StringIO() - df.to_csv(output, index=False, sep=';', encoding='utf-8-sig') - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'csv', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv') - - # Wenn kein Download, zeige Report-Formular - return render_template('resource_report.html', - datetime=datetime, - timedelta=timedelta, - username=session.get('username')) - -if __name__ == "__main__": - app.run(host="0.0.0.0", port=5000) diff --git a/v2_adminpanel/app_new.py b/v2_adminpanel/app_new.py deleted file mode 100644 index c391073..0000000 --- a/v2_adminpanel/app_new.py +++ /dev/null @@ -1,124 +0,0 @@ -import os -import time -import json -import logging -import requests -from io import BytesIO -from datetime import datetime, timedelta -from zoneinfo import ZoneInfo -from pathlib import Path - -from flask import Flask, render_template, request, redirect, session, url_for, send_file, jsonify, flash -from flask_session import Session -from werkzeug.middleware.proxy_fix import ProxyFix -from apscheduler.schedulers.background import BackgroundScheduler -import pandas as pd -from psycopg2.extras import Json - -# Import our new modules -import config -from db import get_connection, get_db_connection, get_db_cursor, execute_query -from auth.decorators import login_required -from auth.password import hash_password, verify_password -from auth.two_factor import ( - generate_totp_secret, generate_qr_code, verify_totp, - generate_backup_codes, hash_backup_code, verify_backup_code -) -from auth.rate_limiting import ( - get_client_ip, check_ip_blocked, record_failed_attempt, - reset_login_attempts, get_login_attempts -) -from utils.audit import log_audit -from utils.license import generate_license_key, validate_license_key -from utils.backup import create_backup, restore_backup, get_or_create_encryption_key -from utils.export import ( - create_excel_export, format_datetime_for_export, - prepare_license_export_data, prepare_customer_export_data, - prepare_session_export_data, prepare_audit_export_data -) -from models import get_user_by_username - -app = Flask(__name__) -# Load configuration from config module -app.config['SECRET_KEY'] = config.SECRET_KEY -app.config['SESSION_TYPE'] = config.SESSION_TYPE -app.config['JSON_AS_ASCII'] = config.JSON_AS_ASCII -app.config['JSONIFY_MIMETYPE'] = config.JSONIFY_MIMETYPE -app.config['PERMANENT_SESSION_LIFETIME'] = config.PERMANENT_SESSION_LIFETIME -app.config['SESSION_COOKIE_HTTPONLY'] = config.SESSION_COOKIE_HTTPONLY -app.config['SESSION_COOKIE_SECURE'] = config.SESSION_COOKIE_SECURE -app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE -app.config['SESSION_COOKIE_NAME'] = config.SESSION_COOKIE_NAME -app.config['SESSION_REFRESH_EACH_REQUEST'] = config.SESSION_REFRESH_EACH_REQUEST -Session(app) - -# ProxyFix für korrekte IP-Adressen hinter Nginx -app.wsgi_app = ProxyFix( - app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 -) - -# Configuration is now loaded from config module - -# Scheduler für automatische Backups -scheduler = BackgroundScheduler() -scheduler.start() - -# Logging konfigurieren -logging.basicConfig(level=logging.INFO) - - -# Scheduled Backup Job -def scheduled_backup(): - """Führt ein geplantes Backup aus""" - logging.info("Starte geplantes Backup...") - create_backup(backup_type="scheduled", created_by="scheduler") - -# Scheduler konfigurieren - täglich um 3:00 Uhr -scheduler.add_job( - scheduled_backup, - 'cron', - hour=config.SCHEDULER_CONFIG['backup_hour'], - minute=config.SCHEDULER_CONFIG['backup_minute'], - id='daily_backup', - replace_existing=True -) - - -def verify_recaptcha(response): - """Verifiziert die reCAPTCHA v2 Response mit Google""" - secret_key = config.RECAPTCHA_SECRET_KEY - - # Wenn kein Secret Key konfiguriert ist, CAPTCHA als bestanden werten (für PoC) - if not secret_key: - logging.warning("RECAPTCHA_SECRET_KEY nicht konfiguriert - CAPTCHA wird übersprungen") - return True - - # Verifizierung bei Google - try: - verify_url = 'https://www.google.com/recaptcha/api/siteverify' - data = { - 'secret': secret_key, - 'response': response - } - - # Timeout für Request setzen - r = requests.post(verify_url, data=data, timeout=5) - result = r.json() - - # Log für Debugging - if not result.get('success'): - logging.warning(f"reCAPTCHA Validierung fehlgeschlagen: {result.get('error-codes', [])}") - - return result.get('success', False) - - except requests.exceptions.RequestException as e: - logging.error(f"reCAPTCHA Verifizierung fehlgeschlagen: {str(e)}") - # Bei Netzwerkfehlern CAPTCHA als bestanden werten - return True - except Exception as e: - logging.error(f"Unerwarteter Fehler bei reCAPTCHA: {str(e)}") - return False - - -# Now copy all the route handlers from the original file -# Starting from line 693... \ No newline at end of file diff --git a/v2_adminpanel/app_with_duplicates.py b/v2_adminpanel/app_with_duplicates.py deleted file mode 100644 index 5b203fe..0000000 --- a/v2_adminpanel/app_with_duplicates.py +++ /dev/null @@ -1,4462 +0,0 @@ -import os -import sys -import time -import json -import logging -import requests -import re -import random -import base64 -from io import BytesIO -from datetime import datetime, timedelta -from zoneinfo import ZoneInfo -from pathlib import Path - -# Add current directory to Python path to ensure modules can be imported -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from flask import Flask, render_template, request, redirect, session, url_for, send_file, jsonify, flash -from flask_session import Session -from werkzeug.middleware.proxy_fix import ProxyFix -from apscheduler.schedulers.background import BackgroundScheduler -import pandas as pd -from psycopg2.extras import Json - -# Import our new modules -import config -from db import get_connection, get_db_connection, get_db_cursor, execute_query -from auth.decorators import login_required -from auth.password import hash_password, verify_password -from auth.two_factor import ( - generate_totp_secret, generate_qr_code, verify_totp, - generate_backup_codes, hash_backup_code, verify_backup_code -) -from auth.rate_limiting import ( - check_ip_blocked, record_failed_attempt, - reset_login_attempts, get_login_attempts -) -from utils.network import get_client_ip -from utils.audit import log_audit -from utils.license import generate_license_key, validate_license_key -from utils.backup import create_backup, restore_backup, get_or_create_encryption_key -from utils.export import ( - create_excel_export, format_datetime_for_export, - prepare_license_export_data, prepare_customer_export_data, - prepare_session_export_data, prepare_audit_export_data -) -from models import get_user_by_username - -app = Flask(__name__) -# Load configuration from config module -app.config['SECRET_KEY'] = config.SECRET_KEY -app.config['SESSION_TYPE'] = config.SESSION_TYPE -app.config['JSON_AS_ASCII'] = config.JSON_AS_ASCII -app.config['JSONIFY_MIMETYPE'] = config.JSONIFY_MIMETYPE -app.config['PERMANENT_SESSION_LIFETIME'] = config.PERMANENT_SESSION_LIFETIME -app.config['SESSION_COOKIE_HTTPONLY'] = config.SESSION_COOKIE_HTTPONLY -app.config['SESSION_COOKIE_SECURE'] = config.SESSION_COOKIE_SECURE -app.config['SESSION_COOKIE_SAMESITE'] = config.SESSION_COOKIE_SAMESITE -app.config['SESSION_COOKIE_NAME'] = config.SESSION_COOKIE_NAME -app.config['SESSION_REFRESH_EACH_REQUEST'] = config.SESSION_REFRESH_EACH_REQUEST -Session(app) - -# ProxyFix für korrekte IP-Adressen hinter Nginx -app.wsgi_app = ProxyFix( - app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 -) - -# Configuration is now loaded from config module - -# Scheduler für automatische Backups -scheduler = BackgroundScheduler() -scheduler.start() - -# Logging konfigurieren -logging.basicConfig(level=logging.INFO) - -# Import and register blueprints -from routes.auth_routes import auth_bp -from routes.admin_routes import admin_bp - -app.register_blueprint(auth_bp) -app.register_blueprint(admin_bp) - - -# Scheduled Backup Job -def scheduled_backup(): - """Führt ein geplantes Backup aus""" - logging.info("Starte geplantes Backup...") - create_backup(backup_type="scheduled", created_by="scheduler") - -# Scheduler konfigurieren - täglich um 3:00 Uhr -scheduler.add_job( - scheduled_backup, - 'cron', - hour=config.SCHEDULER_CONFIG['backup_hour'], - minute=config.SCHEDULER_CONFIG['backup_minute'], - id='daily_backup', - replace_existing=True -) - - -def verify_recaptcha(response): - """Verifiziert die reCAPTCHA v2 Response mit Google""" - secret_key = config.RECAPTCHA_SECRET_KEY - - # Wenn kein Secret Key konfiguriert ist, CAPTCHA als bestanden werten (für PoC) - if not secret_key: - logging.warning("RECAPTCHA_SECRET_KEY nicht konfiguriert - CAPTCHA wird übersprungen") - return True - - # Verifizierung bei Google - try: - verify_url = 'https://www.google.com/recaptcha/api/siteverify' - data = { - 'secret': secret_key, - 'response': response - } - - # Timeout für Request setzen - r = requests.post(verify_url, data=data, timeout=5) - result = r.json() - - # Log für Debugging - if not result.get('success'): - logging.warning(f"reCAPTCHA Validierung fehlgeschlagen: {result.get('error-codes', [])}") - - return result.get('success', False) - - except requests.exceptions.RequestException as e: - logging.error(f"reCAPTCHA Verifizierung fehlgeschlagen: {str(e)}") - # Bei Netzwerkfehlern CAPTCHA als bestanden werten - return True - except Exception as e: - logging.error(f"Unerwarteter Fehler bei reCAPTCHA: {str(e)}") - return False - - -# MOVED TO AUTH BLUEPRINT -# @app.route("/login", methods=["GET", "POST"]) -# def login(): -# # Timing-Attack Schutz - Start Zeit merken -# start_time = time.time() - - # IP-Adresse ermitteln - ip_address = get_client_ip() - - # Prüfen ob IP gesperrt ist - is_blocked, blocked_until = check_ip_blocked(ip_address) - if is_blocked: - time_remaining = (blocked_until - datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None)).total_seconds() / 3600 - error_msg = f"IP GESPERRT! Noch {time_remaining:.1f} Stunden warten." - return render_template("login.html", error=error_msg, error_type="blocked") - - # Anzahl bisheriger Versuche - attempt_count = get_login_attempts(ip_address) - - if request.method == "POST": - username = request.form.get("username") - password = request.form.get("password") - captcha_response = request.form.get("g-recaptcha-response") - - # CAPTCHA-Prüfung nur wenn Keys konfiguriert sind - recaptcha_site_key = config.RECAPTCHA_SITE_KEY - if attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and recaptcha_site_key: - if not captcha_response: - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA ERFORDERLICH!", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # CAPTCHA validieren - if not verify_recaptcha(captcha_response): - # Timing-Attack Schutz - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - return render_template("login.html", - error="CAPTCHA UNGÜLTIG! Bitte erneut versuchen.", - show_captcha=True, - error_type="captcha", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=recaptcha_site_key) - - # Check user in database first, fallback to env vars - user = get_user_by_username(username) - login_success = False - needs_2fa = False - - if user: - # Database user authentication - if verify_password(password, user['password_hash']): - login_success = True - needs_2fa = user['totp_enabled'] - else: - # Fallback to environment variables for backward compatibility - if username in config.ADMIN_USERS and password == config.ADMIN_USERS[username]: - login_success = True - - # Timing-Attack Schutz - Mindestens 1 Sekunde warten - elapsed = time.time() - start_time - if elapsed < 1.0: - time.sleep(1.0 - elapsed) - - if login_success: - # Erfolgreicher Login - if needs_2fa: - # Store temporary session for 2FA verification - session['temp_username'] = username - session['temp_user_id'] = user['id'] - session['awaiting_2fa'] = True - return redirect(url_for('verify_2fa')) - else: - # Complete login without 2FA - session.permanent = True # Aktiviert das Timeout - session['logged_in'] = True - session['username'] = username - session['user_id'] = user['id'] if user else None - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - reset_login_attempts(ip_address) - log_audit('LOGIN_SUCCESS', 'user', - additional_info=f"Erfolgreiche Anmeldung von IP: {ip_address}") - return redirect(url_for('dashboard')) - else: - # Fehlgeschlagener Login - error_message = record_failed_attempt(ip_address, username) - new_attempt_count = get_login_attempts(ip_address) - - # Prüfen ob jetzt gesperrt - is_now_blocked, _ = check_ip_blocked(ip_address) - if is_now_blocked: - log_audit('LOGIN_BLOCKED', 'security', - additional_info=f"IP {ip_address} wurde nach {config.MAX_LOGIN_ATTEMPTS} Versuchen gesperrt") - - return render_template("login.html", - error=error_message, - show_captcha=(new_attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - error_type="failed", - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - new_attempt_count), - recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - - # GET Request - return render_template("login.html", - show_captcha=(attempt_count >= config.CAPTCHA_AFTER_ATTEMPTS and config.RECAPTCHA_SITE_KEY), - attempts_left=max(0, config.MAX_LOGIN_ATTEMPTS - attempt_count), - recaptcha_site_key=config.RECAPTCHA_SITE_KEY) - -@app.route("/logout") -def logout(): - username = session.get('username', 'unknown') - log_audit('LOGOUT', 'user', additional_info=f"Abmeldung") - session.pop('logged_in', None) - session.pop('username', None) - session.pop('user_id', None) - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - return redirect(url_for('login')) - -# MOVED TO AUTH BLUEPRINT -# @app.route("/verify-2fa", methods=["GET", "POST"]) -# def verify_2fa(): -# if not session.get('awaiting_2fa'): -# return redirect(url_for('login')) - - if request.method == "POST": - token = request.form.get('token', '').replace(' ', '') - username = session.get('temp_username') - user_id = session.get('temp_user_id') - - if not username or not user_id: - flash('Session expired. Please login again.', 'error') - return redirect(url_for('login')) - - user = get_user_by_username(username) - if not user: - flash('User not found.', 'error') - return redirect(url_for('login')) - - # Check if it's a backup code - if len(token) == 8 and token.isupper(): - # Try backup code - backup_codes = json.loads(user['backup_codes']) if user['backup_codes'] else [] - if verify_backup_code(token, backup_codes): - # Remove used backup code - code_hash = hash_backup_code(token) - backup_codes.remove(code_hash) - - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET backup_codes = %s WHERE id = %s", - (json.dumps(backup_codes), user_id)) - conn.commit() - cur.close() - conn.close() - - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - flash('Login successful using backup code. Please generate new backup codes.', 'warning') - log_audit('LOGIN_2FA_BACKUP', 'user', additional_info=f"2FA login with backup code") - return redirect(url_for('dashboard')) - else: - # Try TOTP token - if verify_totp(user['totp_secret'], token): - # Complete login - session.permanent = True - session['logged_in'] = True - session['username'] = username - session['user_id'] = user_id - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - session.pop('temp_username', None) - session.pop('temp_user_id', None) - session.pop('awaiting_2fa', None) - - log_audit('LOGIN_2FA_SUCCESS', 'user', additional_info=f"2FA login successful") - return redirect(url_for('dashboard')) - - # Failed verification - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET failed_2fa_attempts = failed_2fa_attempts + 1, last_failed_2fa = %s WHERE id = %s", - (datetime.now(), user_id)) - conn.commit() - cur.close() - conn.close() - - flash('Invalid authentication code. Please try again.', 'error') - log_audit('LOGIN_2FA_FAILED', 'user', additional_info=f"Failed 2FA attempt") - - return render_template('verify_2fa.html') - -@app.route("/profile") -@login_required -def profile(): - user = get_user_by_username(session['username']) - if not user: - # For environment-based users, redirect with message - flash('Bitte führen Sie das Migrations-Script aus, um Passwort-Änderung und 2FA zu aktivieren.', 'info') - return redirect(url_for('dashboard')) - return render_template('profile.html', user=user) - -@app.route("/profile/change-password", methods=["POST"]) -@login_required -def change_password(): - current_password = request.form.get('current_password') - new_password = request.form.get('new_password') - confirm_password = request.form.get('confirm_password') - - user = get_user_by_username(session['username']) - - # Verify current password - if not verify_password(current_password, user['password_hash']): - flash('Current password is incorrect.', 'error') - return redirect(url_for('profile')) - - # Check new password - if new_password != confirm_password: - flash('New passwords do not match.', 'error') - return redirect(url_for('profile')) - - if len(new_password) < 8: - flash('Password must be at least 8 characters long.', 'error') - return redirect(url_for('profile')) - - # Update password - new_hash = hash_password(new_password) - conn = get_connection() - cur = conn.cursor() - cur.execute("UPDATE users SET password_hash = %s, last_password_change = %s WHERE id = %s", - (new_hash, datetime.now(), user['id'])) - conn.commit() - cur.close() - conn.close() - - log_audit('PASSWORD_CHANGE', 'user', entity_id=user['id'], - additional_info="Password changed successfully") - flash('Password changed successfully.', 'success') - return redirect(url_for('profile')) - -@app.route("/profile/setup-2fa") -@login_required -def setup_2fa(): - user = get_user_by_username(session['username']) - - if user['totp_enabled']: - flash('2FA is already enabled for your account.', 'info') - return redirect(url_for('profile')) - - # Generate new TOTP secret - totp_secret = generate_totp_secret() - session['temp_totp_secret'] = totp_secret - - # Generate QR code - qr_code = generate_qr_code(user['username'], totp_secret) - - return render_template('setup_2fa.html', - totp_secret=totp_secret, - qr_code=qr_code) - -@app.route("/profile/enable-2fa", methods=["POST"]) -@login_required -def enable_2fa(): - token = request.form.get('token', '').replace(' ', '') - totp_secret = session.get('temp_totp_secret') - - if not totp_secret: - flash('2FA setup session expired. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Verify the token - if not verify_totp(totp_secret, token): - flash('Invalid authentication code. Please try again.', 'error') - return redirect(url_for('setup_2fa')) - - # Generate backup codes - backup_codes = generate_backup_codes() - hashed_codes = [hash_backup_code(code) for code in backup_codes] - - # Enable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_secret = %s, totp_enabled = TRUE, backup_codes = %s - WHERE username = %s - """, (totp_secret, json.dumps(hashed_codes), session['username'])) - conn.commit() - cur.close() - conn.close() - - session.pop('temp_totp_secret', None) - - log_audit('2FA_ENABLED', 'user', additional_info="2FA enabled successfully") - - # Show backup codes - return render_template('backup_codes.html', backup_codes=backup_codes) - -@app.route("/profile/disable-2fa", methods=["POST"]) -@login_required -def disable_2fa(): - password = request.form.get('password') - user = get_user_by_username(session['username']) - - # Verify password - if not verify_password(password, user['password_hash']): - flash('Incorrect password.', 'error') - return redirect(url_for('profile')) - - # Disable 2FA - conn = get_connection() - cur = conn.cursor() - cur.execute(""" - UPDATE users - SET totp_enabled = FALSE, totp_secret = NULL, backup_codes = NULL - WHERE username = %s - """, (session['username'],)) - conn.commit() - cur.close() - conn.close() - - log_audit('2FA_DISABLED', 'user', additional_info="2FA disabled") - flash('2FA has been disabled for your account.', 'success') - return redirect(url_for('profile')) - -@app.route("/heartbeat", methods=['POST']) -@login_required -def heartbeat(): - """Endpoint für Session Keep-Alive - aktualisiert last_activity""" - # Aktualisiere last_activity nur wenn explizit angefordert - session['last_activity'] = datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - # Force session save - session.modified = True - - return jsonify({ - 'status': 'ok', - 'last_activity': session['last_activity'], - 'username': session.get('username') - }) - -@app.route("/api/generate-license-key", methods=['POST']) -@login_required -def api_generate_key(): - """API Endpoint zur Generierung eines neuen Lizenzschlüssels""" - try: - # Lizenztyp aus Request holen (default: full) - data = request.get_json() or {} - license_type = data.get('type', 'full') - - # Key generieren - key = generate_license_key(license_type) - - # Prüfen ob Key bereits existiert (sehr unwahrscheinlich aber sicher ist sicher) - conn = get_connection() - cur = conn.cursor() - - # Wiederhole bis eindeutiger Key gefunden - attempts = 0 - while attempts < 10: # Max 10 Versuche - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (key,)) - if not cur.fetchone(): - break # Key ist eindeutig - key = generate_license_key(license_type) - attempts += 1 - - cur.close() - conn.close() - - # Log für Audit - log_audit('GENERATE_KEY', 'license', - additional_info={'type': license_type, 'key': key}) - - return jsonify({ - 'success': True, - 'key': key, - 'type': license_type - }) - - except Exception as e: - logging.error(f"Fehler bei Key-Generierung: {str(e)}") - return jsonify({ - 'success': False, - 'error': 'Fehler bei der Key-Generierung' - }), 500 - -@app.route("/api/customers", methods=['GET']) -@login_required -def api_customers(): - """API Endpoint für die Kundensuche mit Select2""" - try: - # Suchparameter - search = request.args.get('q', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - customer_id = request.args.get('id', type=int) - - conn = get_connection() - cur = conn.cursor() - - # Einzelnen Kunden per ID abrufen - if customer_id: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.id = %s - GROUP BY c.id, c.name, c.email - """, (customer_id,)) - - customer = cur.fetchone() - results = [] - if customer: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} ({customer[2]})", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - cur.close() - conn.close() - - return jsonify({ - 'results': results, - 'pagination': {'more': False} - }) - - # SQL Query mit optionaler Suche - elif search: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE LOWER(c.name) LIKE LOWER(%s) - OR LOWER(c.email) LIKE LOWER(%s) - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (f'%{search}%', f'%{search}%', per_page, (page - 1) * per_page)) - else: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (per_page, (page - 1) * per_page)) - - customers = cur.fetchall() - - # Format für Select2 - results = [] - for customer in customers: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} - {customer[2]} ({customer[3]} Lizenzen)", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - # Gesamtanzahl für Pagination - if search: - cur.execute(""" - SELECT COUNT(*) FROM customers - WHERE LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - """, (f'%{search}%', f'%{search}%')) - else: - cur.execute("SELECT COUNT(*) FROM customers") - - total_count = cur.fetchone()[0] - - cur.close() - conn.close() - - # Select2 Response Format - return jsonify({ - 'results': results, - 'pagination': { - 'more': (page * per_page) < total_count - } - }) - - except Exception as e: - logging.error(f"Fehler bei Kundensuche: {str(e)}") - return jsonify({ - 'results': [], - 'error': 'Fehler bei der Kundensuche' - }), 500 - -@app.route("/") -@login_required -def dashboard(): - conn = get_connection() - cur = conn.cursor() - - # Statistiken abrufen - # Gesamtanzahl Kunden (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = FALSE") - total_customers = cur.fetchone()[0] - - # Gesamtanzahl Lizenzen (ohne Testdaten) - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = FALSE") - total_licenses = cur.fetchone()[0] - - # Aktive Lizenzen (nicht abgelaufen und is_active = true, ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE AND is_active = TRUE AND is_test = FALSE - """) - active_licenses = cur.fetchone()[0] - - # Aktive Sessions - cur.execute("SELECT COUNT(*) FROM sessions WHERE is_active = TRUE") - active_sessions_count = cur.fetchone()[0] - - # Abgelaufene Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until < CURRENT_DATE AND is_test = FALSE - """) - expired_licenses = cur.fetchone()[0] - - # Deaktivierte Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE is_active = FALSE AND is_test = FALSE - """) - inactive_licenses = cur.fetchone()[0] - - # Lizenzen die in den nächsten 30 Tagen ablaufen (ohne Testdaten) - cur.execute(""" - SELECT COUNT(*) FROM licenses - WHERE valid_until >= CURRENT_DATE - AND valid_until < CURRENT_DATE + INTERVAL '30 days' - AND is_active = TRUE - AND is_test = FALSE - """) - expiring_soon = cur.fetchone()[0] - - # Testlizenzen vs Vollversionen (ohne Testdaten) - cur.execute(""" - SELECT license_type, COUNT(*) - FROM licenses - WHERE is_test = FALSE - GROUP BY license_type - """) - license_types = dict(cur.fetchall()) - - # Anzahl Testdaten - cur.execute("SELECT COUNT(*) FROM licenses WHERE is_test = TRUE") - test_data_count = cur.fetchone()[0] - - # Anzahl Test-Kunden - cur.execute("SELECT COUNT(*) FROM customers WHERE is_test = TRUE") - test_customers_count = cur.fetchone()[0] - - # Anzahl Test-Ressourcen - cur.execute("SELECT COUNT(*) FROM resource_pools WHERE is_test = TRUE") - test_resources_count = cur.fetchone()[0] - - # Letzte 5 erstellten Lizenzen (ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.is_test = FALSE - ORDER BY l.id DESC - LIMIT 5 - """) - recent_licenses = cur.fetchall() - - # Bald ablaufende Lizenzen (nächste 30 Tage, ohne Testdaten) - cur.execute(""" - SELECT l.id, l.license_key, c.name, l.valid_until, - l.valid_until - CURRENT_DATE as days_left - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.valid_until >= CURRENT_DATE - AND l.valid_until < CURRENT_DATE + INTERVAL '30 days' - AND l.is_active = TRUE - AND l.is_test = FALSE - ORDER BY l.valid_until - LIMIT 10 - """) - expiring_licenses = cur.fetchall() - - # Letztes Backup - cur.execute(""" - SELECT created_at, filesize, duration_seconds, backup_type, status - FROM backup_history - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup_info = cur.fetchone() - - # Sicherheitsstatistiken - # Gesperrte IPs - cur.execute(""" - SELECT COUNT(*) FROM login_attempts - WHERE blocked_until IS NOT NULL AND blocked_until > CURRENT_TIMESTAMP - """) - blocked_ips_count = cur.fetchone()[0] - - # Fehlversuche heute - cur.execute(""" - SELECT COALESCE(SUM(attempt_count), 0) FROM login_attempts - WHERE last_attempt::date = CURRENT_DATE - """) - failed_attempts_today = cur.fetchone()[0] - - # Letzte 5 Sicherheitsereignisse - cur.execute(""" - SELECT - la.ip_address, - la.attempt_count, - la.last_attempt, - la.blocked_until, - la.last_username_tried, - la.last_error_message - FROM login_attempts la - ORDER BY la.last_attempt DESC - LIMIT 5 - """) - recent_security_events = [] - for event in cur.fetchall(): - recent_security_events.append({ - 'ip_address': event[0], - 'attempt_count': event[1], - 'last_attempt': event[2].strftime('%d.%m %H:%M'), - 'blocked_until': event[3].strftime('%d.%m %H:%M') if event[3] and event[3] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None) else None, - 'username_tried': event[4], - 'error_message': event[5] - }) - - # Sicherheitslevel berechnen - if blocked_ips_count > 5 or failed_attempts_today > 50: - security_level = 'danger' - security_level_text = 'KRITISCH' - elif blocked_ips_count > 2 or failed_attempts_today > 20: - security_level = 'warning' - security_level_text = 'ERHÖHT' - else: - security_level = 'success' - security_level_text = 'NORMAL' - - # Resource Pool Statistiken (nur Live-Daten, keine Testdaten) - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = FALSE - GROUP BY resource_type - """) - - resource_stats = {} - resource_warning = None - - for row in cur.fetchall(): - available_percent = round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - resource_stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': available_percent, - 'warning_level': 'danger' if row[1] < 50 else 'warning' if row[1] < 100 else 'success' - } - - # Warnung bei niedrigem Bestand - if row[1] < 50: - if not resource_warning: - resource_warning = f"Niedriger Bestand bei {row[0].upper()}: nur noch {row[1]} verfügbar!" - else: - resource_warning += f" | {row[0].upper()}: {row[1]}" - - cur.close() - conn.close() - - stats = { - 'total_customers': total_customers, - 'total_licenses': total_licenses, - 'active_licenses': active_licenses, - 'expired_licenses': expired_licenses, - 'inactive_licenses': inactive_licenses, - 'expiring_soon': expiring_soon, - 'full_licenses': license_types.get('full', 0), - 'test_licenses': license_types.get('test', 0), - 'test_data_count': test_data_count, - 'test_customers_count': test_customers_count, - 'test_resources_count': test_resources_count, - 'recent_licenses': recent_licenses, - 'expiring_licenses': expiring_licenses, - 'active_sessions': active_sessions_count, - 'last_backup': last_backup_info, - # Sicherheitsstatistiken - 'blocked_ips_count': blocked_ips_count, - 'failed_attempts_today': failed_attempts_today, - 'recent_security_events': recent_security_events, - 'security_level': security_level, - 'security_level_text': security_level_text, - 'resource_stats': resource_stats - } - - return render_template("dashboard.html", - stats=stats, - resource_stats=resource_stats, - resource_warning=resource_warning, - username=session.get('username')) - -@app.route("/create", methods=["GET", "POST"]) -@login_required -def create_license(): - if request.method == "POST": - customer_id = request.form.get("customer_id") - license_key = request.form["license_key"].upper() # Immer Großbuchstaben - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Validiere License Key Format - if not validate_license_key(license_key): - flash('Ungültiges License Key Format! Erwartet: AF-YYYYMMFT-XXXX-YYYY-ZZZZ', 'error') - return redirect(url_for('create_license')) - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('create_license')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('create_license')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - customer_info = {'name': name, 'email': email, 'is_test': is_test} - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos für Audit-Log - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('create_license')) - customer_info = {'name': customer_data[0], 'email': customer_data[1]} - - # Wenn Kunde Test-Kunde ist, Lizenz auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Lizenz hinzufügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit, is_test) - VALUES (%s, %s, %s, %s, %s, TRUE, %s, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit, is_test)) - license_id = cur.fetchone()[0] - - # Ressourcen zuweisen - try: - # Prüfe Verfügbarkeit - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {available[0]})") - if available[1] < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {ipv4_count}, verfügbar: {available[1]})") - if available[2] < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar (benötigt: {phone_count}, verfügbar: {available[2]})") - - # Domains zuweisen - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s zuweisen - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern zuweisen - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - except ValueError as e: - conn.rollback() - flash(str(e), 'error') - return redirect(url_for('create_license')) - - conn.commit() - - # Audit-Log - log_audit('CREATE', 'license', license_id, - new_values={ - 'license_key': license_key, - 'customer_name': customer_info['name'], - 'customer_email': customer_info['email'], - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'device_limit': device_limit, - 'is_test': is_test - }) - - flash(f'Lizenz {license_key} erfolgreich erstellt!', 'success') - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Erstellen der Lizenz: {str(e)}") - flash('Fehler beim Erstellen der Lizenz!', 'error') - finally: - cur.close() - conn.close() - - # Preserve show_test parameter if present - redirect_url = "/create" - if request.args.get('show_test') == 'true': - redirect_url += "?show_test=true" - return redirect(redirect_url) - - # Unterstützung für vorausgewählten Kunden - preselected_customer_id = request.args.get('customer_id', type=int) - return render_template("index.html", username=session.get('username'), preselected_customer_id=preselected_customer_id) - -@app.route("/batch", methods=["GET", "POST"]) -@login_required -def batch_licenses(): - """Batch-Generierung mehrerer Lizenzen für einen Kunden""" - if request.method == "POST": - # Formulardaten - customer_id = request.form.get("customer_id") - license_type = request.form["license_type"] - quantity = int(request.form["quantity"]) - valid_from = request.form["valid_from"] - is_test = request.form.get("is_test") == "on" # Checkbox value - - # Berechne valid_until basierend auf Laufzeit - duration = int(request.form.get("duration", 1)) - duration_type = request.form.get("duration_type", "years") - - from datetime import datetime, timedelta - from dateutil.relativedelta import relativedelta - - start_date = datetime.strptime(valid_from, "%Y-%m-%d") - - if duration_type == "days": - end_date = start_date + timedelta(days=duration) - elif duration_type == "months": - end_date = start_date + relativedelta(months=duration) - else: # years - end_date = start_date + relativedelta(years=duration) - - # Ein Tag abziehen, da der Starttag mitgezählt wird - end_date = end_date - timedelta(days=1) - valid_until = end_date.strftime("%Y-%m-%d") - - # Resource counts - domain_count = int(request.form.get("domain_count", 1)) - ipv4_count = int(request.form.get("ipv4_count", 1)) - phone_count = int(request.form.get("phone_count", 1)) - device_limit = int(request.form.get("device_limit", 3)) - - # Sicherheitslimit - if quantity < 1 or quantity > 100: - flash('Anzahl muss zwischen 1 und 100 liegen!', 'error') - return redirect(url_for('batch_licenses')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob neuer Kunde oder bestehender - if customer_id == "new": - # Neuer Kunde - name = request.form.get("customer_name") - email = request.form.get("email") - - if not name: - flash('Kundenname ist erforderlich!', 'error') - return redirect(url_for('batch_licenses')) - - # Prüfe ob E-Mail bereits existiert - if email: - cur.execute("SELECT id, name FROM customers WHERE LOWER(email) = LOWER(%s)", (email,)) - existing = cur.fetchone() - if existing: - flash(f'E-Mail bereits vergeben für Kunde: {existing[1]}', 'error') - return redirect(url_for('batch_licenses')) - - # Kunde einfügen (erbt Test-Status von Lizenz) - cur.execute(""" - INSERT INTO customers (name, email, is_test, created_at) - VALUES (%s, %s, %s, NOW()) - RETURNING id - """, (name, email, is_test)) - customer_id = cur.fetchone()[0] - - # Audit-Log für neuen Kunden - log_audit('CREATE', 'customer', customer_id, - new_values={'name': name, 'email': email, 'is_test': is_test}) - else: - # Bestehender Kunde - hole Infos - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - customer_data = cur.fetchone() - if not customer_data: - flash('Kunde nicht gefunden!', 'error') - return redirect(url_for('batch_licenses')) - name = customer_data[0] - email = customer_data[1] - - # Wenn Kunde Test-Kunde ist, Lizenzen auch als Test markieren - if customer_data[2]: # is_test des Kunden - is_test = True - - # Prüfe Ressourcen-Verfügbarkeit für gesamten Batch - total_domains_needed = domain_count * quantity - total_ipv4s_needed = ipv4_count * quantity - total_phones_needed = phone_count * quantity - - cur.execute(""" - SELECT - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s) as domains, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s) as ipv4s, - (SELECT COUNT(*) FROM resource_pools WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s) as phones - """, (is_test, is_test, is_test)) - available = cur.fetchone() - - if available[0] < total_domains_needed: - flash(f"Nicht genügend Domains verfügbar (benötigt: {total_domains_needed}, verfügbar: {available[0]})", 'error') - return redirect(url_for('batch_licenses')) - if available[1] < total_ipv4s_needed: - flash(f"Nicht genügend IPv4-Adressen verfügbar (benötigt: {total_ipv4s_needed}, verfügbar: {available[1]})", 'error') - return redirect(url_for('batch_licenses')) - if available[2] < total_phones_needed: - flash(f"Nicht genügend Telefonnummern verfügbar (benötigt: {total_phones_needed}, verfügbar: {available[2]})", 'error') - return redirect(url_for('batch_licenses')) - - # Lizenzen generieren und speichern - generated_licenses = [] - for i in range(quantity): - # Eindeutigen Key generieren - attempts = 0 - while attempts < 10: - license_key = generate_license_key(license_type) - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (license_key,)) - if not cur.fetchone(): - break - attempts += 1 - - # Lizenz einfügen - cur.execute(""" - INSERT INTO licenses (license_key, customer_id, license_type, is_test, - valid_from, valid_until, is_active, - domain_count, ipv4_count, phone_count, device_limit) - VALUES (%s, %s, %s, %s, %s, %s, true, %s, %s, %s, %s) - RETURNING id - """, (license_key, customer_id, license_type, is_test, valid_from, valid_until, - domain_count, ipv4_count, phone_count, device_limit)) - license_id = cur.fetchone()[0] - - # Ressourcen für diese Lizenz zuweisen - # Domains - if domain_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, domain_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # IPv4s - if ipv4_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, ipv4_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - # Telefonnummern - if phone_count > 0: - cur.execute(""" - SELECT id FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' AND is_test = %s - LIMIT %s FOR UPDATE - """, (is_test, phone_count)) - for (resource_id,) in cur.fetchall(): - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - generated_licenses.append({ - 'id': license_id, - 'key': license_key, - 'type': license_type - }) - - conn.commit() - - # Audit-Log - log_audit('CREATE_BATCH', 'license', - new_values={'customer': name, 'quantity': quantity, 'type': license_type}, - additional_info=f"Batch-Generierung von {quantity} Lizenzen") - - # Session für Export speichern - session['batch_export'] = { - 'customer': name, - 'email': email, - 'licenses': generated_licenses, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'timestamp': datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None).isoformat() - } - - flash(f'{quantity} Lizenzen erfolgreich generiert!', 'success') - return render_template("batch_result.html", - customer=name, - email=email, - licenses=generated_licenses, - valid_from=valid_from, - valid_until=valid_until) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler bei Batch-Generierung: {str(e)}") - flash('Fehler bei der Batch-Generierung!', 'error') - return redirect(url_for('batch_licenses')) - finally: - cur.close() - conn.close() - - # GET Request - return render_template("batch_form.html") - -@app.route("/batch/export") -@login_required -def export_batch(): - """Exportiert die zuletzt generierten Batch-Lizenzen""" - batch_data = session.get('batch_export') - if not batch_data: - flash('Keine Batch-Daten zum Exportieren vorhanden!', 'error') - return redirect(url_for('batch_licenses')) - - # CSV generieren - output = io.StringIO() - output.write('\ufeff') # UTF-8 BOM für Excel - - # Header - output.write(f"Kunde: {batch_data['customer']}\n") - output.write(f"E-Mail: {batch_data['email']}\n") - output.write(f"Generiert am: {datetime.fromisoformat(batch_data['timestamp']).strftime('%d.%m.%Y %H:%M')}\n") - output.write(f"Gültig von: {batch_data['valid_from']} bis {batch_data['valid_until']}\n") - output.write("\n") - output.write("Nr;Lizenzschlüssel;Typ\n") - - # Lizenzen - for i, license in enumerate(batch_data['licenses'], 1): - typ_text = "Vollversion" if license['type'] == 'full' else "Testversion" - output.write(f"{i};{license['key']};{typ_text}\n") - - output.seek(0) - - # Audit-Log - log_audit('EXPORT', 'batch_licenses', - additional_info=f"Export von {len(batch_data['licenses'])} Batch-Lizenzen") - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f"batch_licenses_{batch_data['customer'].replace(' ', '_')}_{datetime.now(ZoneInfo('Europe/Berlin')).strftime('%Y%m%d_%H%M%S')}.csv" - ) - -@app.route("/licenses") -@login_required -def licenses(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/license/edit/", methods=["GET", "POST"]) -@login_required -def edit_license(license_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute(""" - SELECT license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit - FROM licenses WHERE id = %s - """, (license_id,)) - old_license = cur.fetchone() - - # Update license - license_key = request.form["license_key"] - license_type = request.form["license_type"] - valid_from = request.form["valid_from"] - valid_until = request.form["valid_until"] - is_active = request.form.get("is_active") == "on" - is_test = request.form.get("is_test") == "on" - device_limit = int(request.form.get("device_limit", 3)) - - cur.execute(""" - UPDATE licenses - SET license_key = %s, license_type = %s, valid_from = %s, - valid_until = %s, is_active = %s, is_test = %s, device_limit = %s - WHERE id = %s - """, (license_key, license_type, valid_from, valid_until, is_active, is_test, device_limit, license_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'license_key': old_license[0], - 'license_type': old_license[1], - 'valid_from': str(old_license[2]), - 'valid_until': str(old_license[3]), - 'is_active': old_license[4], - 'is_test': old_license[5], - 'device_limit': old_license[6] - }, - new_values={ - 'license_key': license_key, - 'license_type': license_type, - 'valid_from': valid_from, - 'valid_until': valid_until, - 'is_active': is_active, - 'is_test': is_test, - 'device_limit': device_limit - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei wenn vorhanden - if request.referrer and 'customer_id=' in request.referrer: - import re - match = re.search(r'customer_id=(\d+)', request.referrer) - if match: - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={match.group(1)}" - - return redirect(redirect_url) - - # Get license data - cur.execute(""" - SELECT l.id, l.license_key, c.name, c.email, l.license_type, - l.valid_from, l.valid_until, l.is_active, c.id, l.is_test, l.device_limit - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - - license = cur.fetchone() - cur.close() - conn.close() - - if not license: - return redirect("/licenses") - - return render_template("edit_license.html", license=license, username=session.get('username')) - -@app.route("/license/delete/", methods=["POST"]) -@login_required -def delete_license(license_id): - conn = get_connection() - cur = conn.cursor() - - # Lizenzdetails für Audit-Log abrufen - cur.execute(""" - SELECT l.license_key, c.name, l.license_type - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE l.id = %s - """, (license_id,)) - license_info = cur.fetchone() - - cur.execute("DELETE FROM licenses WHERE id = %s", (license_id,)) - - conn.commit() - - # Audit-Log - if license_info: - log_audit('DELETE', 'license', license_id, - old_values={ - 'license_key': license_info[0], - 'customer_name': license_info[1], - 'license_type': license_info[2] - }) - - cur.close() - conn.close() - - return redirect("/licenses") - -@app.route("/customers") -@login_required -def customers(): - # Redirect zur kombinierten Ansicht - return redirect("/customers-licenses") - -@app.route("/customer/edit/", methods=["GET", "POST"]) -@login_required -def edit_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - if request.method == "POST": - # Alte Werte für Audit-Log abrufen - cur.execute("SELECT name, email, is_test FROM customers WHERE id = %s", (customer_id,)) - old_customer = cur.fetchone() - - # Update customer - name = request.form["name"] - email = request.form["email"] - is_test = request.form.get("is_test") == "on" - - cur.execute(""" - UPDATE customers - SET name = %s, email = %s, is_test = %s - WHERE id = %s - """, (name, email, is_test, customer_id)) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'customer', customer_id, - old_values={ - 'name': old_customer[0], - 'email': old_customer[1], - 'is_test': old_customer[2] - }, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - cur.close() - conn.close() - - # Redirect zurück zu customers-licenses mit beibehaltenen Parametern - redirect_url = "/customers-licenses" - - # Behalte show_test Parameter bei (aus Form oder GET-Parameter) - show_test = request.form.get('show_test') or request.args.get('show_test') - if show_test == 'true': - redirect_url += "?show_test=true" - - # Behalte customer_id bei (immer der aktuelle Kunde) - connector = "&" if "?" in redirect_url else "?" - redirect_url += f"{connector}customer_id={customer_id}" - - return redirect(redirect_url) - - # Get customer data with licenses - cur.execute(""" - SELECT id, name, email, created_at, is_test FROM customers WHERE id = %s - """, (customer_id,)) - - customer = cur.fetchone() - if not customer: - cur.close() - conn.close() - return "Kunde nicht gefunden", 404 - - - # Get customer's licenses - cur.execute(""" - SELECT id, license_key, license_type, valid_from, valid_until, is_active - FROM licenses - WHERE customer_id = %s - ORDER BY valid_until DESC - """, (customer_id,)) - - licenses = cur.fetchall() - - cur.close() - conn.close() - - if not customer: - return redirect("/customers-licenses") - - return render_template("edit_customer.html", customer=customer, licenses=licenses, username=session.get('username')) - -@app.route("/customer/create", methods=["GET", "POST"]) -@login_required -def create_customer(): - """Erstellt einen neuen Kunden ohne Lizenz""" - if request.method == "POST": - name = request.form.get('name') - email = request.form.get('email') - is_test = request.form.get('is_test') == 'on' - - if not name or not email: - flash("Name und E-Mail sind Pflichtfelder!", "error") - return render_template("create_customer.html", username=session.get('username')) - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfen ob E-Mail bereits existiert - cur.execute("SELECT id, name FROM customers WHERE email = %s", (email,)) - existing = cur.fetchone() - if existing: - flash(f"Ein Kunde mit der E-Mail '{email}' existiert bereits: {existing[1]}", "error") - return render_template("create_customer.html", username=session.get('username')) - - # Kunde erstellen - cur.execute(""" - INSERT INTO customers (name, email, created_at, is_test) - VALUES (%s, %s, %s, %s) RETURNING id - """, (name, email, datetime.now(), is_test)) - - customer_id = cur.fetchone()[0] - conn.commit() - - # Audit-Log - log_audit('CREATE', 'customer', customer_id, - new_values={ - 'name': name, - 'email': email, - 'is_test': is_test - }) - - flash(f"Kunde '{name}' wurde erfolgreich angelegt!", "success") - return redirect(f"/customer/edit/{customer_id}") - - except Exception as e: - conn.rollback() - flash(f"Fehler beim Anlegen des Kunden: {str(e)}", "error") - return render_template("create_customer.html", username=session.get('username')) - finally: - cur.close() - conn.close() - - # GET Request - Formular anzeigen - return render_template("create_customer.html", username=session.get('username')) - -@app.route("/customer/delete/", methods=["POST"]) -@login_required -def delete_customer(customer_id): - conn = get_connection() - cur = conn.cursor() - - # Prüfen ob Kunde Lizenzen hat - cur.execute("SELECT COUNT(*) FROM licenses WHERE customer_id = %s", (customer_id,)) - license_count = cur.fetchone()[0] - - if license_count > 0: - # Kunde hat Lizenzen - nicht löschen - cur.close() - conn.close() - return redirect("/customers") - - # Kundendetails für Audit-Log abrufen - cur.execute("SELECT name, email FROM customers WHERE id = %s", (customer_id,)) - customer_info = cur.fetchone() - - # Kunde löschen wenn keine Lizenzen vorhanden - cur.execute("DELETE FROM customers WHERE id = %s", (customer_id,)) - - conn.commit() - - # Audit-Log - if customer_info: - log_audit('DELETE', 'customer', customer_id, - old_values={ - 'name': customer_info[0], - 'email': customer_info[1] - }) - - cur.close() - conn.close() - - return redirect("/customers") - -@app.route("/customers-licenses") -@login_required -def customers_licenses(): - """Kombinierte Ansicht für Kunden und deren Lizenzen""" - conn = get_connection() - cur = conn.cursor() - - # Hole alle Kunden mit Lizenzstatistiken (inkl. Testkunden wenn gewünscht) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - query = """ - SELECT - c.id, - c.name, - c.email, - c.created_at, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - """ - - if not show_test: - query += " WHERE c.is_test = FALSE" - - query += """ - GROUP BY c.id, c.name, c.email, c.created_at - ORDER BY c.name - """ - - cur.execute(query) - customers = cur.fetchall() - - # Hole ausgewählten Kunden nur wenn explizit in URL angegeben - selected_customer_id = request.args.get('customer_id', type=int) - licenses = [] - selected_customer = None - - if customers and selected_customer_id: - # Hole Daten des ausgewählten Kunden - for customer in customers: - if customer[0] == selected_customer_id: - selected_customer = customer - break - - # Hole Lizenzen des ausgewählten Kunden - if selected_customer: - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (selected_customer_id,)) - licenses = cur.fetchall() - - cur.close() - conn.close() - - return render_template("customers_licenses.html", - customers=customers, - selected_customer=selected_customer, - selected_customer_id=selected_customer_id, - licenses=licenses, - show_test=show_test) - -@app.route("/api/customer//licenses") -@login_required -def api_customer_licenses(customer_id): - """API-Endpoint für AJAX-Abruf der Lizenzen eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Lizenzen des Kunden - cur.execute(""" - SELECT - l.id, - l.license_key, - l.license_type, - l.valid_from, - l.valid_until, - l.is_active, - CASE - WHEN l.is_active = FALSE THEN 'deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab' - ELSE 'aktiv' - END as status, - l.domain_count, - l.ipv4_count, - l.phone_count, - l.device_limit, - (SELECT COUNT(*) FROM device_registrations WHERE license_id = l.id AND is_active = TRUE) as active_devices, - -- Actual resource counts - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'domain') as actual_domain_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'ipv4') as actual_ipv4_count, - (SELECT COUNT(*) FROM license_resources lr - JOIN resource_pools rp ON lr.resource_id = rp.id - WHERE lr.license_id = l.id AND lr.is_active = true AND rp.resource_type = 'phone') as actual_phone_count - FROM licenses l - WHERE l.customer_id = %s - ORDER BY l.created_at DESC, l.id DESC - """, (customer_id,)) - - licenses = [] - for row in cur.fetchall(): - license_id = row[0] - - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for res_row in cur.fetchall(): - resource_info = { - 'id': res_row[0], - 'value': res_row[2], - 'assigned_at': res_row[3].strftime('%d.%m.%Y') if res_row[3] else '' - } - - if res_row[1] == 'domain': - resources['domains'].append(resource_info) - elif res_row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif res_row[1] == 'phone': - resources['phones'].append(resource_info) - - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'license_type': row[2], - 'valid_from': row[3].strftime('%d.%m.%Y') if row[3] else '', - 'valid_until': row[4].strftime('%d.%m.%Y') if row[4] else '', - 'is_active': row[5], - 'status': row[6], - 'domain_count': row[7], # limit - 'ipv4_count': row[8], # limit - 'phone_count': row[9], # limit - 'device_limit': row[10], - 'active_devices': row[11], - 'actual_domain_count': row[12], # actual count - 'actual_ipv4_count': row[13], # actual count - 'actual_phone_count': row[14], # actual count - 'resources': resources - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'licenses': licenses, - 'count': len(licenses) - }) - -@app.route("/api/customer//quick-stats") -@login_required -def api_customer_quick_stats(customer_id): - """API-Endpoint für Schnellstatistiken eines Kunden""" - conn = get_connection() - cur = conn.cursor() - - # Hole Kundenstatistiken - cur.execute(""" - SELECT - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' AND l.valid_until >= CURRENT_DATE THEN 1 END) as expiring_soon - FROM licenses l - WHERE l.customer_id = %s - """, (customer_id,)) - - stats = cur.fetchone() - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'stats': { - 'total': stats[0], - 'active': stats[1], - 'expired': stats[2], - 'expiring_soon': stats[3] - } - }) - -@app.route("/api/license//quick-edit", methods=['POST']) -@login_required -def api_license_quick_edit(license_id): - """API-Endpoint für schnelle Lizenz-Bearbeitung""" - conn = get_connection() - cur = conn.cursor() - - try: - data = request.get_json() - - # Hole alte Werte für Audit-Log - cur.execute(""" - SELECT is_active, valid_until, license_type - FROM licenses WHERE id = %s - """, (license_id,)) - old_values = cur.fetchone() - - if not old_values: - return jsonify({'success': False, 'error': 'Lizenz nicht gefunden'}), 404 - - # Update-Felder vorbereiten - updates = [] - params = [] - new_values = {} - - if 'is_active' in data: - updates.append("is_active = %s") - params.append(data['is_active']) - new_values['is_active'] = data['is_active'] - - if 'valid_until' in data: - updates.append("valid_until = %s") - params.append(data['valid_until']) - new_values['valid_until'] = data['valid_until'] - - if 'license_type' in data: - updates.append("license_type = %s") - params.append(data['license_type']) - new_values['license_type'] = data['license_type'] - - if updates: - params.append(license_id) - cur.execute(f""" - UPDATE licenses - SET {', '.join(updates)} - WHERE id = %s - """, params) - - conn.commit() - - # Audit-Log - log_audit('UPDATE', 'license', license_id, - old_values={ - 'is_active': old_values[0], - 'valid_until': old_values[1].isoformat() if old_values[1] else None, - 'license_type': old_values[2] - }, - new_values=new_values) - - cur.close() - conn.close() - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/api/license//resources") -@login_required -def api_license_resources(license_id): - """API-Endpoint für detaillierte Ressourcen-Informationen einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Hole die konkreten zugewiesenen Ressourcen für diese Lizenz - cur.execute(""" - SELECT rp.id, rp.resource_type, rp.resource_value, lr.assigned_at - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s AND lr.is_active = true - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = { - 'domains': [], - 'ipv4s': [], - 'phones': [] - } - - for row in cur.fetchall(): - resource_info = { - 'id': row[0], - 'value': row[2], - 'assigned_at': row[3].strftime('%d.%m.%Y') if row[3] else '' - } - - if row[1] == 'domain': - resources['domains'].append(resource_info) - elif row[1] == 'ipv4': - resources['ipv4s'].append(resource_info) - elif row[1] == 'phone': - resources['phones'].append(resource_info) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'resources': resources - }) - - except Exception as e: - cur.close() - conn.close() - return jsonify({'success': False, 'error': str(e)}), 500 - -@app.route("/sessions") -@login_required -def sessions(): - conn = get_connection() - cur = conn.cursor() - - # Sortierparameter - active_sort = request.args.get('active_sort', 'last_heartbeat') - active_order = request.args.get('active_order', 'desc') - ended_sort = request.args.get('ended_sort', 'ended_at') - ended_order = request.args.get('ended_order', 'desc') - - # Whitelist für erlaubte Sortierfelder - Aktive Sessions - active_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'last_heartbeat': 's.last_heartbeat', - 'inactive': 'minutes_inactive' - } - - # Whitelist für erlaubte Sortierfelder - Beendete Sessions - ended_sort_fields = { - 'customer': 'c.name', - 'license': 'l.license_key', - 'ip': 's.ip_address', - 'started': 's.started_at', - 'ended_at': 's.ended_at', - 'duration': 'duration_minutes' - } - - # Validierung - if active_sort not in active_sort_fields: - active_sort = 'last_heartbeat' - if ended_sort not in ended_sort_fields: - ended_sort = 'ended_at' - if active_order not in ['asc', 'desc']: - active_order = 'desc' - if ended_order not in ['asc', 'desc']: - ended_order = 'desc' - - # Aktive Sessions abrufen - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.user_agent, s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.last_heartbeat))/60 as minutes_inactive - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = TRUE - ORDER BY {active_sort_fields[active_sort]} {active_order.upper()} - """) - active_sessions = cur.fetchall() - - # Inaktive Sessions der letzten 24 Stunden - cur.execute(f""" - SELECT s.id, s.session_id, l.license_key, c.name, s.ip_address, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))/60 as duration_minutes - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = FALSE - AND s.ended_at > NOW() - INTERVAL '24 hours' - ORDER BY {ended_sort_fields[ended_sort]} {ended_order.upper()} - LIMIT 50 - """) - recent_sessions = cur.fetchall() - - cur.close() - conn.close() - - return render_template("sessions.html", - active_sessions=active_sessions, - recent_sessions=recent_sessions, - active_sort=active_sort, - active_order=active_order, - ended_sort=ended_sort, - ended_order=ended_order, - username=session.get('username')) - -@app.route("/session/end/", methods=["POST"]) -@login_required -def end_session(session_id): - conn = get_connection() - cur = conn.cursor() - - # Session beenden - cur.execute(""" - UPDATE sessions - SET is_active = FALSE, ended_at = NOW() - WHERE id = %s AND is_active = TRUE - """, (session_id,)) - - conn.commit() - cur.close() - conn.close() - - return redirect("/sessions") - -@app.route("/export/licenses") -@login_required -def export_licenses(): - conn = get_connection() - cur = conn.cursor() - - # Alle Lizenzen mit Kundeninformationen abrufen (ohne Testdaten, außer explizit gewünscht) - include_test = request.args.get('include_test', 'false').lower() == 'true' - customer_id = request.args.get('customer_id', type=int) - - query = """ - SELECT l.id, l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type, l.valid_from, l.valid_until, l.is_active, l.is_test, - CASE - WHEN l.is_active = FALSE THEN 'Deaktiviert' - WHEN l.valid_until < CURRENT_DATE THEN 'Abgelaufen' - WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'Läuft bald ab' - ELSE 'Aktiv' - END as status - FROM licenses l - JOIN customers c ON l.customer_id = c.id - """ - - # Build WHERE clause - where_conditions = [] - params = [] - - if not include_test: - where_conditions.append("l.is_test = FALSE") - - if customer_id: - where_conditions.append("l.customer_id = %s") - params.append(customer_id) - - if where_conditions: - query += " WHERE " + " AND ".join(where_conditions) - - query += " ORDER BY l.id" - - cur.execute(query, params) - - # Spaltennamen - columns = ['ID', 'Lizenzschlüssel', 'Kunde', 'E-Mail', 'Typ', - 'Gültig von', 'Gültig bis', 'Aktiv', 'Testdaten', 'Status'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Gültig von'] = pd.to_datetime(df['Gültig von']).dt.strftime('%d.%m.%Y') - df['Gültig bis'] = pd.to_datetime(df['Gültig bis']).dt.strftime('%d.%m.%Y') - - # Typ und Aktiv Status anpassen - df['Typ'] = df['Typ'].replace({'full': 'Vollversion', 'test': 'Testversion'}) - df['Aktiv'] = df['Aktiv'].replace({True: 'Ja', False: 'Nein'}) - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'license', - additional_info=f"Export aller Lizenzen als {export_format.upper()}") - filename = f'lizenzen_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Lizenzen', index=False) - - # Formatierung - worksheet = writer.sheets['Lizenzen'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/audit") -@login_required -def export_audit(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_user = request.args.get('user', '') - filter_action = request.args.get('action', '') - filter_entity = request.args.get('entity', '') - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - params = [] - - if filter_user: - query += " AND username ILIKE %s" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - query += " ORDER BY timestamp DESC" - - cur.execute(query, params) - audit_logs = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for log in audit_logs: - action_text = { - 'CREATE': 'Erstellt', - 'UPDATE': 'Bearbeitet', - 'DELETE': 'Gelöscht', - 'LOGIN': 'Anmeldung', - 'LOGOUT': 'Abmeldung', - 'AUTO_LOGOUT': 'Auto-Logout', - 'EXPORT': 'Export', - 'GENERATE_KEY': 'Key generiert', - 'CREATE_BATCH': 'Batch erstellt', - 'BACKUP': 'Backup erstellt', - 'LOGIN_2FA_SUCCESS': '2FA-Anmeldung', - 'LOGIN_2FA_BACKUP': '2FA-Backup-Code', - 'LOGIN_2FA_FAILED': '2FA-Fehlgeschlagen', - 'LOGIN_BLOCKED': 'Login-Blockiert', - 'RESTORE': 'Wiederhergestellt', - 'PASSWORD_CHANGE': 'Passwort geändert', - '2FA_ENABLED': '2FA aktiviert', - '2FA_DISABLED': '2FA deaktiviert' - }.get(log[3], log[3]) - - data.append({ - 'ID': log[0], - 'Zeitstempel': log[1].strftime('%d.%m.%Y %H:%M:%S'), - 'Benutzer': log[2], - 'Aktion': action_text, - 'Entität': log[4], - 'Entität-ID': log[5] or '', - 'IP-Adresse': log[8] or '', - 'Zusatzinfo': log[10] or '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'audit_log_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'audit_log', - additional_info=f"{export_format.upper()} Export mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Audit Log') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Audit Log'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/customers") -@login_required -def export_customers(): - conn = get_connection() - cur = conn.cursor() - - # Check if test data should be included - include_test = request.args.get('include_test', 'false').lower() == 'true' - - # Build query based on test data filter - if include_test: - # Include all customers - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(l.id) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - else: - # Exclude test customers and test licenses - query = """ - SELECT c.id, c.name, c.email, c.created_at, c.is_test, - COUNT(CASE WHEN l.is_test = FALSE THEN 1 END) as total_licenses, - COUNT(CASE WHEN l.is_active = TRUE AND l.valid_until >= CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as active_licenses, - COUNT(CASE WHEN l.valid_until < CURRENT_DATE AND l.is_test = FALSE THEN 1 END) as expired_licenses - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.is_test = FALSE - GROUP BY c.id, c.name, c.email, c.created_at, c.is_test - ORDER BY c.id - """ - - cur.execute(query) - - # Spaltennamen - columns = ['ID', 'Name', 'E-Mail', 'Erstellt am', 'Testdaten', - 'Lizenzen gesamt', 'Aktive Lizenzen', 'Abgelaufene Lizenzen'] - - # Daten in DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - # Datumsformatierung - df['Erstellt am'] = pd.to_datetime(df['Erstellt am']).dt.strftime('%d.%m.%Y %H:%M') - - # Testdaten formatting - df['Testdaten'] = df['Testdaten'].replace({True: 'Ja', False: 'Nein'}) - - cur.close() - conn.close() - - # Export Format - export_format = request.args.get('format', 'excel') - - # Audit-Log - log_audit('EXPORT', 'customer', - additional_info=f"Export aller Kunden als {export_format.upper()}") - filename = f'kunden_export_{datetime.now(ZoneInfo("Europe/Berlin")).strftime("%Y%m%d_%H%M%S")}' - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - df.to_csv(output, index=False, encoding='utf-8-sig', sep=';') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Kunden', index=False) - - # Formatierung - worksheet = writer.sheets['Kunden'] - for column in worksheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - worksheet.column_dimensions[column_letter].width = adjusted_width - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/sessions") -@login_required -def export_sessions(): - conn = get_connection() - cur = conn.cursor() - - # Holen des Session-Typs (active oder ended) - session_type = request.args.get('type', 'active') - export_format = request.args.get('format', 'excel') - - # Daten je nach Typ abrufen - if session_type == 'active': - # Aktive Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.last_heartbeat, - EXTRACT(EPOCH FROM (NOW() - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = true - ORDER BY s.last_heartbeat DESC - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Letzte Aktivität': sess[5].strftime('%d.%m.%Y %H:%M:%S'), - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Aktive Sessions' - filename_prefix = 'aktive_sessions' - else: - # Beendete Lizenz-Sessions - cur.execute(""" - SELECT s.id, l.license_key, c.name as customer_name, s.session_id, - s.started_at, s.ended_at, - EXTRACT(EPOCH FROM (s.ended_at - s.started_at))::INT as duration_seconds, - s.ip_address, s.user_agent - FROM sessions s - JOIN licenses l ON s.license_id = l.id - JOIN customers c ON l.customer_id = c.id - WHERE s.is_active = false AND s.ended_at IS NOT NULL - ORDER BY s.ended_at DESC - LIMIT 1000 - """) - sessions = cur.fetchall() - - # Daten für Export vorbereiten - data = [] - for sess in sessions: - duration = sess[6] if sess[6] else 0 - hours = duration // 3600 - minutes = (duration % 3600) // 60 - seconds = duration % 60 - - data.append({ - 'Session-ID': sess[0], - 'Lizenzschlüssel': sess[1], - 'Kunde': sess[2], - 'Session-ID (Tech)': sess[3], - 'Startzeit': sess[4].strftime('%d.%m.%Y %H:%M:%S'), - 'Endzeit': sess[5].strftime('%d.%m.%Y %H:%M:%S') if sess[5] else '', - 'Dauer': f"{hours}h {minutes}m {seconds}s", - 'IP-Adresse': sess[7], - 'Browser': sess[8] - }) - - sheet_name = 'Beendete Sessions' - filename_prefix = 'beendete_sessions' - - cur.close() - conn.close() - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'{filename_prefix}_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'sessions', - additional_info=f"{export_format.upper()} Export von {session_type} Sessions mit {len(data)} Einträgen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name=sheet_name) - - # Spaltenbreiten anpassen - worksheet = writer.sheets[sheet_name] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/export/resources") -@login_required -def export_resources(): - conn = get_connection() - cur = conn.cursor() - - # Holen der Filter-Parameter - filter_type = request.args.get('type', '') - filter_status = request.args.get('status', '') - search_query = request.args.get('search', '') - show_test = request.args.get('show_test', 'false').lower() == 'true' - export_format = request.args.get('format', 'excel') - - # SQL Query mit Filtern - query = """ - SELECT r.id, r.resource_type, r.resource_value, r.status, r.allocated_to_license, - r.created_at, r.status_changed_at, - l.license_key, c.name as customer_name, c.email as customer_email, - l.license_type - FROM resource_pools r - LEFT JOIN licenses l ON r.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE 1=1 - """ - params = [] - - # Filter für Testdaten - if not show_test: - query += " AND (r.is_test = false OR r.is_test IS NULL)" - - # Filter für Ressourcentyp - if filter_type: - query += " AND r.resource_type = %s" - params.append(filter_type) - - # Filter für Status - if filter_status: - query += " AND r.status = %s" - params.append(filter_status) - - # Suchfilter - if search_query: - query += " AND (r.resource_value ILIKE %s OR l.license_key ILIKE %s OR c.name ILIKE %s)" - params.extend([f'%{search_query}%', f'%{search_query}%', f'%{search_query}%']) - - query += " ORDER BY r.id DESC" - - cur.execute(query, params) - resources = cur.fetchall() - cur.close() - conn.close() - - # Daten für Export vorbereiten - data = [] - for res in resources: - status_text = { - 'available': 'Verfügbar', - 'allocated': 'Zugewiesen', - 'quarantine': 'Quarantäne' - }.get(res[3], res[3]) - - type_text = { - 'domain': 'Domain', - 'ipv4': 'IPv4', - 'phone': 'Telefon' - }.get(res[1], res[1]) - - data.append({ - 'ID': res[0], - 'Typ': type_text, - 'Ressource': res[2], - 'Status': status_text, - 'Lizenzschlüssel': res[7] or '', - 'Kunde': res[8] or '', - 'Kunden-Email': res[9] or '', - 'Lizenztyp': res[10] or '', - 'Erstellt am': res[5].strftime('%d.%m.%Y %H:%M:%S') if res[5] else '', - 'Zugewiesen am': res[6].strftime('%d.%m.%Y %H:%M:%S') if res[6] else '' - }) - - # DataFrame erstellen - df = pd.DataFrame(data) - - # Timestamp für Dateiname - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f'resources_export_{timestamp}' - - # Audit Log für Export - log_audit('EXPORT', 'resources', - additional_info=f"{export_format.upper()} Export mit {len(data)} Ressourcen") - - if export_format == 'csv': - # CSV Export - output = io.StringIO() - # UTF-8 BOM für Excel - output.write('\ufeff') - df.to_csv(output, index=False, sep=';', encoding='utf-8') - output.seek(0) - - return send_file( - io.BytesIO(output.getvalue().encode('utf-8')), - mimetype='text/csv;charset=utf-8', - as_attachment=True, - download_name=f'{filename}.csv' - ) - else: - # Excel Export - output = BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, index=False, sheet_name='Resources') - - # Spaltenbreiten anpassen - worksheet = writer.sheets['Resources'] - for idx, col in enumerate(df.columns): - max_length = max( - df[col].astype(str).map(len).max(), - len(col) - ) + 2 - worksheet.column_dimensions[get_column_letter(idx + 1)].width = min(max_length, 50) - - output.seek(0) - - return send_file( - output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx' - ) - -@app.route("/audit") -@login_required -def audit_log(): - conn = get_connection() - cur = conn.cursor() - - # Parameter - filter_user = request.args.get('user', '').strip() - filter_action = request.args.get('action', '').strip() - filter_entity = request.args.get('entity', '').strip() - page = request.args.get('page', 1, type=int) - sort = request.args.get('sort', 'timestamp') - order = request.args.get('order', 'desc') - per_page = 50 - - # Whitelist für erlaubte Sortierfelder - allowed_sort_fields = { - 'timestamp': 'timestamp', - 'username': 'username', - 'action': 'action', - 'entity': 'entity_type', - 'ip': 'ip_address' - } - - # Validierung - if sort not in allowed_sort_fields: - sort = 'timestamp' - if order not in ['asc', 'desc']: - order = 'desc' - - sort_field = allowed_sort_fields[sort] - - # SQL Query mit optionalen Filtern - query = """ - SELECT id, timestamp, username, action, entity_type, entity_id, - old_values, new_values, ip_address, user_agent, additional_info - FROM audit_log - WHERE 1=1 - """ - - params = [] - - # Filter - if filter_user: - query += " AND LOWER(username) LIKE LOWER(%s)" - params.append(f'%{filter_user}%') - - if filter_action: - query += " AND action = %s" - params.append(filter_action) - - if filter_entity: - query += " AND entity_type = %s" - params.append(filter_entity) - - # Gesamtanzahl für Pagination - count_query = "SELECT COUNT(*) FROM (" + query + ") as count_table" - cur.execute(count_query, params) - total = cur.fetchone()[0] - - # Pagination - offset = (page - 1) * per_page - query += f" ORDER BY {sort_field} {order.upper()} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - logs = cur.fetchall() - - # JSON-Werte parsen - parsed_logs = [] - for log in logs: - parsed_log = list(log) - # old_values und new_values sind bereits Dictionaries (JSONB) - # Keine Konvertierung nötig - parsed_logs.append(parsed_log) - - # Pagination Info - total_pages = (total + per_page - 1) // per_page - - cur.close() - conn.close() - - return render_template("audit_log.html", - logs=parsed_logs, - filter_user=filter_user, - filter_action=filter_action, - filter_entity=filter_entity, - page=page, - total_pages=total_pages, - total=total, - sort=sort, - order=order, - username=session.get('username')) - -@app.route("/backups") -@login_required -def backups(): - """Zeigt die Backup-Historie an""" - conn = get_connection() - cur = conn.cursor() - - # Letztes erfolgreiches Backup für Dashboard - cur.execute(""" - SELECT created_at, filesize, duration_seconds - FROM backup_history - WHERE status = 'success' - ORDER BY created_at DESC - LIMIT 1 - """) - last_backup = cur.fetchone() - - # Alle Backups abrufen - cur.execute(""" - SELECT id, filename, filesize, backup_type, status, error_message, - created_at, created_by, tables_count, records_count, - duration_seconds, is_encrypted - FROM backup_history - ORDER BY created_at DESC - """) - backups = cur.fetchall() - - cur.close() - conn.close() - - return render_template("backups.html", - backups=backups, - last_backup=last_backup, - username=session.get('username')) - -@app.route("/backup/create", methods=["POST"]) -@login_required -def create_backup_route(): - """Erstellt ein manuelles Backup""" - username = session.get('username') - success, result = create_backup(backup_type="manual", created_by=username) - - if success: - return jsonify({ - 'success': True, - 'message': f'Backup erfolgreich erstellt: {result}' - }) - else: - return jsonify({ - 'success': False, - 'message': f'Backup fehlgeschlagen: {result}' - }), 500 - -@app.route("/backup/restore/", methods=["POST"]) -@login_required -def restore_backup_route(backup_id): - """Stellt ein Backup wieder her""" - encryption_key = request.form.get('encryption_key') - - success, message = restore_backup(backup_id, encryption_key) - - if success: - return jsonify({ - 'success': True, - 'message': message - }) - else: - return jsonify({ - 'success': False, - 'message': message - }), 500 - -@app.route("/backup/download/") -@login_required -def download_backup(backup_id): - """Lädt eine Backup-Datei herunter""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - cur.close() - conn.close() - - if not backup_info: - return "Backup nicht gefunden", 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - if not filepath.exists(): - return "Backup-Datei nicht gefunden", 404 - - # Audit-Log - log_audit('DOWNLOAD', 'backup', backup_id, - additional_info=f"Backup heruntergeladen: {filename}") - - return send_file(filepath, as_attachment=True, download_name=filename) - -@app.route("/backup/delete/", methods=["DELETE"]) -@login_required -def delete_backup(backup_id): - """Löscht ein Backup""" - conn = get_connection() - cur = conn.cursor() - - try: - # Backup-Informationen abrufen - cur.execute(""" - SELECT filename, filepath - FROM backup_history - WHERE id = %s - """, (backup_id,)) - backup_info = cur.fetchone() - - if not backup_info: - return jsonify({ - 'success': False, - 'message': 'Backup nicht gefunden' - }), 404 - - filename, filepath = backup_info - filepath = Path(filepath) - - # Datei löschen, wenn sie existiert - if filepath.exists(): - filepath.unlink() - - # Aus Datenbank löschen - cur.execute(""" - DELETE FROM backup_history - WHERE id = %s - """, (backup_id,)) - - conn.commit() - - # Audit-Log - log_audit('DELETE', 'backup', backup_id, - additional_info=f"Backup gelöscht: {filename}") - - return jsonify({ - 'success': True, - 'message': f'Backup "{filename}" wurde erfolgreich gelöscht' - }) - - except Exception as e: - conn.rollback() - return jsonify({ - 'success': False, - 'message': f'Fehler beim Löschen des Backups: {str(e)}' - }), 500 - finally: - cur.close() - conn.close() - -@app.route("/security/blocked-ips") -@login_required -def blocked_ips(): - """Zeigt alle gesperrten IPs an""" - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - SELECT - ip_address, - attempt_count, - first_attempt, - last_attempt, - blocked_until, - last_username_tried, - last_error_message - FROM login_attempts - WHERE blocked_until IS NOT NULL - ORDER BY blocked_until DESC - """) - - blocked_ips_list = [] - for ip in cur.fetchall(): - blocked_ips_list.append({ - 'ip_address': ip[0], - 'attempt_count': ip[1], - 'first_attempt': ip[2].strftime('%d.%m.%Y %H:%M'), - 'last_attempt': ip[3].strftime('%d.%m.%Y %H:%M'), - 'blocked_until': ip[4].strftime('%d.%m.%Y %H:%M'), - 'is_active': ip[4] > datetime.now(ZoneInfo("Europe/Berlin")).replace(tzinfo=None), - 'last_username': ip[5], - 'last_error': ip[6] - }) - - cur.close() - conn.close() - - return render_template("blocked_ips.html", - blocked_ips=blocked_ips_list, - username=session.get('username')) - -@app.route("/security/unblock-ip", methods=["POST"]) -@login_required -def unblock_ip(): - """Entsperrt eine IP-Adresse""" - ip_address = request.form.get('ip_address') - - if ip_address: - conn = get_connection() - cur = conn.cursor() - - cur.execute(""" - UPDATE login_attempts - SET blocked_until = NULL - WHERE ip_address = %s - """, (ip_address,)) - - conn.commit() - cur.close() - conn.close() - - # Audit-Log - log_audit('UNBLOCK_IP', 'security', - additional_info=f"IP {ip_address} manuell entsperrt") - - return redirect(url_for('blocked_ips')) - -@app.route("/security/clear-attempts", methods=["POST"]) -@login_required -def clear_attempts(): - """Löscht alle Login-Versuche für eine IP""" - ip_address = request.form.get('ip_address') - - if ip_address: - reset_login_attempts(ip_address) - - # Audit-Log - log_audit('CLEAR_ATTEMPTS', 'security', - additional_info=f"Login-Versuche für IP {ip_address} zurückgesetzt") - - return redirect(url_for('blocked_ips')) - -# API Endpoints for License Management -@app.route("/api/license//toggle", methods=["POST"]) -@login_required -def toggle_license_api(license_id): - """Toggle license active status via API""" - try: - data = request.get_json() - is_active = data.get('is_active', False) - - conn = get_connection() - cur = conn.cursor() - - # Update license status - cur.execute(""" - UPDATE licenses - SET is_active = %s - WHERE id = %s - """, (is_active, license_id)) - - conn.commit() - - # Log the action - log_audit('UPDATE', 'license', license_id, - new_values={'is_active': is_active}, - additional_info=f"Lizenz {'aktiviert' if is_active else 'deaktiviert'} via Toggle") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Status erfolgreich geändert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-activate", methods=["POST"]) -@login_required -def bulk_activate_licenses(): - """Activate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = TRUE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': True, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen aktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen aktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/licenses/bulk-deactivate", methods=["POST"]) -@login_required -def bulk_deactivate_licenses(): - """Deactivate multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Update all selected licenses (nur Live-Daten) - cur.execute(""" - UPDATE licenses - SET is_active = FALSE - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_UPDATE', 'licenses', None, - new_values={'is_active': False, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen deaktiviert") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen deaktiviert'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -@app.route("/api/license//devices") -@login_required -def get_license_devices(license_id): - """Hole alle registrierten Geräte einer Lizenz""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und hole device_limit - cur.execute(""" - SELECT device_limit FROM licenses WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit = license_data[0] - - # Hole alle Geräte für diese Lizenz - cur.execute(""" - SELECT id, hardware_id, device_name, operating_system, - first_seen, last_seen, is_active, ip_address - FROM device_registrations - WHERE license_id = %s - ORDER BY is_active DESC, last_seen DESC - """, (license_id,)) - - devices = [] - for row in cur.fetchall(): - devices.append({ - 'id': row[0], - 'hardware_id': row[1], - 'device_name': row[2] or 'Unbekanntes Gerät', - 'operating_system': row[3] or 'Unbekannt', - 'first_seen': row[4].strftime('%d.%m.%Y %H:%M') if row[4] else '', - 'last_seen': row[5].strftime('%d.%m.%Y %H:%M') if row[5] else '', - 'is_active': row[6], - 'ip_address': row[7] or '-' - }) - - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'devices': devices, - 'device_limit': device_limit, - 'active_count': sum(1 for d in devices if d['is_active']) - }) - - except Exception as e: - logging.error(f"Fehler beim Abrufen der Geräte: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Abrufen der Geräte'}), 500 - -@app.route("/api/license//register-device", methods=["POST"]) -def register_device(license_id): - """Registriere ein neues Gerät für eine Lizenz""" - try: - data = request.get_json() - hardware_id = data.get('hardware_id') - device_name = data.get('device_name', '') - operating_system = data.get('operating_system', '') - - if not hardware_id: - return jsonify({'success': False, 'message': 'Hardware-ID fehlt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Lizenz existiert und aktiv ist - cur.execute(""" - SELECT device_limit, is_active, valid_until - FROM licenses - WHERE id = %s - """, (license_id,)) - license_data = cur.fetchone() - - if not license_data: - return jsonify({'success': False, 'message': 'Lizenz nicht gefunden'}), 404 - - device_limit, is_active, valid_until = license_data - - # Prüfe ob Lizenz aktiv und gültig ist - if not is_active: - return jsonify({'success': False, 'message': 'Lizenz ist deaktiviert'}), 403 - - if valid_until < datetime.now(ZoneInfo("Europe/Berlin")).date(): - return jsonify({'success': False, 'message': 'Lizenz ist abgelaufen'}), 403 - - # Prüfe ob Gerät bereits registriert ist - cur.execute(""" - SELECT id, is_active FROM device_registrations - WHERE license_id = %s AND hardware_id = %s - """, (license_id, hardware_id)) - existing_device = cur.fetchone() - - if existing_device: - device_id, is_device_active = existing_device - if is_device_active: - # Gerät ist bereits aktiv, update last_seen - cur.execute(""" - UPDATE device_registrations - SET last_seen = CURRENT_TIMESTAMP, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät bereits registriert', 'device_id': device_id}) - else: - # Gerät war deaktiviert, prüfe ob wir es reaktivieren können - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Reaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = TRUE, - last_seen = CURRENT_TIMESTAMP, - deactivated_at = NULL, - deactivated_by = NULL, - ip_address = %s, - user_agent = %s - WHERE id = %s - """, (get_client_ip(), request.headers.get('User-Agent', ''), device_id)) - conn.commit() - return jsonify({'success': True, 'message': 'Gerät reaktiviert', 'device_id': device_id}) - - # Neues Gerät - prüfe Gerätelimit - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_id = %s AND is_active = TRUE - """, (license_id,)) - active_count = cur.fetchone()[0] - - if active_count >= device_limit: - return jsonify({'success': False, 'message': f'Gerätelimit erreicht ({device_limit} Geräte)'}), 403 - - # Registriere neues Gerät - cur.execute(""" - INSERT INTO device_registrations - (license_id, hardware_id, device_name, operating_system, ip_address, user_agent) - VALUES (%s, %s, %s, %s, %s, %s) - RETURNING id - """, (license_id, hardware_id, device_name, operating_system, - get_client_ip(), request.headers.get('User-Agent', ''))) - device_id = cur.fetchone()[0] - - conn.commit() - - # Audit Log - log_audit('DEVICE_REGISTER', 'device', device_id, - new_values={'license_id': license_id, 'hardware_id': hardware_id}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich registriert', 'device_id': device_id}) - - except Exception as e: - logging.error(f"Fehler bei Geräte-Registrierung: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler bei der Registrierung'}), 500 - -@app.route("/api/license//deactivate-device/", methods=["POST"]) -@login_required -def deactivate_device(license_id, device_id): - """Deaktiviere ein registriertes Gerät""" - try: - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob das Gerät zu dieser Lizenz gehört - cur.execute(""" - SELECT id FROM device_registrations - WHERE id = %s AND license_id = %s AND is_active = TRUE - """, (device_id, license_id)) - - if not cur.fetchone(): - return jsonify({'success': False, 'message': 'Gerät nicht gefunden oder bereits deaktiviert'}), 404 - - # Deaktiviere das Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = FALSE, - deactivated_at = CURRENT_TIMESTAMP, - deactivated_by = %s - WHERE id = %s - """, (session['username'], device_id)) - - conn.commit() - - # Audit Log - log_audit('DEVICE_DEACTIVATE', 'device', device_id, - old_values={'is_active': True}, - new_values={'is_active': False}) - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': 'Gerät erfolgreich deaktiviert'}) - - except Exception as e: - logging.error(f"Fehler beim Deaktivieren des Geräts: {str(e)}") - return jsonify({'success': False, 'message': 'Fehler beim Deaktivieren'}), 500 - -@app.route("/api/licenses/bulk-delete", methods=["POST"]) -@login_required -def bulk_delete_licenses(): - """Delete multiple licenses at once""" - try: - data = request.get_json() - license_ids = data.get('ids', []) - - if not license_ids: - return jsonify({'success': False, 'message': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - # Get license info for audit log (nur Live-Daten) - cur.execute(""" - SELECT license_key - FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - license_keys = [row[0] for row in cur.fetchall()] - - # Delete all selected licenses (nur Live-Daten) - cur.execute(""" - DELETE FROM licenses - WHERE id = ANY(%s) AND is_test = FALSE - """, (license_ids,)) - - affected_rows = cur.rowcount - conn.commit() - - # Log the bulk action - log_audit('BULK_DELETE', 'licenses', None, - old_values={'license_keys': license_keys, 'count': affected_rows}, - additional_info=f"{affected_rows} Lizenzen gelöscht") - - cur.close() - conn.close() - - return jsonify({'success': True, 'message': f'{affected_rows} Lizenzen gelöscht'}) - except Exception as e: - return jsonify({'success': False, 'message': str(e)}), 500 - -# ===================== RESOURCE POOL MANAGEMENT ===================== - -@app.route('/resources') -@login_required -def resources(): - """Resource Pool Hauptübersicht""" - conn = get_connection() - cur = conn.cursor() - - # Prüfe ob Testdaten angezeigt werden sollen (gleiche Logik wie bei Kunden) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - # Statistiken abrufen - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - WHERE is_test = %s - GROUP BY resource_type - """, (show_test,)) - - stats = {} - for row in cur.fetchall(): - stats[row[0]] = { - 'available': row[1], - 'allocated': row[2], - 'quarantine': row[3], - 'total': row[4], - 'available_percent': round((row[1] / row[4] * 100) if row[4] > 0 else 0, 1) - } - - # Letzte Aktivitäten (gefiltert nach Test/Live) - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rp.resource_type, - rp.resource_value, - rh.details - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - WHERE rp.is_test = %s - ORDER BY rh.action_at DESC - LIMIT 10 - """, (show_test,)) - recent_activities = cur.fetchall() - - # Ressourcen-Liste mit Pagination - page = request.args.get('page', 1, type=int) - per_page = 50 - offset = (page - 1) * per_page - - resource_type = request.args.get('type', '') - status_filter = request.args.get('status', '') - search = request.args.get('search', '') - - # Sortierung - sort_by = request.args.get('sort', 'id') - sort_order = request.args.get('order', 'desc') - - # Base Query - query = """ - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - rp.allocated_to_license, - l.license_key, - c.name as customer_name, - rp.status_changed_at, - rp.quarantine_reason, - rp.quarantine_until, - c.id as customer_id - FROM resource_pools rp - LEFT JOIN licenses l ON rp.allocated_to_license = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rp.is_test = %s - """ - params = [show_test] - - if resource_type: - query += " AND rp.resource_type = %s" - params.append(resource_type) - - if status_filter: - query += " AND rp.status = %s" - params.append(status_filter) - - if search: - query += " AND rp.resource_value ILIKE %s" - params.append(f'%{search}%') - - # Count total - count_query = f"SELECT COUNT(*) FROM ({query}) as cnt" - cur.execute(count_query, params) - total = cur.fetchone()[0] - total_pages = (total + per_page - 1) // per_page - - # Get paginated results with dynamic sorting - sort_column_map = { - 'id': 'rp.id', - 'type': 'rp.resource_type', - 'resource': 'rp.resource_value', - 'status': 'rp.status', - 'assigned': 'c.name', - 'changed': 'rp.status_changed_at' - } - - sort_column = sort_column_map.get(sort_by, 'rp.id') - sort_direction = 'ASC' if sort_order == 'asc' else 'DESC' - - query += f" ORDER BY {sort_column} {sort_direction} LIMIT %s OFFSET %s" - params.extend([per_page, offset]) - - cur.execute(query, params) - resources = cur.fetchall() - - cur.close() - conn.close() - - return render_template('resources.html', - stats=stats, - resources=resources, - recent_activities=recent_activities, - page=page, - total_pages=total_pages, - total=total, - resource_type=resource_type, - status_filter=status_filter, - search=search, - show_test=show_test, - sort_by=sort_by, - sort_order=sort_order, - datetime=datetime, - timedelta=timedelta) - -@app.route('/resources/add', methods=['GET', 'POST']) -@login_required -def add_resources(): - """Ressourcen zum Pool hinzufügen""" - # Hole show_test Parameter für die Anzeige - show_test = request.args.get('show_test', 'false').lower() == 'true' - - if request.method == 'POST': - resource_type = request.form.get('resource_type') - resources_text = request.form.get('resources_text', '') - is_test = request.form.get('is_test') == 'on' # Checkbox für Testdaten - - # Parse resources (one per line) - resources = [r.strip() for r in resources_text.split('\n') if r.strip()] - - if not resources: - flash('Keine Ressourcen angegeben', 'error') - return redirect(url_for('add_resources', show_test=show_test)) - - conn = get_connection() - cur = conn.cursor() - - added = 0 - duplicates = 0 - - for resource_value in resources: - try: - cur.execute(""" - INSERT INTO resource_pools (resource_type, resource_value, status_changed_by, is_test) - VALUES (%s, %s, %s, %s) - ON CONFLICT (resource_type, resource_value) DO NOTHING - """, (resource_type, resource_value, session['username'], is_test)) - - if cur.rowcount > 0: - added += 1 - # Get the inserted ID - cur.execute("SELECT id FROM resource_pools WHERE resource_type = %s AND resource_value = %s", - (resource_type, resource_value)) - resource_id = cur.fetchone()[0] - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'created', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - else: - duplicates += 1 - - except Exception as e: - app.logger.error(f"Error adding resource {resource_value}: {e}") - - conn.commit() - cur.close() - conn.close() - - log_audit('CREATE', 'resource_pool', None, - new_values={'type': resource_type, 'added': added, 'duplicates': duplicates, 'is_test': is_test}, - additional_info=f"{added} {'Test-' if is_test else ''}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen") - - flash(f'{added} {"Test-" if is_test else ""}Ressourcen hinzugefügt, {duplicates} Duplikate übersprungen', 'success') - return redirect(url_for('resources', show_test=show_test)) - - return render_template('add_resources.html', show_test=show_test) - -@app.route('/resources/quarantine/', methods=['POST']) -@login_required -def quarantine_resource(resource_id): - """Ressource in Quarantäne setzen""" - reason = request.form.get('reason', 'review') - until_date = request.form.get('until_date') - notes = request.form.get('notes', '') - - conn = get_connection() - cur = conn.cursor() - - # Get current resource info - cur.execute("SELECT resource_type, resource_value, status FROM resource_pools WHERE id = %s", (resource_id,)) - resource = cur.fetchone() - - if not resource: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - old_status = resource[2] - - # Update resource - cur.execute(""" - UPDATE resource_pools - SET status = 'quarantine', - quarantine_reason = %s, - quarantine_until = %s, - notes = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (reason, until_date if until_date else None, notes, session['username'], resource_id)) - - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address, details) - VALUES (%s, 'quarantined', %s, %s, %s) - """, (resource_id, session['username'], get_client_ip(), - Json({'reason': reason, 'until': until_date, 'notes': notes, 'old_status': old_status}))) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource', resource_id, - old_values={'status': old_status}, - new_values={'status': 'quarantine', 'reason': reason}, - additional_info=f"Ressource {resource[0]}: {resource[1]} in Quarantäne") - - flash('Ressource in Quarantäne gesetzt', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/resources/release', methods=['POST']) -@login_required -def release_resources(): - """Ressourcen aus Quarantäne freigeben""" - resource_ids = request.form.getlist('resource_ids') - - if not resource_ids: - flash('Keine Ressourcen ausgewählt', 'error') - return redirect(url_for('resources')) - - conn = get_connection() - cur = conn.cursor() - - released = 0 - for resource_id in resource_ids: - cur.execute(""" - UPDATE resource_pools - SET status = 'available', - quarantine_reason = NULL, - quarantine_until = NULL, - allocated_to_license = NULL, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s AND status = 'quarantine' - """, (session['username'], resource_id)) - - if cur.rowcount > 0: - released += 1 - # Log in history - cur.execute(""" - INSERT INTO resource_history (resource_id, action, action_by, ip_address) - VALUES (%s, 'released', %s, %s) - """, (resource_id, session['username'], get_client_ip())) - - conn.commit() - cur.close() - conn.close() - - log_audit('UPDATE', 'resource_pool', None, - new_values={'released': released}, - additional_info=f"{released} Ressourcen aus Quarantäne freigegeben") - - flash(f'{released} Ressourcen freigegeben', 'success') - - # Redirect mit allen aktuellen Filtern - return redirect(url_for('resources', - show_test=request.args.get('show_test', request.form.get('show_test', 'false')), - type=request.args.get('type', request.form.get('type', '')), - status=request.args.get('status', request.form.get('status', '')), - search=request.args.get('search', request.form.get('search', '')))) - -@app.route('/api/resources/allocate', methods=['POST']) -@login_required -def allocate_resources_api(): - """API für Ressourcen-Zuweisung bei Lizenzerstellung""" - data = request.json - license_id = data.get('license_id') - domain_count = data.get('domain_count', 1) - ipv4_count = data.get('ipv4_count', 1) - phone_count = data.get('phone_count', 1) - - conn = get_connection() - cur = conn.cursor() - - try: - allocated = {'domains': [], 'ipv4s': [], 'phones': []} - - # Allocate domains - if domain_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'domain' AND status = 'available' - LIMIT %s FOR UPDATE - """, (domain_count,)) - domains = cur.fetchall() - - if len(domains) < domain_count: - raise ValueError(f"Nicht genügend Domains verfügbar (benötigt: {domain_count}, verfügbar: {len(domains)})") - - for domain_id, domain_value in domains: - # Update resource status - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], domain_id)) - - # Create assignment - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, domain_id, session['username'])) - - # Log history - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (domain_id, license_id, session['username'], get_client_ip())) - - allocated['domains'].append(domain_value) - - # Allocate IPv4s (similar logic) - if ipv4_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'ipv4' AND status = 'available' - LIMIT %s FOR UPDATE - """, (ipv4_count,)) - ipv4s = cur.fetchall() - - if len(ipv4s) < ipv4_count: - raise ValueError(f"Nicht genügend IPv4-Adressen verfügbar") - - for ipv4_id, ipv4_value in ipv4s: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], ipv4_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, ipv4_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (ipv4_id, license_id, session['username'], get_client_ip())) - - allocated['ipv4s'].append(ipv4_value) - - # Allocate phones (similar logic) - if phone_count > 0: - cur.execute(""" - SELECT id, resource_value FROM resource_pools - WHERE resource_type = 'phone' AND status = 'available' - LIMIT %s FOR UPDATE - """, (phone_count,)) - phones = cur.fetchall() - - if len(phones) < phone_count: - raise ValueError(f"Nicht genügend Telefonnummern verfügbar") - - for phone_id, phone_value in phones: - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], phone_id)) - - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, phone_id, session['username'])) - - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (phone_id, license_id, session['username'], get_client_ip())) - - allocated['phones'].append(phone_value) - - # Update license resource counts - cur.execute(""" - UPDATE licenses - SET domain_count = %s, - ipv4_count = %s, - phone_count = %s - WHERE id = %s - """, (domain_count, ipv4_count, phone_count, license_id)) - - conn.commit() - cur.close() - conn.close() - - return jsonify({ - 'success': True, - 'allocated': allocated - }) - - except Exception as e: - conn.rollback() - cur.close() - conn.close() - return jsonify({ - 'success': False, - 'error': str(e) - }), 400 - -@app.route('/api/resources/check-availability', methods=['GET']) -@login_required -def check_resource_availability(): - """Prüft verfügbare Ressourcen""" - resource_type = request.args.get('type', '') - count = request.args.get('count', 10, type=int) - show_test = request.args.get('show_test', 'false').lower() == 'true' - - conn = get_connection() - cur = conn.cursor() - - if resource_type: - # Spezifische Ressourcen für einen Typ - cur.execute(""" - SELECT id, resource_value - FROM resource_pools - WHERE status = 'available' - AND resource_type = %s - AND is_test = %s - ORDER BY resource_value - LIMIT %s - """, (resource_type, show_test, count)) - - resources = [] - for row in cur.fetchall(): - resources.append({ - 'id': row[0], - 'value': row[1] - }) - - cur.close() - conn.close() - - return jsonify({ - 'available': resources, - 'type': resource_type, - 'count': len(resources) - }) - else: - # Zusammenfassung aller Typen - cur.execute(""" - SELECT - resource_type, - COUNT(*) as available - FROM resource_pools - WHERE status = 'available' - AND is_test = %s - GROUP BY resource_type - """, (show_test,)) - - availability = {} - for row in cur.fetchall(): - availability[row[0]] = row[1] - - cur.close() - conn.close() - - return jsonify(availability) - -@app.route('/api/global-search', methods=['GET']) -@login_required -def global_search(): - """Global search API endpoint for searching customers and licenses""" - query = request.args.get('q', '').strip() - - if not query or len(query) < 2: - return jsonify({'customers': [], 'licenses': []}) - - conn = get_connection() - cur = conn.cursor() - - # Search pattern with wildcards - search_pattern = f'%{query}%' - - # Search customers - cur.execute(""" - SELECT id, name, email, company_name - FROM customers - WHERE (LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - OR LOWER(company_name) LIKE LOWER(%s)) - AND is_test = FALSE - ORDER BY name - LIMIT 5 - """, (search_pattern, search_pattern, search_pattern)) - - customers = [] - for row in cur.fetchall(): - customers.append({ - 'id': row[0], - 'name': row[1], - 'email': row[2], - 'company_name': row[3] - }) - - # Search licenses - cur.execute(""" - SELECT l.id, l.license_key, c.name as customer_name - FROM licenses l - JOIN customers c ON l.customer_id = c.id - WHERE LOWER(l.license_key) LIKE LOWER(%s) - AND l.is_test = FALSE - ORDER BY l.created_at DESC - LIMIT 5 - """, (search_pattern,)) - - licenses = [] - for row in cur.fetchall(): - licenses.append({ - 'id': row[0], - 'license_key': row[1], - 'customer_name': row[2] - }) - - cur.close() - conn.close() - - return jsonify({ - 'customers': customers, - 'licenses': licenses - }) - -@app.route('/resources/history/') -@login_required -def resource_history(resource_id): - """Zeigt die komplette Historie einer Ressource""" - conn = get_connection() - cur = conn.cursor() - - # Get complete resource info using named columns - cur.execute(""" - SELECT id, resource_type, resource_value, status, allocated_to_license, - status_changed_at, status_changed_by, quarantine_reason, - quarantine_until, created_at, notes - FROM resource_pools - WHERE id = %s - """, (resource_id,)) - row = cur.fetchone() - - if not row: - flash('Ressource nicht gefunden', 'error') - return redirect(url_for('resources')) - - # Create resource object with named attributes - resource = { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'allocated_to_license': row[4], - 'status_changed_at': row[5], - 'status_changed_by': row[6], - 'quarantine_reason': row[7], - 'quarantine_until': row[8], - 'created_at': row[9], - 'notes': row[10] - } - - # Get license info if allocated - license_info = None - if resource['allocated_to_license']: - cur.execute("SELECT license_key FROM licenses WHERE id = %s", - (resource['allocated_to_license'],)) - lic = cur.fetchone() - if lic: - license_info = {'license_key': lic[0]} - - # Get history with named columns - cur.execute(""" - SELECT - rh.action, - rh.action_by, - rh.action_at, - rh.details, - rh.license_id, - rh.ip_address - FROM resource_history rh - WHERE rh.resource_id = %s - ORDER BY rh.action_at DESC - """, (resource_id,)) - - history = [] - for row in cur.fetchall(): - history.append({ - 'action': row[0], - 'action_by': row[1], - 'action_at': row[2], - 'details': row[3], - 'license_id': row[4], - 'ip_address': row[5] - }) - - cur.close() - conn.close() - - # Convert to object-like for template - class ResourceObj: - def __init__(self, data): - for key, value in data.items(): - setattr(self, key, value) - - resource_obj = ResourceObj(resource) - history_objs = [ResourceObj(h) for h in history] - - return render_template('resource_history.html', - resource=resource_obj, - license_info=license_info, - history=history_objs) - -@app.route('/resources/metrics') -@login_required -def resources_metrics(): - """Dashboard für Resource Metrics und Reports""" - conn = get_connection() - cur = conn.cursor() - - # Overall stats with fallback values - cur.execute(""" - SELECT - COUNT(DISTINCT resource_id) as total_resources, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(cost), 0) as total_cost, - COALESCE(SUM(revenue), 0) as total_revenue, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - """) - row = cur.fetchone() - - # Calculate ROI - roi = 0 - if row[2] > 0: # if total_cost > 0 - roi = row[3] / row[2] # revenue / cost - - stats = { - 'total_resources': row[0] or 0, - 'avg_performance': row[1] or 0, - 'total_cost': row[2] or 0, - 'total_revenue': row[3] or 0, - 'total_issues': row[4] or 0, - 'roi': roi - } - - # Performance by type - cur.execute(""" - SELECT - rp.resource_type, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COUNT(DISTINCT rp.id) as resource_count - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY rp.resource_type - ORDER BY rp.resource_type - """) - performance_by_type = cur.fetchall() - - # Utilization data - cur.execute(""" - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) as total, - ROUND(COUNT(*) FILTER (WHERE status = 'allocated') * 100.0 / COUNT(*), 1) as allocated_percent - FROM resource_pools - GROUP BY resource_type - """) - utilization_rows = cur.fetchall() - utilization_data = [ - { - 'type': row[0].upper(), - 'allocated': row[1], - 'total': row[2], - 'allocated_percent': row[3] - } - for row in utilization_rows - ] - - # Top performing resources - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - COALESCE(AVG(rm.performance_score), 0) as avg_score, - COALESCE(SUM(rm.revenue), 0) as total_revenue, - COALESCE(SUM(rm.cost), 1) as total_cost, - CASE - WHEN COALESCE(SUM(rm.cost), 0) = 0 THEN 0 - ELSE COALESCE(SUM(rm.revenue), 0) / COALESCE(SUM(rm.cost), 1) - END as roi - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rp.status != 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value - HAVING AVG(rm.performance_score) IS NOT NULL - ORDER BY avg_score DESC - LIMIT 10 - """) - top_rows = cur.fetchall() - top_performers = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'avg_score': row[3], - 'roi': row[6] - } - for row in top_rows - ] - - # Resources with issues - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.status, - COALESCE(SUM(rm.issues_count), 0) as total_issues - FROM resource_pools rp - LEFT JOIN resource_metrics rm ON rp.id = rm.resource_id - AND rm.metric_date >= CURRENT_DATE - INTERVAL '30 days' - WHERE rm.issues_count > 0 OR rp.status = 'quarantine' - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - HAVING SUM(rm.issues_count) > 0 - ORDER BY total_issues DESC - LIMIT 10 - """) - problem_rows = cur.fetchall() - problem_resources = [ - { - 'id': row[0], - 'resource_type': row[1], - 'resource_value': row[2], - 'status': row[3], - 'total_issues': row[4] - } - for row in problem_rows - ] - - # Daily metrics for trend chart (last 30 days) - cur.execute(""" - SELECT - metric_date, - COALESCE(AVG(performance_score), 0) as avg_performance, - COALESCE(SUM(issues_count), 0) as total_issues - FROM resource_metrics - WHERE metric_date >= CURRENT_DATE - INTERVAL '30 days' - GROUP BY metric_date - ORDER BY metric_date - """) - daily_rows = cur.fetchall() - daily_metrics = [ - { - 'date': row[0].strftime('%d.%m'), - 'performance': float(row[1]), - 'issues': int(row[2]) - } - for row in daily_rows - ] - - cur.close() - conn.close() - - return render_template('resource_metrics.html', - stats=stats, - performance_by_type=performance_by_type, - utilization_data=utilization_data, - top_performers=top_performers, - problem_resources=problem_resources, - daily_metrics=daily_metrics) - -@app.route('/resources/report', methods=['GET']) -@login_required -def resources_report(): - """Generiert Ressourcen-Reports oder zeigt Report-Formular""" - # Prüfe ob Download angefordert wurde - if request.args.get('download') == 'true': - report_type = request.args.get('type', 'usage') - format_type = request.args.get('format', 'excel') - date_from = request.args.get('from', (datetime.now(ZoneInfo("Europe/Berlin")) - timedelta(days=30)).strftime('%Y-%m-%d')) - date_to = request.args.get('to', datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y-%m-%d')) - - conn = get_connection() - cur = conn.cursor() - - if report_type == 'usage': - # Auslastungsreport - query = """ - SELECT - rp.resource_type, - rp.resource_value, - rp.status, - COUNT(DISTINCT rh.license_id) as unique_licenses, - COUNT(rh.id) as total_allocations, - MIN(rh.action_at) as first_used, - MAX(rh.action_at) as last_used - FROM resource_pools rp - LEFT JOIN resource_history rh ON rp.id = rh.resource_id - AND rh.action = 'allocated' - AND rh.action_at BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value, rp.status - ORDER BY rp.resource_type, total_allocations DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Status', 'Unique Lizenzen', 'Gesamt Zuweisungen', 'Erste Nutzung', 'Letzte Nutzung'] - - elif report_type == 'performance': - # Performance-Report - query = """ - SELECT - rp.resource_type, - rp.resource_value, - AVG(rm.performance_score) as avg_performance, - SUM(rm.usage_count) as total_usage, - SUM(rm.revenue) as total_revenue, - SUM(rm.cost) as total_cost, - SUM(rm.revenue - rm.cost) as profit, - SUM(rm.issues_count) as total_issues - FROM resource_pools rp - JOIN resource_metrics rm ON rp.id = rm.resource_id - WHERE rm.metric_date BETWEEN %s AND %s - GROUP BY rp.id, rp.resource_type, rp.resource_value - ORDER BY profit DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Typ', 'Ressource', 'Durchschn. Performance', 'Gesamt Nutzung', 'Umsatz', 'Kosten', 'Gewinn', 'Issues'] - - elif report_type == 'compliance': - # Compliance-Report - query = """ - SELECT - rh.action_at, - rh.action, - rh.action_by, - rp.resource_type, - rp.resource_value, - l.license_key, - c.name as customer_name, - rh.ip_address - FROM resource_history rh - JOIN resource_pools rp ON rh.resource_id = rp.id - LEFT JOIN licenses l ON rh.license_id = l.id - LEFT JOIN customers c ON l.customer_id = c.id - WHERE rh.action_at BETWEEN %s AND %s - ORDER BY rh.action_at DESC - """ - cur.execute(query, (date_from, date_to)) - columns = ['Zeit', 'Aktion', 'Von', 'Typ', 'Ressource', 'Lizenz', 'Kunde', 'IP-Adresse'] - - else: # inventory report - # Inventar-Report - query = """ - SELECT - resource_type, - COUNT(*) FILTER (WHERE status = 'available') as available, - COUNT(*) FILTER (WHERE status = 'allocated') as allocated, - COUNT(*) FILTER (WHERE status = 'quarantine') as quarantine, - COUNT(*) as total - FROM resource_pools - GROUP BY resource_type - ORDER BY resource_type - """ - cur.execute(query) - columns = ['Typ', 'Verfügbar', 'Zugeteilt', 'Quarantäne', 'Gesamt'] - - # Convert to DataFrame - data = cur.fetchall() - df = pd.DataFrame(data, columns=columns) - - cur.close() - conn.close() - - # Generate file - timestamp = datetime.now(ZoneInfo("Europe/Berlin")).strftime('%Y%m%d_%H%M%S') - filename = f"resource_report_{report_type}_{timestamp}" - - if format_type == 'excel': - output = io.BytesIO() - with pd.ExcelWriter(output, engine='openpyxl') as writer: - df.to_excel(writer, sheet_name='Report', index=False) - - # Auto-adjust columns width - worksheet = writer.sheets['Report'] - for column in worksheet.columns: - max_length = 0 - column = [cell for cell in column] - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = (max_length + 2) - worksheet.column_dimensions[column[0].column_letter].width = adjusted_width - - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'excel', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(output, - mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - as_attachment=True, - download_name=f'{filename}.xlsx') - - else: # CSV - output = io.StringIO() - df.to_csv(output, index=False, sep=';', encoding='utf-8-sig') - output.seek(0) - - log_audit('EXPORT', 'resource_report', None, - new_values={'type': report_type, 'format': 'csv', 'rows': len(df)}, - additional_info=f"Resource Report {report_type} exportiert") - - return send_file(io.BytesIO(output.getvalue().encode('utf-8-sig')), - mimetype='text/csv', - as_attachment=True, - download_name=f'{filename}.csv') - - # Wenn kein Download, zeige Report-Formular - return render_template('resource_report.html', - datetime=datetime, - timedelta=timedelta, - username=session.get('username')) - -if __name__ == "__main__": - app.run(host="0.0.0.0", port=5000) diff --git a/v2_adminpanel/cleanup_commented_routes.py b/v2_adminpanel/cleanup_commented_routes.py deleted file mode 100644 index 9422603..0000000 --- a/v2_adminpanel/cleanup_commented_routes.py +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env python3 -""" -Cleanup-Skript zum sicheren Entfernen auskommentierter Routes aus app.py -Entfernt alle auskommentierten @app.route Blöcke nach der Blueprint-Migration -""" - -import re -import sys -from datetime import datetime - -def cleanup_commented_routes(file_path): - """Entfernt auskommentierte Route-Blöcke aus app.py""" - - with open(file_path, 'r', encoding='utf-8') as f: - lines = f.readlines() - - print(f"📄 Datei geladen: {len(lines)} Zeilen") - - cleaned_lines = [] - in_commented_block = False - block_start_line = -1 - removed_blocks = [] - - i = 0 - while i < len(lines): - line = lines[i] - - # Prüfe ob eine auskommentierte Route beginnt - if re.match(r'^# @app\.route\(', line.strip()): - in_commented_block = True - block_start_line = i + 1 # 1-basiert für Anzeige - block_lines = [line] - i += 1 - - # Sammle den ganzen auskommentierten Block - while i < len(lines): - current_line = lines[i] - - # Block endet wenn: - # 1. Eine neue Funktion/Route beginnt (nicht auskommentiert) - # 2. Eine Leerzeile nach mehreren kommentierten Zeilen - # 3. Eine neue auskommentierte Route beginnt - - if re.match(r'^@', current_line.strip()) or \ - re.match(r'^def\s+\w+', current_line.strip()) or \ - re.match(r'^class\s+\w+', current_line.strip()): - # Nicht-kommentierter Code gefunden, Block endet - break - - if re.match(r'^# @app\.route\(', current_line.strip()) and len(block_lines) > 1: - # Neue auskommentierte Route, vorheriger Block endet - break - - # Prüfe ob die Zeile zum kommentierten Block gehört - if current_line.strip() == '' and i + 1 < len(lines): - # Schaue voraus - next_line = lines[i + 1] - if not (next_line.strip().startswith('#') or next_line.strip() == ''): - # Leerzeile gefolgt von nicht-kommentiertem Code - block_lines.append(current_line) - i += 1 - break - - if current_line.strip().startswith('#') or current_line.strip() == '': - block_lines.append(current_line) - i += 1 - else: - # Nicht-kommentierte Zeile gefunden, Block endet - break - - # Entferne trailing Leerzeilen vom Block - while block_lines and block_lines[-1].strip() == '': - block_lines.pop() - i -= 1 - - removed_blocks.append({ - 'start_line': block_start_line, - 'end_line': block_start_line + len(block_lines) - 1, - 'lines': len(block_lines), - 'route': extract_route_info(block_lines) - }) - - in_commented_block = False - - # Füge eine Leerzeile ein wenn nötig (um Abstand zu wahren) - if cleaned_lines and cleaned_lines[-1].strip() != '' and \ - i < len(lines) and lines[i].strip() != '': - cleaned_lines.append('\n') - - else: - cleaned_lines.append(line) - i += 1 - - return cleaned_lines, removed_blocks - -def extract_route_info(block_lines): - """Extrahiert Route-Information aus dem kommentierten Block""" - for line in block_lines: - match = re.search(r'# @app\.route\("([^"]+)"', line) - if match: - return match.group(1) - return "Unknown" - -def main(): - file_path = 'app.py' - backup_path = f'app.py.backup_before_cleanup_{datetime.now().strftime("%Y%m%d_%H%M%S")}' - - print("🧹 Starte Cleanup der auskommentierten Routes...\n") - - # Backup erstellen - print(f"💾 Erstelle Backup: {backup_path}") - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - with open(backup_path, 'w', encoding='utf-8') as f: - f.write(content) - - # Cleanup durchführen - cleaned_lines, removed_blocks = cleanup_commented_routes(file_path) - - # Statistiken anzeigen - print(f"\n📊 Cleanup-Statistiken:") - print(f" Entfernte Blöcke: {len(removed_blocks)}") - print(f" Entfernte Zeilen: {sum(block['lines'] for block in removed_blocks)}") - print(f" Neue Dateigröße: {len(cleaned_lines)} Zeilen") - - print(f"\n🗑️ Entfernte Routes:") - for block in removed_blocks: - print(f" Zeilen {block['start_line']}-{block['end_line']}: {block['route']} ({block['lines']} Zeilen)") - - # Bestätigung abfragen - print(f"\n⚠️ Diese Operation wird {sum(block['lines'] for block in removed_blocks)} Zeilen entfernen!") - response = input("Fortfahren? (ja/nein): ") - - if response.lower() in ['ja', 'j', 'yes', 'y']: - # Bereinigte Datei schreiben - with open(file_path, 'w', encoding='utf-8') as f: - f.writelines(cleaned_lines) - print(f"\n✅ Cleanup abgeschlossen! Backup gespeichert als: {backup_path}") - - # Größenvergleich - import os - old_size = os.path.getsize(backup_path) - new_size = os.path.getsize(file_path) - reduction = old_size - new_size - reduction_percent = (reduction / old_size) * 100 - - print(f"\n📉 Dateigrößen-Reduktion:") - print(f" Vorher: {old_size:,} Bytes") - print(f" Nachher: {new_size:,} Bytes") - print(f" Reduziert um: {reduction:,} Bytes ({reduction_percent:.1f}%)") - - else: - print("\n❌ Cleanup abgebrochen. Keine Änderungen vorgenommen.") - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/v2_adminpanel/cleanup_commented_routes_auto.py b/v2_adminpanel/cleanup_commented_routes_auto.py deleted file mode 100644 index ad50790..0000000 --- a/v2_adminpanel/cleanup_commented_routes_auto.py +++ /dev/null @@ -1,153 +0,0 @@ -#!/usr/bin/env python3 -""" -Automatisches Cleanup-Skript zum Entfernen auskommentierter Routes aus app.py -Führt das Cleanup ohne Benutzerinteraktion durch -""" - -import re -import sys -from datetime import datetime -import os - -def cleanup_commented_routes(file_path): - """Entfernt auskommentierte Route-Blöcke aus app.py""" - - with open(file_path, 'r', encoding='utf-8') as f: - lines = f.readlines() - - print(f"📄 Datei geladen: {len(lines)} Zeilen") - - cleaned_lines = [] - removed_blocks = [] - - i = 0 - while i < len(lines): - line = lines[i] - - # Prüfe ob eine auskommentierte Route beginnt - if re.match(r'^# @app\.route\(', line.strip()): - block_start_line = i + 1 # 1-basiert für Anzeige - block_lines = [line] - i += 1 - - # Sammle den ganzen auskommentierten Block - while i < len(lines): - current_line = lines[i] - - # Block endet wenn: - # 1. Eine neue Funktion/Route beginnt (nicht auskommentiert) - # 2. Eine neue auskommentierte Route beginnt - # 3. Nicht-kommentierter Code gefunden wird - - if re.match(r'^@', current_line.strip()) or \ - re.match(r'^def\s+\w+', current_line.strip()) or \ - re.match(r'^class\s+\w+', current_line.strip()): - # Nicht-kommentierter Code gefunden, Block endet - break - - if re.match(r'^# @app\.route\(', current_line.strip()) and len(block_lines) > 1: - # Neue auskommentierte Route, vorheriger Block endet - break - - # Prüfe ob die Zeile zum kommentierten Block gehört - if current_line.strip() == '' and i + 1 < len(lines): - # Schaue voraus - next_line = lines[i + 1] - if not (next_line.strip().startswith('#') or next_line.strip() == ''): - # Leerzeile gefolgt von nicht-kommentiertem Code - block_lines.append(current_line) - i += 1 - break - - if current_line.strip().startswith('#') or current_line.strip() == '': - block_lines.append(current_line) - i += 1 - else: - # Nicht-kommentierte Zeile gefunden, Block endet - break - - # Entferne trailing Leerzeilen vom Block - while block_lines and block_lines[-1].strip() == '': - block_lines.pop() - i -= 1 - - removed_blocks.append({ - 'start_line': block_start_line, - 'end_line': block_start_line + len(block_lines) - 1, - 'lines': len(block_lines), - 'route': extract_route_info(block_lines) - }) - - # Füge eine Leerzeile ein wenn nötig (um Abstand zu wahren) - if cleaned_lines and cleaned_lines[-1].strip() != '' and \ - i < len(lines) and lines[i].strip() != '': - cleaned_lines.append('\n') - - else: - cleaned_lines.append(line) - i += 1 - - return cleaned_lines, removed_blocks - -def extract_route_info(block_lines): - """Extrahiert Route-Information aus dem kommentierten Block""" - for line in block_lines: - match = re.search(r'# @app\.route\("([^"]+)"', line) - if match: - return match.group(1) - return "Unknown" - -def main(): - file_path = 'app.py' - backup_path = f'app.py.backup_before_cleanup_{datetime.now().strftime("%Y%m%d_%H%M%S")}' - - print("🧹 Starte automatisches Cleanup der auskommentierten Routes...\n") - - # Backup erstellen - print(f"💾 Erstelle Backup: {backup_path}") - with open(file_path, 'r', encoding='utf-8') as f: - content = f.read() - with open(backup_path, 'w', encoding='utf-8') as f: - f.write(content) - - # Cleanup durchführen - cleaned_lines, removed_blocks = cleanup_commented_routes(file_path) - - # Statistiken anzeigen - print(f"\n📊 Cleanup-Statistiken:") - print(f" Entfernte Blöcke: {len(removed_blocks)}") - print(f" Entfernte Zeilen: {sum(block['lines'] for block in removed_blocks)}") - print(f" Neue Dateigröße: {len(cleaned_lines)} Zeilen") - - if len(removed_blocks) > 10: - print(f"\n🗑️ Erste 10 entfernte Routes:") - for block in removed_blocks[:10]: - print(f" Zeilen {block['start_line']}-{block['end_line']}: {block['route']} ({block['lines']} Zeilen)") - print(f" ... und {len(removed_blocks) - 10} weitere Routes") - else: - print(f"\n🗑️ Entfernte Routes:") - for block in removed_blocks: - print(f" Zeilen {block['start_line']}-{block['end_line']}: {block['route']} ({block['lines']} Zeilen)") - - # Bereinigte Datei schreiben - print(f"\n✍️ Schreibe bereinigte Datei...") - with open(file_path, 'w', encoding='utf-8') as f: - f.writelines(cleaned_lines) - - # Größenvergleich - old_size = os.path.getsize(backup_path) - new_size = os.path.getsize(file_path) - reduction = old_size - new_size - reduction_percent = (reduction / old_size) * 100 - - print(f"\n📉 Dateigrößen-Reduktion:") - print(f" Vorher: {old_size:,} Bytes") - print(f" Nachher: {new_size:,} Bytes") - print(f" Reduziert um: {reduction:,} Bytes ({reduction_percent:.1f}%)") - - print(f"\n✅ Cleanup erfolgreich abgeschlossen!") - print(f" Backup: {backup_path}") - print(f" Rollback möglich mit: cp {backup_path} app.py") - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/v2_adminpanel/cookies.txt b/v2_adminpanel/cookies.txt deleted file mode 100644 index bc84d1a..0000000 --- a/v2_adminpanel/cookies.txt +++ /dev/null @@ -1,5 +0,0 @@ -# Netscape HTTP Cookie File -# https://curl.se/docs/http-cookies.html -# This file was generated by libcurl! Edit at your own risk. - -#HttpOnly_localhost FALSE / FALSE 1749329847 admin_session aojqyq4GcSt5oT7NJPeg7UHPoEZUVkn-s1Kr-EAnJWM diff --git a/v2_adminpanel/create_users_table.sql b/v2_adminpanel/create_users_table.sql deleted file mode 100644 index 202f4e8..0000000 --- a/v2_adminpanel/create_users_table.sql +++ /dev/null @@ -1,20 +0,0 @@ --- Create users table if it doesn't exist -CREATE TABLE IF NOT EXISTS users ( - id SERIAL PRIMARY KEY, - username VARCHAR(50) UNIQUE NOT NULL, - password_hash VARCHAR(255) NOT NULL, - email VARCHAR(100), - totp_secret VARCHAR(32), - totp_enabled BOOLEAN DEFAULT FALSE, - backup_codes TEXT, -- JSON array of hashed backup codes - created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, - last_password_change TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, - password_reset_token VARCHAR(64), - password_reset_expires TIMESTAMP WITH TIME ZONE, - failed_2fa_attempts INTEGER DEFAULT 0, - last_failed_2fa TIMESTAMP WITH TIME ZONE -); - --- Index for faster login lookups -CREATE INDEX IF NOT EXISTS idx_users_username ON users(username); -CREATE INDEX IF NOT EXISTS idx_users_reset_token ON users(password_reset_token) WHERE password_reset_token IS NOT NULL; \ No newline at end of file diff --git a/v2_adminpanel/fix_license_keys.sql b/v2_adminpanel/fix_license_keys.sql deleted file mode 100644 index da6c431..0000000 --- a/v2_adminpanel/fix_license_keys.sql +++ /dev/null @@ -1,13 +0,0 @@ --- Fix für die fehlerhafte Migration - entfernt doppelte Bindestriche -UPDATE licenses -SET license_key = REPLACE(license_key, 'AF--', 'AF-') -WHERE license_key LIKE 'AF--%'; - -UPDATE licenses -SET license_key = REPLACE(license_key, '6--', '6-') -WHERE license_key LIKE '%6--%'; - --- Zeige die korrigierten Keys -SELECT id, license_key, license_type -FROM licenses -ORDER BY id; \ No newline at end of file diff --git a/v2_adminpanel/mark_resources_as_test.sql b/v2_adminpanel/mark_resources_as_test.sql deleted file mode 100644 index 2377e7a..0000000 --- a/v2_adminpanel/mark_resources_as_test.sql +++ /dev/null @@ -1,5 +0,0 @@ --- Markiere alle existierenden Ressourcen als Testdaten -UPDATE resource_pools SET is_test = TRUE WHERE is_test = FALSE OR is_test IS NULL; - --- Zeige Anzahl der aktualisierten Ressourcen -SELECT COUNT(*) as updated_resources FROM resource_pools WHERE is_test = TRUE; \ No newline at end of file diff --git a/v2_adminpanel/migrate_device_limit.sql b/v2_adminpanel/migrate_device_limit.sql deleted file mode 100644 index d62291f..0000000 --- a/v2_adminpanel/migrate_device_limit.sql +++ /dev/null @@ -1,13 +0,0 @@ --- Migration: Setze device_limit für bestehende Test-Lizenzen auf 3 --- Dieses Script wird nur einmal ausgeführt, um bestehende Lizenzen zu aktualisieren - --- Setze device_limit = 3 für alle bestehenden Lizenzen, die noch keinen Wert haben -UPDATE licenses -SET device_limit = 3 -WHERE device_limit IS NULL; - --- Bestätige die Änderung -SELECT COUNT(*) as updated_licenses, - COUNT(CASE WHEN is_test = TRUE THEN 1 END) as test_licenses_updated -FROM licenses -WHERE device_limit = 3; \ No newline at end of file diff --git a/v2_adminpanel/migrate_license_keys.sql b/v2_adminpanel/migrate_license_keys.sql deleted file mode 100644 index 6ff91e6..0000000 --- a/v2_adminpanel/migrate_license_keys.sql +++ /dev/null @@ -1,54 +0,0 @@ --- Migration der Lizenzschlüssel vom alten Format zum neuen Format --- Alt: AF-YYYYMMFT-XXXX-YYYY-ZZZZ --- Neu: AF-F-YYYYMM-XXXX-YYYY-ZZZZ - --- Backup der aktuellen Schlüssel erstellen (für Sicherheit) -CREATE TEMP TABLE license_backup AS -SELECT id, license_key FROM licenses; - --- Update für Fullversion Keys (F) -UPDATE licenses -SET license_key = - CONCAT( - SUBSTRING(license_key, 1, 3), -- 'AF-' - '-F-', - SUBSTRING(license_key, 4, 6), -- 'YYYYMM' - '-', - SUBSTRING(license_key, 11) -- Rest des Keys - ) -WHERE license_key LIKE 'AF-%F-%' - AND license_type = 'full' - AND license_key NOT LIKE 'AF-F-%'; -- Nicht bereits migriert - --- Update für Testversion Keys (T) -UPDATE licenses -SET license_key = - CONCAT( - SUBSTRING(license_key, 1, 3), -- 'AF-' - '-T-', - SUBSTRING(license_key, 4, 6), -- 'YYYYMM' - '-', - SUBSTRING(license_key, 11) -- Rest des Keys - ) -WHERE license_key LIKE 'AF-%T-%' - AND license_type = 'test' - AND license_key NOT LIKE 'AF-T-%'; -- Nicht bereits migriert - --- Zeige die Änderungen -SELECT - b.license_key as old_key, - l.license_key as new_key, - l.license_type -FROM licenses l -JOIN license_backup b ON l.id = b.id -WHERE b.license_key != l.license_key -ORDER BY l.id; - --- Anzahl der migrierten Keys -SELECT - COUNT(*) as total_migrated, - SUM(CASE WHEN license_type = 'full' THEN 1 ELSE 0 END) as full_licenses, - SUM(CASE WHEN license_type = 'test' THEN 1 ELSE 0 END) as test_licenses -FROM licenses l -JOIN license_backup b ON l.id = b.id -WHERE b.license_key != l.license_key; \ No newline at end of file diff --git a/v2_adminpanel/migrate_users.py b/v2_adminpanel/migrate_users.py deleted file mode 100644 index 106833d..0000000 --- a/v2_adminpanel/migrate_users.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python3 -""" -Migration script to create initial users in the database from environment variables -Run this once after creating the users table -""" - -import os -import psycopg2 -import bcrypt -from dotenv import load_dotenv -from datetime import datetime - -load_dotenv() - -def get_connection(): - return psycopg2.connect( - host=os.getenv("POSTGRES_HOST", "postgres"), - port=os.getenv("POSTGRES_PORT", "5432"), - dbname=os.getenv("POSTGRES_DB"), - user=os.getenv("POSTGRES_USER"), - password=os.getenv("POSTGRES_PASSWORD"), - options='-c client_encoding=UTF8' - ) - -def hash_password(password): - return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') - -def migrate_users(): - conn = get_connection() - cur = conn.cursor() - - try: - # Check if users already exist - cur.execute("SELECT COUNT(*) FROM users") - user_count = cur.fetchone()[0] - - if user_count > 0: - print(f"Users table already contains {user_count} users. Skipping migration.") - return - - # Get admin users from environment - admin1_user = os.getenv("ADMIN1_USERNAME") - admin1_pass = os.getenv("ADMIN1_PASSWORD") - admin2_user = os.getenv("ADMIN2_USERNAME") - admin2_pass = os.getenv("ADMIN2_PASSWORD") - - if not all([admin1_user, admin1_pass, admin2_user, admin2_pass]): - print("ERROR: Admin credentials not found in environment variables!") - return - - # Insert admin users - users = [ - (admin1_user, hash_password(admin1_pass), f"{admin1_user}@v2-admin.local"), - (admin2_user, hash_password(admin2_pass), f"{admin2_user}@v2-admin.local") - ] - - for username, password_hash, email in users: - cur.execute(""" - INSERT INTO users (username, password_hash, email, totp_enabled, created_at) - VALUES (%s, %s, %s, %s, %s) - """, (username, password_hash, email, False, datetime.now())) - print(f"Created user: {username}") - - conn.commit() - print("\nMigration completed successfully!") - print("Users can now log in with their existing credentials.") - print("They can enable 2FA from their profile page.") - - except Exception as e: - conn.rollback() - print(f"ERROR during migration: {e}") - finally: - cur.close() - conn.close() - -if __name__ == "__main__": - print("Starting user migration...") - migrate_users() \ No newline at end of file diff --git a/v2_adminpanel/remove_duplicate_routes.py b/v2_adminpanel/remove_duplicate_routes.py deleted file mode 100644 index 648aab0..0000000 --- a/v2_adminpanel/remove_duplicate_routes.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python3 -""" -Remove duplicate routes that have been moved to blueprints -""" - -import re - -# Read the current app.py -with open('app.py', 'r') as f: - content = f.read() - -# List of function names that have been moved to blueprints -moved_functions = [ - # Auth routes - 'login', - 'logout', - 'verify_2fa', - 'profile', - 'change_password', - 'setup_2fa', - 'enable_2fa', - 'disable_2fa', - 'heartbeat', - # Admin routes - 'dashboard', - 'audit_log', - 'backups', - 'create_backup_route', - 'restore_backup_route', - 'download_backup', - 'delete_backup', - 'blocked_ips', - 'unblock_ip', - 'clear_attempts' -] - -# Create a pattern to match route decorators and their functions -for func_name in moved_functions: - # Pattern to match from @app.route to the end of the function - pattern = rf'@app\.route\([^)]+\)\s*(?:@login_required\s*)?def {func_name}\([^)]*\):.*?(?=\n@app\.route|\n@[a-zA-Z]|\nif __name__|$)' - - # Replace with a comment - replacement = f'# Function {func_name} moved to blueprint' - - content = re.sub(pattern, replacement, content, flags=re.DOTALL) - -# Write the modified content -with open('app_no_duplicates.py', 'w') as f: - f.write(content) - -print("Created app_no_duplicates.py with duplicate routes removed") -print("Please review the file before using it") \ No newline at end of file diff --git a/v2_adminpanel/routes/__pycache__/__init__.cpython-312.pyc b/v2_adminpanel/routes/__pycache__/__init__.cpython-312.pyc index d28b39d..a81c845 100644 Binary files a/v2_adminpanel/routes/__pycache__/__init__.cpython-312.pyc and b/v2_adminpanel/routes/__pycache__/__init__.cpython-312.pyc differ diff --git a/v2_adminpanel/routes/__pycache__/admin_routes.cpython-312.pyc b/v2_adminpanel/routes/__pycache__/admin_routes.cpython-312.pyc new file mode 100644 index 0000000..90c7614 Binary files /dev/null and b/v2_adminpanel/routes/__pycache__/admin_routes.cpython-312.pyc differ diff --git a/v2_adminpanel/routes/__pycache__/api_routes.cpython-312.pyc b/v2_adminpanel/routes/__pycache__/api_routes.cpython-312.pyc new file mode 100644 index 0000000..1b4b531 Binary files /dev/null and b/v2_adminpanel/routes/__pycache__/api_routes.cpython-312.pyc differ diff --git a/v2_adminpanel/routes/__pycache__/auth_routes.cpython-312.pyc b/v2_adminpanel/routes/__pycache__/auth_routes.cpython-312.pyc new file mode 100644 index 0000000..e6d9a8c Binary files /dev/null and b/v2_adminpanel/routes/__pycache__/auth_routes.cpython-312.pyc differ diff --git a/v2_adminpanel/routes/__pycache__/batch_routes.cpython-312.pyc b/v2_adminpanel/routes/__pycache__/batch_routes.cpython-312.pyc new file mode 100644 index 0000000..753606e Binary files /dev/null and b/v2_adminpanel/routes/__pycache__/batch_routes.cpython-312.pyc differ diff --git a/v2_adminpanel/routes/__pycache__/customer_routes.cpython-312.pyc b/v2_adminpanel/routes/__pycache__/customer_routes.cpython-312.pyc index ccb85f5..7b5b6b0 100644 Binary files a/v2_adminpanel/routes/__pycache__/customer_routes.cpython-312.pyc and b/v2_adminpanel/routes/__pycache__/customer_routes.cpython-312.pyc differ diff --git a/v2_adminpanel/routes/__pycache__/export_routes.cpython-312.pyc b/v2_adminpanel/routes/__pycache__/export_routes.cpython-312.pyc new file mode 100644 index 0000000..3f0aaae Binary files /dev/null and b/v2_adminpanel/routes/__pycache__/export_routes.cpython-312.pyc differ diff --git a/v2_adminpanel/routes/__pycache__/license_routes.cpython-312.pyc b/v2_adminpanel/routes/__pycache__/license_routes.cpython-312.pyc new file mode 100644 index 0000000..c0baaf7 Binary files /dev/null and b/v2_adminpanel/routes/__pycache__/license_routes.cpython-312.pyc differ diff --git a/v2_adminpanel/routes/__pycache__/resource_routes.cpython-312.pyc b/v2_adminpanel/routes/__pycache__/resource_routes.cpython-312.pyc new file mode 100644 index 0000000..34962e3 Binary files /dev/null and b/v2_adminpanel/routes/__pycache__/resource_routes.cpython-312.pyc differ diff --git a/v2_adminpanel/routes/__pycache__/session_routes.cpython-312.pyc b/v2_adminpanel/routes/__pycache__/session_routes.cpython-312.pyc new file mode 100644 index 0000000..d1abdb6 Binary files /dev/null and b/v2_adminpanel/routes/__pycache__/session_routes.cpython-312.pyc differ diff --git a/v2_adminpanel/routes/api_routes.py b/v2_adminpanel/routes/api_routes.py index 46da9a6..7d1e834 100644 --- a/v2_adminpanel/routes/api_routes.py +++ b/v2_adminpanel/routes/api_routes.py @@ -65,22 +65,22 @@ def toggle_license(license_id): if not license_data: return jsonify({'error': 'Lizenz nicht gefunden'}), 404 - new_status = not license_data['active'] + new_status = not license_data['is_active'] # Update status - cur.execute("UPDATE licenses SET active = %s WHERE id = %s", (new_status, license_id)) + cur.execute("UPDATE licenses SET is_active = %s WHERE id = %s", (new_status, license_id)) conn.commit() # Log change log_audit('TOGGLE', 'license', license_id, - old_values={'active': license_data['active']}, - new_values={'active': new_status}) + old_values={'is_active': license_data['is_active']}, + new_values={'is_active': new_status}) - return jsonify({'success': True, 'active': new_status}) + return jsonify({'success': True, 'is_active': new_status}) except Exception as e: conn.rollback() - logging.error(f"Fehler beim Umschalten der Lizenz: {str(e)}") + logging.error(f"Fehler beim Umschalten der Lizenz: {str(e)}", exc_info=True) return jsonify({'error': 'Fehler beim Umschalten der Lizenz'}), 500 finally: cur.close() @@ -104,8 +104,8 @@ def bulk_activate_licenses(): # Update all selected licenses cur.execute(""" UPDATE licenses - SET active = true - WHERE id = ANY(%s) AND active = false + SET is_active = true + WHERE id = ANY(%s) AND is_active = false RETURNING id """, (license_ids,)) @@ -115,7 +115,7 @@ def bulk_activate_licenses(): # Log changes for license_id in updated_ids: log_audit('BULK_ACTIVATE', 'license', license_id, - new_values={'active': True}) + new_values={'is_active': True}) return jsonify({ 'success': True, @@ -148,8 +148,8 @@ def bulk_deactivate_licenses(): # Update all selected licenses cur.execute(""" UPDATE licenses - SET active = false - WHERE id = ANY(%s) AND active = true + SET is_active = false + WHERE id = ANY(%s) AND is_active = true RETURNING id """, (license_ids,)) @@ -159,7 +159,7 @@ def bulk_deactivate_licenses(): # Log changes for license_id in updated_ids: log_audit('BULK_DEACTIVATE', 'license', license_id, - new_values={'active': False}) + new_values={'is_active': False}) return jsonify({ 'success': True, @@ -451,10 +451,10 @@ def quick_edit_license(license_id): new_values['valid_until'] = data['valid_until'] if 'active' in data: - updates.append("active = %s") + updates.append("is_active = %s") params.append(bool(data['active'])) - old_values['active'] = current_license['active'] - new_values['active'] = bool(data['active']) + old_values['is_active'] = current_license['is_active'] + new_values['is_active'] = bool(data['active']) if not updates: return jsonify({'error': 'Keine Änderungen angegeben'}), 400 @@ -797,7 +797,7 @@ def global_search(): try: # Suche in Lizenzen cur.execute(""" - SELECT id, license_key, customer_name, active + SELECT id, license_key, customer_name, is_active FROM licenses WHERE license_key ILIKE %s OR customer_name ILIKE %s @@ -810,7 +810,7 @@ def global_search(): 'id': row[0], 'license_key': row[1], 'customer_name': row[2], - 'active': row[3] + 'is_active': row[3] }) # Suche in Kunden diff --git a/v2_adminpanel/routes/api_routes.py.backup b/v2_adminpanel/routes/api_routes.py.backup deleted file mode 100644 index 8f49f25..0000000 --- a/v2_adminpanel/routes/api_routes.py.backup +++ /dev/null @@ -1,943 +0,0 @@ -import logging -from datetime import datetime -from zoneinfo import ZoneInfo -from flask import Blueprint, request, jsonify, session - -import config -from auth.decorators import login_required -from utils.audit import log_audit -from utils.network import get_client_ip -from utils.license import generate_license_key -from db import get_connection, get_db_connection, get_db_cursor -from models import get_license_by_id, get_customers - -# Create Blueprint -api_bp = Blueprint('api', __name__, url_prefix='/api') - - -@api_bp.route("/customers", methods=["GET"]) -@login_required -def api_customers(): - """API endpoint for customer search (used by Select2)""" - search = request.args.get('q', '').strip() - page = int(request.args.get('page', 1)) - per_page = 20 - - try: - # Get all customers (with optional search) - customers = get_customers(show_test=True, search=search) - - # Pagination - start = (page - 1) * per_page - end = start + per_page - paginated_customers = customers[start:end] - - # Format for Select2 - results = [] - for customer in paginated_customers: - results.append({ - 'id': customer['id'], - 'text': f"{customer['name']} ({customer['email'] or 'keine E-Mail'})" - }) - - return jsonify({ - 'results': results, - 'pagination': { - 'more': len(customers) > end - } - }) - - except Exception as e: - logging.error(f"Error in api_customers: {str(e)}") - return jsonify({'error': 'Fehler beim Laden der Kunden'}), 500 - - -@api_bp.route("/license//toggle", methods=["POST"]) -@login_required -def toggle_license(license_id): - """Toggle license active status""" - conn = get_connection() - cur = conn.cursor() - - try: - # Get current status - license_data = get_license_by_id(license_id) - if not license_data: - return jsonify({'error': 'Lizenz nicht gefunden'}), 404 - - new_status = not license_data['active'] - - # Update status - cur.execute("UPDATE licenses SET active = %s WHERE id = %s", (new_status, license_id)) - conn.commit() - - # Log change - log_audit('TOGGLE', 'license', license_id, - old_values={'active': license_data['active']}, - new_values={'active': new_status}) - - return jsonify({'success': True, 'active': new_status}) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Umschalten der Lizenz: {str(e)}") - return jsonify({'error': 'Fehler beim Umschalten der Lizenz'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/licenses/bulk-activate", methods=["POST"]) -@login_required -def bulk_activate_licenses(): - """Aktiviere mehrere Lizenzen gleichzeitig""" - data = request.get_json() - license_ids = data.get('license_ids', []) - - if not license_ids: - return jsonify({'error': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - try: - # Update all selected licenses - cur.execute(""" - UPDATE licenses - SET active = true - WHERE id = ANY(%s) AND active = false - RETURNING id - """, (license_ids,)) - - updated_ids = [row[0] for row in cur.fetchall()] - conn.commit() - - # Log changes - for license_id in updated_ids: - log_audit('BULK_ACTIVATE', 'license', license_id, - new_values={'active': True}) - - return jsonify({ - 'success': True, - 'updated_count': len(updated_ids) - }) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Bulk-Aktivieren: {str(e)}") - return jsonify({'error': 'Fehler beim Aktivieren der Lizenzen'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/licenses/bulk-deactivate", methods=["POST"]) -@login_required -def bulk_deactivate_licenses(): - """Deaktiviere mehrere Lizenzen gleichzeitig""" - data = request.get_json() - license_ids = data.get('license_ids', []) - - if not license_ids: - return jsonify({'error': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - try: - # Update all selected licenses - cur.execute(""" - UPDATE licenses - SET active = false - WHERE id = ANY(%s) AND active = true - RETURNING id - """, (license_ids,)) - - updated_ids = [row[0] for row in cur.fetchall()] - conn.commit() - - # Log changes - for license_id in updated_ids: - log_audit('BULK_DEACTIVATE', 'license', license_id, - new_values={'active': False}) - - return jsonify({ - 'success': True, - 'updated_count': len(updated_ids) - }) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Bulk-Deaktivieren: {str(e)}") - return jsonify({'error': 'Fehler beim Deaktivieren der Lizenzen'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/license//devices") -@login_required -def get_license_devices(license_id): - """Hole alle Geräte einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Hole Lizenz-Info - license_data = get_license_by_id(license_id) - if not license_data: - return jsonify({'error': 'Lizenz nicht gefunden'}), 404 - - # Hole registrierte Geräte - cur.execute(""" - SELECT - dr.id, - dr.device_id, - dr.device_name, - dr.device_type, - dr.registration_date, - dr.last_seen, - dr.is_active, - (SELECT COUNT(*) FROM sessions s - WHERE s.license_key = dr.license_key - AND s.device_id = dr.device_id - AND s.active = true) as active_sessions - FROM device_registrations dr - WHERE dr.license_key = %s - ORDER BY dr.registration_date DESC - """, (license_data['license_key'],)) - - devices = [] - for row in cur.fetchall(): - devices.append({ - 'id': row[0], - 'device_id': row[1], - 'device_name': row[2], - 'device_type': row[3], - 'registration_date': row[4].isoformat() if row[4] else None, - 'last_seen': row[5].isoformat() if row[5] else None, - 'is_active': row[6], - 'active_sessions': row[7] - }) - - return jsonify({ - 'license_key': license_data['license_key'], - 'device_limit': license_data['device_limit'], - 'devices': devices, - 'device_count': len(devices) - }) - - except Exception as e: - logging.error(f"Fehler beim Abrufen der Geräte: {str(e)}") - return jsonify({'error': 'Fehler beim Abrufen der Geräte'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/license//register-device", methods=["POST"]) -@login_required -def register_device(license_id): - """Registriere ein neues Gerät für eine Lizenz""" - data = request.get_json() - - device_id = data.get('device_id') - device_name = data.get('device_name') - device_type = data.get('device_type', 'unknown') - - if not device_id or not device_name: - return jsonify({'error': 'Geräte-ID und Name erforderlich'}), 400 - - conn = get_connection() - cur = conn.cursor() - - try: - # Hole Lizenz-Info - license_data = get_license_by_id(license_id) - if not license_data: - return jsonify({'error': 'Lizenz nicht gefunden'}), 404 - - # Prüfe Gerätelimit - cur.execute(""" - SELECT COUNT(*) FROM device_registrations - WHERE license_key = %s AND is_active = true - """, (license_data['license_key'],)) - - active_device_count = cur.fetchone()[0] - - if active_device_count >= license_data['device_limit']: - return jsonify({'error': 'Gerätelimit erreicht'}), 400 - - # Prüfe ob Gerät bereits registriert - cur.execute(""" - SELECT id, is_active FROM device_registrations - WHERE license_key = %s AND device_id = %s - """, (license_data['license_key'], device_id)) - - existing = cur.fetchone() - - if existing: - if existing[1]: # is_active - return jsonify({'error': 'Gerät bereits registriert'}), 400 - else: - # Reaktiviere Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = true, last_seen = CURRENT_TIMESTAMP - WHERE id = %s - """, (existing[0],)) - else: - # Registriere neues Gerät - cur.execute(""" - INSERT INTO device_registrations - (license_key, device_id, device_name, device_type, is_active) - VALUES (%s, %s, %s, %s, true) - """, (license_data['license_key'], device_id, device_name, device_type)) - - conn.commit() - - # Audit-Log - log_audit('DEVICE_REGISTER', 'license', license_id, - additional_info=f"Gerät {device_name} ({device_id}) registriert") - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Registrieren des Geräts: {str(e)}") - return jsonify({'error': 'Fehler beim Registrieren des Geräts'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/license//deactivate-device/", methods=["POST"]) -@login_required -def deactivate_device(license_id, device_id): - """Deaktiviere ein Gerät einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe ob Gerät zur Lizenz gehört - cur.execute(""" - SELECT dr.device_name, dr.device_id, l.license_key - FROM device_registrations dr - JOIN licenses l ON dr.license_key = l.license_key - WHERE dr.id = %s AND l.id = %s - """, (device_id, license_id)) - - device = cur.fetchone() - if not device: - return jsonify({'error': 'Gerät nicht gefunden'}), 404 - - # Deaktiviere Gerät - cur.execute(""" - UPDATE device_registrations - SET is_active = false - WHERE id = %s - """, (device_id,)) - - # Beende aktive Sessions - cur.execute(""" - UPDATE sessions - SET active = false, logout_time = CURRENT_TIMESTAMP - WHERE license_key = %s AND device_id = %s AND active = true - """, (device[2], device[1])) - - conn.commit() - - # Audit-Log - log_audit('DEVICE_DEACTIVATE', 'license', license_id, - additional_info=f"Gerät {device[0]} ({device[1]}) deaktiviert") - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Deaktivieren des Geräts: {str(e)}") - return jsonify({'error': 'Fehler beim Deaktivieren des Geräts'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/licenses/bulk-delete", methods=["POST"]) -@login_required -def bulk_delete_licenses(): - """Lösche mehrere Lizenzen gleichzeitig""" - data = request.get_json() - license_ids = data.get('license_ids', []) - - if not license_ids: - return jsonify({'error': 'Keine Lizenzen ausgewählt'}), 400 - - conn = get_connection() - cur = conn.cursor() - - try: - deleted_count = 0 - - for license_id in license_ids: - # Hole Lizenz-Info für Audit - cur.execute("SELECT license_key FROM licenses WHERE id = %s", (license_id,)) - result = cur.fetchone() - - if result: - license_key = result[0] - - # Lösche Sessions - cur.execute("DELETE FROM sessions WHERE license_key = %s", (license_key,)) - - # Lösche Geräte-Registrierungen - cur.execute("DELETE FROM device_registrations WHERE license_key = %s", (license_key,)) - - # Lösche Lizenz - cur.execute("DELETE FROM licenses WHERE id = %s", (license_id,)) - - # Audit-Log - log_audit('BULK_DELETE', 'license', license_id, - old_values={'license_key': license_key}) - - deleted_count += 1 - - conn.commit() - - return jsonify({ - 'success': True, - 'deleted_count': deleted_count - }) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Bulk-Löschen: {str(e)}") - return jsonify({'error': 'Fehler beim Löschen der Lizenzen'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/license//quick-edit", methods=['POST']) -@login_required -def quick_edit_license(license_id): - """Schnellbearbeitung einer Lizenz""" - data = request.get_json() - - conn = get_connection() - cur = conn.cursor() - - try: - # Hole aktuelle Lizenz für Vergleich - current_license = get_license_by_id(license_id) - if not current_license: - return jsonify({'error': 'Lizenz nicht gefunden'}), 404 - - # Update nur die übergebenen Felder - updates = [] - params = [] - old_values = {} - new_values = {} - - if 'device_limit' in data: - updates.append("device_limit = %s") - params.append(int(data['device_limit'])) - old_values['device_limit'] = current_license['device_limit'] - new_values['device_limit'] = int(data['device_limit']) - - if 'valid_until' in data: - updates.append("valid_until = %s") - params.append(data['valid_until']) - old_values['valid_until'] = str(current_license['valid_until']) - new_values['valid_until'] = data['valid_until'] - - if 'active' in data: - updates.append("active = %s") - params.append(bool(data['active'])) - old_values['active'] = current_license['active'] - new_values['active'] = bool(data['active']) - - if not updates: - return jsonify({'error': 'Keine Änderungen angegeben'}), 400 - - # Führe Update aus - params.append(license_id) - cur.execute(f""" - UPDATE licenses - SET {', '.join(updates)} - WHERE id = %s - """, params) - - conn.commit() - - # Audit-Log - log_audit('QUICK_EDIT', 'license', license_id, - old_values=old_values, - new_values=new_values) - - return jsonify({'success': True}) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler bei Schnellbearbeitung: {str(e)}") - return jsonify({'error': 'Fehler bei der Bearbeitung'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/license//resources") -@login_required -def get_license_resources(license_id): - """Hole alle Ressourcen einer Lizenz""" - conn = get_connection() - cur = conn.cursor() - - try: - # Hole Lizenz-Info - license_data = get_license_by_id(license_id) - if not license_data: - return jsonify({'error': 'Lizenz nicht gefunden'}), 404 - - # Hole zugewiesene Ressourcen - cur.execute(""" - SELECT - rp.id, - rp.resource_type, - rp.resource_value, - rp.is_test, - rp.status_changed_at, - lr.assigned_at, - lr.assigned_by - FROM resource_pools rp - JOIN license_resources lr ON rp.id = lr.resource_id - WHERE lr.license_id = %s - ORDER BY rp.resource_type, rp.resource_value - """, (license_id,)) - - resources = [] - for row in cur.fetchall(): - resources.append({ - 'id': row[0], - 'type': row[1], - 'value': row[2], - 'is_test': row[3], - 'status_changed_at': row[4].isoformat() if row[4] else None, - 'assigned_at': row[5].isoformat() if row[5] else None, - 'assigned_by': row[6] - }) - - # Gruppiere nach Typ - grouped = {} - for resource in resources: - res_type = resource['type'] - if res_type not in grouped: - grouped[res_type] = [] - grouped[res_type].append(resource) - - return jsonify({ - 'license_key': license_data['license_key'], - 'resources': resources, - 'grouped': grouped, - 'total_count': len(resources) - }) - - except Exception as e: - logging.error(f"Fehler beim Abrufen der Ressourcen: {str(e)}") - return jsonify({'error': 'Fehler beim Abrufen der Ressourcen'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/resources/allocate", methods=['POST']) -@login_required -def allocate_resources(): - """Weise Ressourcen einer Lizenz zu""" - data = request.get_json() - - license_id = data.get('license_id') - resource_ids = data.get('resource_ids', []) - - if not license_id or not resource_ids: - return jsonify({'error': 'Lizenz-ID und Ressourcen erforderlich'}), 400 - - conn = get_connection() - cur = conn.cursor() - - try: - # Prüfe Lizenz - license_data = get_license_by_id(license_id) - if not license_data: - return jsonify({'error': 'Lizenz nicht gefunden'}), 404 - - allocated_count = 0 - errors = [] - - for resource_id in resource_ids: - try: - # Prüfe ob Ressource verfügbar ist - cur.execute(""" - SELECT resource_value, status, is_test - FROM resource_pools - WHERE id = %s - """, (resource_id,)) - - resource = cur.fetchone() - if not resource: - errors.append(f"Ressource {resource_id} nicht gefunden") - continue - - if resource[1] != 'available': - errors.append(f"Ressource {resource[0]} ist nicht verfügbar") - continue - - # Prüfe Test/Produktion Kompatibilität - if resource[2] != license_data['is_test']: - errors.append(f"Ressource {resource[0]} ist {'Test' if resource[2] else 'Produktion'}, Lizenz ist {'Test' if license_data['is_test'] else 'Produktion'}") - continue - - # Weise Ressource zu - cur.execute(""" - UPDATE resource_pools - SET status = 'allocated', - allocated_to_license = %s, - status_changed_at = CURRENT_TIMESTAMP, - status_changed_by = %s - WHERE id = %s - """, (license_id, session['username'], resource_id)) - - # Erstelle Verknüpfung - cur.execute(""" - INSERT INTO license_resources (license_id, resource_id, assigned_by) - VALUES (%s, %s, %s) - """, (license_id, resource_id, session['username'])) - - # History-Eintrag - cur.execute(""" - INSERT INTO resource_history (resource_id, license_id, action, action_by, ip_address) - VALUES (%s, %s, 'allocated', %s, %s) - """, (resource_id, license_id, session['username'], get_client_ip())) - - allocated_count += 1 - - except Exception as e: - errors.append(f"Fehler bei Ressource {resource_id}: {str(e)}") - - conn.commit() - - # Audit-Log - if allocated_count > 0: - log_audit('RESOURCE_ALLOCATE', 'license', license_id, - additional_info=f"{allocated_count} Ressourcen zugewiesen") - - return jsonify({ - 'success': True, - 'allocated_count': allocated_count, - 'errors': errors - }) - - except Exception as e: - conn.rollback() - logging.error(f"Fehler beim Zuweisen der Ressourcen: {str(e)}") - return jsonify({'error': 'Fehler beim Zuweisen der Ressourcen'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/resources/check-availability", methods=['GET']) -@login_required -def check_resource_availability(): - """Prüfe Verfügbarkeit von Ressourcen""" - resource_type = request.args.get('type') - count = int(request.args.get('count', 1)) - is_test = request.args.get('is_test', 'false') == 'true' - - if not resource_type: - return jsonify({'error': 'Ressourcen-Typ erforderlich'}), 400 - - conn = get_connection() - cur = conn.cursor() - - try: - # Zähle verfügbare Ressourcen - cur.execute(""" - SELECT COUNT(*) - FROM resource_pools - WHERE resource_type = %s - AND status = 'available' - AND is_test = %s - """, (resource_type, is_test)) - - available_count = cur.fetchone()[0] - - return jsonify({ - 'resource_type': resource_type, - 'requested': count, - 'available': available_count, - 'sufficient': available_count >= count, - 'is_test': is_test - }) - - except Exception as e: - logging.error(f"Fehler beim Prüfen der Verfügbarkeit: {str(e)}") - return jsonify({'error': 'Fehler beim Prüfen der Verfügbarkeit'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/global-search", methods=['GET']) -@login_required -def global_search(): - """Globale Suche über alle Entitäten""" - query = request.args.get('q', '').strip() - - if not query or len(query) < 3: - return jsonify({'error': 'Suchbegriff muss mindestens 3 Zeichen haben'}), 400 - - conn = get_connection() - cur = conn.cursor() - - results = { - 'licenses': [], - 'customers': [], - 'resources': [], - 'sessions': [] - } - - try: - # Suche in Lizenzen - cur.execute(""" - SELECT id, license_key, customer_name, active - FROM licenses - WHERE license_key ILIKE %s - OR customer_name ILIKE %s - OR customer_email ILIKE %s - LIMIT 10 - """, (f'%{query}%', f'%{query}%', f'%{query}%')) - - for row in cur.fetchall(): - results['licenses'].append({ - 'id': row[0], - 'license_key': row[1], - 'customer_name': row[2], - 'active': row[3] - }) - - # Suche in Kunden - cur.execute(""" - SELECT id, name, email - FROM customers - WHERE name ILIKE %s OR email ILIKE %s - LIMIT 10 - """, (f'%{query}%', f'%{query}%')) - - for row in cur.fetchall(): - results['customers'].append({ - 'id': row[0], - 'name': row[1], - 'email': row[2] - }) - - # Suche in Ressourcen - cur.execute(""" - SELECT id, resource_type, resource_value, status - FROM resource_pools - WHERE resource_value ILIKE %s - LIMIT 10 - """, (f'%{query}%',)) - - for row in cur.fetchall(): - results['resources'].append({ - 'id': row[0], - 'type': row[1], - 'value': row[2], - 'status': row[3] - }) - - # Suche in Sessions - cur.execute(""" - SELECT id, license_key, username, device_id, active - FROM sessions - WHERE username ILIKE %s OR device_id ILIKE %s - ORDER BY login_time DESC - LIMIT 10 - """, (f'%{query}%', f'%{query}%')) - - for row in cur.fetchall(): - results['sessions'].append({ - 'id': row[0], - 'license_key': row[1], - 'username': row[2], - 'device_id': row[3], - 'active': row[4] - }) - - return jsonify(results) - - except Exception as e: - logging.error(f"Fehler bei der globalen Suche: {str(e)}") - return jsonify({'error': 'Fehler bei der Suche'}), 500 - finally: - cur.close() - conn.close() - - -@api_bp.route("/generate-license-key", methods=['POST']) -@login_required -def api_generate_key(): - """API Endpoint zur Generierung eines neuen Lizenzschlüssels""" - try: - # Lizenztyp aus Request holen (default: full) - data = request.get_json() or {} - license_type = data.get('type', 'full') - - # Key generieren - key = generate_license_key(license_type) - - # Prüfen ob Key bereits existiert (sehr unwahrscheinlich aber sicher ist sicher) - conn = get_connection() - cur = conn.cursor() - - # Wiederhole bis eindeutiger Key gefunden - attempts = 0 - while attempts < 10: # Max 10 Versuche - cur.execute("SELECT 1 FROM licenses WHERE license_key = %s", (key,)) - if not cur.fetchone(): - break # Key ist eindeutig - key = generate_license_key(license_type) - attempts += 1 - - cur.close() - conn.close() - - # Log für Audit - log_audit('GENERATE_KEY', 'license', - additional_info={'type': license_type, 'key': key}) - - return jsonify({ - 'success': True, - 'key': key, - 'type': license_type - }) - - except Exception as e: - logging.error(f"Fehler bei Key-Generierung: {str(e)}") - return jsonify({ - 'success': False, - 'error': 'Fehler bei der Key-Generierung' - }), 500 - - -@api_bp.route("/customers", methods=['GET']) -@login_required -def api_customers(): - """API Endpoint für die Kundensuche mit Select2""" - try: - # Suchparameter - search = request.args.get('q', '').strip() - page = request.args.get('page', 1, type=int) - per_page = 20 - customer_id = request.args.get('id', type=int) - - conn = get_connection() - cur = conn.cursor() - - # Einzelnen Kunden per ID abrufen - if customer_id: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE c.id = %s - GROUP BY c.id, c.name, c.email - """, (customer_id,)) - - customer = cur.fetchone() - results = [] - if customer: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} ({customer[2]})", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - cur.close() - conn.close() - - return jsonify({ - 'results': results, - 'pagination': {'more': False} - }) - - # SQL Query mit optionaler Suche - elif search: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - WHERE LOWER(c.name) LIKE LOWER(%s) - OR LOWER(c.email) LIKE LOWER(%s) - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (f'%{search}%', f'%{search}%', per_page, (page - 1) * per_page)) - else: - cur.execute(""" - SELECT c.id, c.name, c.email, - COUNT(l.id) as license_count - FROM customers c - LEFT JOIN licenses l ON c.id = l.customer_id - GROUP BY c.id, c.name, c.email - ORDER BY c.name - LIMIT %s OFFSET %s - """, (per_page, (page - 1) * per_page)) - - customers = cur.fetchall() - - # Format für Select2 - results = [] - for customer in customers: - results.append({ - 'id': customer[0], - 'text': f"{customer[1]} - {customer[2]} ({customer[3]} Lizenzen)", - 'name': customer[1], - 'email': customer[2], - 'license_count': customer[3] - }) - - # Gesamtanzahl für Pagination - if search: - cur.execute(""" - SELECT COUNT(*) FROM customers - WHERE LOWER(name) LIKE LOWER(%s) - OR LOWER(email) LIKE LOWER(%s) - """, (f'%{search}%', f'%{search}%')) - else: - cur.execute("SELECT COUNT(*) FROM customers") - - total_count = cur.fetchone()[0] - - cur.close() - conn.close() - - # Select2 Response Format - return jsonify({ - 'results': results, - 'pagination': { - 'more': (page * per_page) < total_count - } - }) - - except Exception as e: - logging.error(f"Fehler bei Kundensuche: {str(e)}") - return jsonify({ - 'results': [], - 'pagination': {'more': False}, - 'error': str(e) - }), 500 \ No newline at end of file diff --git a/v2_adminpanel/routes/customer_routes.py b/v2_adminpanel/routes/customer_routes.py index 78db397..8648f37 100644 --- a/v2_adminpanel/routes/customer_routes.py +++ b/v2_adminpanel/routes/customer_routes.py @@ -24,12 +24,39 @@ def test_customers(): def customers(): show_test = request.args.get('show_test', 'false').lower() == 'true' search = request.args.get('search', '').strip() + page = request.args.get('page', 1, type=int) + per_page = 20 + sort = request.args.get('sort', 'name') + order = request.args.get('order', 'asc') customers_list = get_customers(show_test=show_test, search=search) + + # Sortierung + if sort == 'name': + customers_list.sort(key=lambda x: x['name'].lower(), reverse=(order == 'desc')) + elif sort == 'email': + customers_list.sort(key=lambda x: x['email'].lower(), reverse=(order == 'desc')) + elif sort == 'created_at': + customers_list.sort(key=lambda x: x['created_at'], reverse=(order == 'desc')) + + # Paginierung + total_customers = len(customers_list) + total_pages = (total_customers + per_page - 1) // per_page + start = (page - 1) * per_page + end = start + per_page + paginated_customers = customers_list[start:end] + return render_template("customers.html", - customers=customers_list, + customers=paginated_customers, show_test=show_test, - search=search) + search=search, + page=page, + per_page=per_page, + total_pages=total_pages, + total_customers=total_customers, + sort=sort, + order=order, + current_order=order) @customer_bp.route("/customer/edit/", methods=["GET", "POST"]) diff --git a/v2_adminpanel/templates/base.html b/v2_adminpanel/templates/base.html index 469a253..b2ed743 100644 --- a/v2_adminpanel/templates/base.html +++ b/v2_adminpanel/templates/base.html @@ -363,12 +363,18 @@