This commit is contained in:
Kyattsukuro 2025-07-31 00:41:19 +02:00
commit 10ee2249ae
34 changed files with 8007 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.venv

10
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,10 @@
{
"recommendations": [
"Vue.volar",
"vitest.explorer",
"dbaeumer.vscode-eslint",
"EditorConfig.EditorConfig",
"oxc.oxc-vscode",
"esbenp.prettier-vscode"
]
}

24
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,24 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${cwd}/backend_py/main.py",
"console": "integratedTerminal"
},
{
"type": "node",
"request": "launch",
"name": "Run npm dev",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "dev"],
"cwd": "${workspaceFolder}/frontend",
"console": "integratedTerminal"
}
]
}

14
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,14 @@
{
"explorer.fileNesting.enabled": true,
"explorer.fileNesting.patterns": {
"tsconfig.json": "tsconfig.*.json, env.d.ts",
"vite.config.*": "jsconfig*, vitest.config.*, cypress.config.*, playwright.config.*",
"package.json": "package-lock.json, pnpm*, .yarnrc*, yarn*, .eslint*, eslint*, .oxlint*, oxlint*, .prettier*, prettier*, .editorconfig"
},
"editor.codeActionsOnSave": {
"source.fixAll": "explicit"
},
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"nixEnvSelector.nixFile": "${workspaceFolder}/shell.nix"
}

Binary file not shown.

36
backend_py/db_handler.py Normal file
View File

@ -0,0 +1,36 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy import Column, Integer, String
from dataclasses import dataclass
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
name = Column(String, primary_key=True)
hash = Column(String)
role = Column(String)
class DbConnector:
def __init__(self, db_url: str):
self.engine = create_engine(db_url)
Base.metadata.create_all(self.engine)
self.session = sessionmaker(bind=self.engine)()
self._create_defaults()
def _create_defaults(self):
self.add_user(name="admin", hash="$2b$12$IcUr5w7pIFaXaGVFP5yVV.b.sIYjDbETR3l2PKgWO4nkrHU.1HmFa", role="admin")
def get_user(self, name: str) -> User | None:
return self.session.query(User).filter(User.name==name).first()
def add_user(self, name: str, hash: str, role: str = "user"):
if self.get_user(name):
raise ValueError("User already exists")
new_user = User(name, hash, role)
self.session.add(new_user)
self.session.commit()

131
backend_py/main.py Normal file
View File

@ -0,0 +1,131 @@
from bottle import response, request, Bottle
from json import dumps, loads
import time
from db_handler import DbConnector
from functools import wraps
import jwt
from passlib.context import CryptContext
import bcrypt
# Needet because of: https://github.com/pyca/bcrypt/issues/684
if not hasattr(bcrypt, '__about__'):
bcrypt.__about__ = type('about', (object,), {'__version__': bcrypt.__version__})
def user_guard(reyection_msg: str = "Requires authentication", allow_anonymous: bool = False):
def user_guard_decorator(fn: callable):
@wraps(fn)
async def wrapper(*args, **kwargs):
username = username_by_token(request)
if not username and not allow_anonymous:
response.status = 401
return dumps({"error": reyection_msg})
if username:
user = request.db_connector.get_user(username)
return await fn(user, *args, **kwargs)
return wrapper
return user_guard_decorator
def admin_guard(reyection_msg: str = "Requires admin priveledges"):
def admin_guard_decorator(fn: callable):
@wraps(fn)
@user_guard(reyection_msg)
async def wrapper(user, *args, **kwargs):
if user.role != "admin":
response.status = 401
return dumps({"error": reyection_msg})
return await fn(user, *args, **kwargs)
return wrapper
return admin_guard_decorator
def read_keys_from_request(keys: None|dict = None):
result = {}
try:
body = request.body.read()
data = loads(body.decode('utf-8'))
except:
return result
if keys:
missing_keys = [key for key in keys if key not in data]
if missing_keys:
raise ValueError(f"Missing required keys: {', '.join(missing_keys)}")
data = {key: data[key] for key in keys}
return data
hash_context = CryptContext(schemes=["bcrypt"])
app = Bottle()
@app.route("/auth/token", method=["POST"])
def token():
body = request.body.read()
try:
data = loads(body.decode('utf-8'))
username = data.get("user")
password = data.get("password")
except:
response.status = 400
return dumps({"error": "Invalid JSON format"})
user = request.db_connector.get_user(username)
if not user or not hash_context.verify(password, user.hash):
response.status = 401
return dumps({"error": "Invalid username or password"})
jwt_content = {
"sub": {
"user": user.name,
},
"iat": time.time(),
"exp": 60 * 20
}
token = jwt.encode(jwt_content, "secret", algorithm="HS256")
response.set_cookie("oauth2", token, max_age=60*20, path='/')
response.status = 200
return dumps(jwt_content)
def username_by_token(request) -> str | None:
token = request.get_cookie("oauth2")
if not token:
return None
try:
decoded = jwt.decode(token, "secret", algorithms=["HS256"])
curent_time = time.time()
if decoded.get("exp", float("inf")) + decoded.get("iat", float("inf")) < curent_time:
return None
return decoded["sub"]["user"]
except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
return None
@app.route("/user", method=["GET"])
def get_user():
username = username_by_token(request)
if not username:
response.status = 401
return dumps({"error": "Unauthorized"})
return dumps({"name": username})
@app.route("/user_add", method=["POST"])
@admin_guard()
def add_user(user):
data = read_keys_from_request(["new_user", "new_password"])
request.db_connector.add_user(data["new_user"], hash_context.genhash)
def initialize_app():
db = DbConnector("sqlite:///./data/db.sqlite")
@app.hook('before_request')
def attach_resources():
request.db_connector = db
body = request.body.read()
return app
if __name__ == "__main__":
initialize_app()
app.run(host='localhost', port=8080, debug=True)

BIN
data/db.sqlite Normal file

Binary file not shown.

9
frontend/.editorconfig Normal file
View File

@ -0,0 +1,9 @@
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
charset = utf-8
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
max_line_length = 100

1
frontend/.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* text=auto eol=lf

30
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,30 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.tsbuildinfo

View File

@ -0,0 +1,6 @@
{
"$schema": "https://json.schemastore.org/prettierrc",
"semi": false,
"singleQuote": true,
"printWidth": 100
}

1
frontend/env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

30
frontend/eslint.config.ts Normal file
View File

@ -0,0 +1,30 @@
import { globalIgnores } from 'eslint/config'
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'
import pluginVue from 'eslint-plugin-vue'
import pluginVitest from '@vitest/eslint-plugin'
import pluginOxlint from 'eslint-plugin-oxlint'
import skipFormatting from '@vue/eslint-config-prettier/skip-formatting'
// To allow more languages other than `ts` in `.vue` files, uncomment the following lines:
// import { configureVueProject } from '@vue/eslint-config-typescript'
// configureVueProject({ scriptLangs: ['ts', 'tsx'] })
// More info at https://github.com/vuejs/eslint-config-typescript/#advanced-setup
export default defineConfigWithVueTs(
{
name: 'app/files-to-lint',
files: ['**/*.{ts,mts,tsx,vue}'],
},
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
pluginVue.configs['flat/essential'],
vueTsConfigs.recommended,
{
...pluginVitest.configs.recommended,
files: ['src/**/__tests__/*'],
},
...pluginOxlint.configs['flat/recommended'],
skipFormatting,
)

13
frontend/index.html Normal file
View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

7356
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

49
frontend/package.json Normal file
View File

@ -0,0 +1,49 @@
{
"name": "sample-setup",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"test:unit": "vitest",
"build-only": "vite build",
"type-check": "vue-tsc --build",
"lint:oxlint": "oxlint . --fix -D correctness --ignore-path .gitignore",
"lint:eslint": "eslint . --fix",
"lint": "run-s lint:*",
"format": "prettier --write src/"
},
"dependencies": {
"@tailwindcss/vite": "^4.1.10",
"tailwindcss": "^4.1.10",
"vue": "^3.5.13",
"vue-router": "^4.5.0"
},
"devDependencies": {
"@tsconfig/node22": "^22.0.1",
"@types/jsdom": "^21.1.7",
"@types/node": "^22.14.0",
"@vitejs/plugin-vue": "^5.2.3",
"@vitejs/plugin-vue-jsx": "^4.1.2",
"@vitest/eslint-plugin": "^1.1.39",
"@vue/eslint-config-prettier": "^10.2.0",
"@vue/eslint-config-typescript": "^14.5.0",
"@vue/test-utils": "^2.4.6",
"@vue/tsconfig": "^0.7.0",
"eslint": "^9.22.0",
"eslint-plugin-oxlint": "^0.16.0",
"eslint-plugin-vue": "~10.0.0",
"jiti": "^2.4.2",
"jsdom": "^26.0.0",
"npm-run-all2": "^7.0.2",
"oxlint": "^0.16.0",
"prettier": "3.5.3",
"typescript": "~5.8.0",
"vite": "^6.2.4",
"vite-plugin-vue-devtools": "^7.7.2",
"vitest": "^3.1.1",
"vue-tsc": "^2.2.8"
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

8
frontend/src/App.vue Normal file
View File

@ -0,0 +1,8 @@
<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
import HelloWorld from './components/HelloWorld.vue'
</script>
<template>
<RouterView />
</template>

View File

@ -0,0 +1 @@
@import 'tailwindcss';

View File

@ -0,0 +1,5 @@
<script setup lang="ts"></script>
<template>
<h3>Hello World</h3>
</template>

View File

@ -0,0 +1,6 @@
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import HelloWorld from '../HelloWorld.vue'
describe('HelloWorld', () => {})

View File

@ -0,0 +1,76 @@
import { API_URL } from '@/main'
export interface User {
user: string
}
function getJsonOrError(response: Response) {
if (!response.ok) {
return response.json().then((data) => {
throw new Error(data.error || 'Request failed')
})
}
return response.json()
}
/*
const getUser = async (token: string | undefined) => {
if (!token) {
throw new Error('No token provided')
}
return fetch(`${API_URL}/user`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}).then(async (response) => {
let data = await getJsonOrError(response)
return {
name: data.name,
} as User
})
}
*/
const readToken = () => {
const token = document.cookie.split('; ').find((row) => row.startsWith('oauth2='))
if (token) {
return token.split('=')[1]
}
return null
}
export const getSessionFromJWT = (): User => {
let coockie = readToken()
if (!coockie) {
throw new Error('No token found in cookies')
}
let token = coockie.split(' ')[coockie.split(' ').length - 1] // Get the last part of the token
try {
// Phrase JWT
const base64Url = token.split('.')[1] // Get the payload part
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/') // Base64 adjustments
return JSON.parse(atob(base64)).sub // Decode and parse JSON
} catch (_) {
throw new Error('Invalid token format')
}
}
export const requestToken = async (user: string, password: string): Promise<User> => {
return fetch(`${API_URL}/auth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // set coockies from responce
body: JSON.stringify({
user: user,
password: password,
}),
}).then(async (response) => {
let data = await getJsonOrError(response)
return {
name: data.sub.user,
} as User
})
}

12
frontend/src/main.ts Normal file
View File

@ -0,0 +1,12 @@
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
export const API_URL = 'http://localhost:8080'
app.use(router)
app.mount('#app')

View File

@ -0,0 +1,38 @@
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/Login.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/login',
name: 'login',
component: HomeView,
},
{
path: '/chat',
name: 'chat',
component: () => import('../views/Chat.vue'),
meta: { requiresAuth: true },
},
{
path: '/*',
name: 'any',
redirect: { name: 'login' },
},
],
})
router.beforeEach(async (to) => {
// Redirect to login if route requires auth and user is not logged in
console.log(document.cookie)
if ((to.meta.requiresAuth || false) && !document.cookie.includes('oauth2=')) {
return { name: 'login', query: { redirect: to.fullPath } }
} else if (to.name === 'login' && document.cookie.includes('oauth2=')) {
// Redirect to home if user is logged in and tries to access login page
return { name: '/' }
}
return true
})
export default router

View File

@ -0,0 +1,15 @@
<script lang="ts">
import { getSessionFromJWT, type User } from '@/composable/auth'
import router from '@/router'
import { ref, onMounted, type Ref } from 'vue'
const user: Ref<User> = ref(getSessionFromJWT())
console.log('User:', user.value)
</script>
<template>
<main>
<h1>Chat</h1>
<h3>Hello {{ user.name }}</h3>
</main>
</template>

View File

@ -0,0 +1,32 @@
<script setup lang="ts">
import { ref } from 'vue'
import { API_URL } from '@/main.ts'
import { requestToken } from '@/composable/auth.ts'
import router from '@/router'
const name = ref('')
const password = ref('')
const msg = ref('')
const onLogin = () => {
requestToken(name.value, password.value)
.then((user) => {
console.log('Login successful:', user)
router.push({ name: 'chat' })
})
.catch((error) => {
msg.value = error.message || 'Login failed'
})
}
</script>
<template>
<main>
<div>
<input v-model="name" placeholder="Username" />
<input v-model="password" type="password" placeholder="Password" />
<button @click="() => onLogin()">Login</button>
<p>{{ msg }}</p>
</div>
</main>
</template>

View File

@ -0,0 +1,12 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"paths": {
"@/*": ["./src/*"]
}
}
}

14
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.node.json"
},
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.vitest.json"
}
]
}

View File

@ -0,0 +1,19 @@
{
"extends": "@tsconfig/node22/tsconfig.json",
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"nightwatch.conf.*",
"playwright.config.*",
"eslint.config.*"
],
"compilerOptions": {
"noEmit": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["node"]
}
}

View File

@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"composite": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"types": ["node", "jsdom", "vitest"]
},
"include": ["vite.config.ts", "vitest.config.ts", "src/**/*.test.ts"],
"exclude": ["node_modules"]
}

17
frontend/vite.config.ts Normal file
View File

@ -0,0 +1,17 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import tailwindcss from '@tailwindcss/vite'
// https://vite.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx(), vueDevTools(), tailwindcss()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
})

14
frontend/vitest.config.ts Normal file
View File

@ -0,0 +1,14 @@
import { fileURLToPath } from 'node:url'
import { mergeConfig, defineConfig, configDefaults } from 'vitest/config'
import viteConfig from './vite.config'
export default mergeConfig(
viteConfig,
defineConfig({
test: {
environment: 'jsdom',
exclude: [...configDefaults.exclude, 'e2e/**'],
root: fileURLToPath(new URL('./', import.meta.url)),
},
}),
)

17
shell.nix Normal file
View File

@ -0,0 +1,17 @@
let
pkgs = import <nixpkgs> {
overlays = [ ];
};
in
pkgs.mkShell {
buildInputs = with pkgs; [
nodejs
python3
sqlite
];
exitHook = ''
echo "closing env.."
'';
}