#109 begin migration

This commit is contained in:
Tim
2024-08-21 23:33:06 +02:00
parent 69b8efc8b9
commit 38f2282049
31 changed files with 68 additions and 5814 deletions

View File

View File

@@ -1,36 +0,0 @@
package middleware
import (
"api/src/utils"
"context"
"log"
"net/http"
)
type ContextKey string
const TOKEN_KEY ContextKey = "token"
func EnsureAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenStr := r.Header.Get("Authorization")
if (tokenStr == "") || (len(tokenStr) < len("Bearer ")) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
tokenStr = tokenStr[len("Bearer "):]
token, err := utils.VerifyToken(tokenStr)
if err != nil {
log.Println(err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
var newContext = context.WithValue(r.Context(), TOKEN_KEY, token)
next.ServeHTTP(w, r.WithContext(newContext))
})
}

View File

@@ -1,36 +0,0 @@
package utils
import (
"context"
"log"
firebase "firebase.google.com/go"
"firebase.google.com/go/auth"
"google.golang.org/api/option"
)
var app *firebase.App
func VerifyToken(token string) (*auth.Token, error) {
if app == nil {
setup()
}
client, err := app.Auth(context.Background())
if err != nil {
log.Fatalf("error getting Auth client: %v\n", err)
}
return client.VerifyIDToken(context.Background(), token)
}
func setup() {
opt := option.WithCredentialsFile("./secrets/firebase.json")
firebaseApp, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
log.Fatalf("error initializing app: %v", err)
}
app = firebaseApp
}

View File

View File

View File

@@ -1,10 +1,7 @@
package main
import (
"api/src/middleware"
"api/src/utils"
"api/src/workout"
"api/utils"
"database/sql"
"log"
"net/http"
@@ -36,10 +33,9 @@ func main() {
}
}()
var router = getRouter(db)
var server = http.Server{
Addr: ":8080",
Handler: middleware.Logging(middleware.EnableCors(middleware.EnsureAuth(router))),
Handler: getHandler(db),
}
log.Println("Starting server at", server.Addr)
@@ -49,10 +45,3 @@ func main() {
}
}
func getRouter(db *sql.DB) *http.ServeMux {
var router = http.NewServeMux()
router.HandleFunc("POST /workout", workout.NewWorkout(db))
router.HandleFunc("GET /workout", workout.GetWorkouts(db))
router.HandleFunc("DELETE /workout", workout.DeleteWorkout(db))
return router
}

22
router.go Normal file
View File

@@ -0,0 +1,22 @@
package main
import (
"api/middleware"
"api/workout"
"database/sql"
"net/http"
)
func getHandler(db *sql.DB) http.Handler {
var router = http.NewServeMux()
static := http.FileServer(http.Dir("./static"))
router.Handle("/static", static)
router.HandleFunc("POST /workout", workout.NewWorkout(db))
router.HandleFunc("GET /workout", workout.GetWorkouts(db))
router.HandleFunc("DELETE /workout", workout.DeleteWorkout(db))
return middleware.Logging(middleware.EnableCors(router))
}

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -1,3 +1,6 @@
package main
templ hello(name string) {
<!doctype html>
<html lang="en">
<head>
@@ -11,3 +14,4 @@
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
}

30
utils/auth.go Normal file
View File

@@ -0,0 +1,30 @@
package utils
// import (
// "context"
// "log"
// )
// func VerifyToken(token string) (*auth.Token, error) {
// if app == nil {
// setup()
// }
//
// client, err := app.Auth(context.Background())
// if err != nil {
// log.Fatalf("error getting Auth client: %v\n", err)
// }
// return client.VerifyIDToken(context.Background(), token)
// }
//
// func setup() {
// opt := option.WithCredentialsFile("./secrets/firebase.json")
//
// firebaseApp, err := firebase.NewApp(context.Background(), nil, opt)
//
// if err != nil {
// log.Fatalf("error initializing app: %v", err)
// }
//
// app = firebaseApp
// }

21
view/.gitignore vendored
View File

@@ -1,21 +0,0 @@
node_modules
# Output
.output
.vercel
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

View File

@@ -1 +0,0 @@
engine-strict=true

View File

@@ -1,4 +0,0 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock

View File

@@ -1,8 +0,0 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

View File

@@ -1,13 +0,0 @@
FROM node:20@sha256:a4d1de4c7339eabcf78a90137dfd551b798829e3ef3e399e0036ac454afa1291 AS build
ARG PUBLIC_BASE_API_URL=
WORKDIR /app
COPY . ./
RUN npm install && npm run build
FROM nginx:1.27.1-alpine@sha256:c04c18adc2a407740a397c8407c011fc6c90026a9b65cceddef7ae5484360158
EXPOSE 80
COPY --from=build /app/build /usr/share/nginx/html

View File

@@ -1,38 +0,0 @@
# create-svelte
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.

View File

@@ -1,33 +0,0 @@
import js from '@eslint/js';
import ts from 'typescript-eslint';
import svelte from 'eslint-plugin-svelte';
import prettier from 'eslint-config-prettier';
import globals from 'globals';
/** @type {import('eslint').Linter.FlatConfig[]} */
export default [
js.configs.recommended,
...ts.configs.recommended,
...svelte.configs['flat/recommended'],
prettier,
...svelte.configs['flat/prettier'],
{
languageOptions: {
globals: {
...globals.browser,
...globals.node
}
}
},
{
files: ['**/*.svelte'],
languageOptions: {
parserOptions: {
parser: ts.parser
}
}
},
{
ignores: ['build/', '.svelte-kit/', 'dist/']
}
];

5533
view/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +0,0 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

View File

@@ -1,3 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

13
view/src/app.d.ts vendored
View File

@@ -1,13 +0,0 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

View File

@@ -1,18 +0,0 @@
import adapter from '@sveltejs/adapter-static';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://kit.svelte.dev/docs/adapters for more information about adapters.
adapter: adapter()
}
};
export default config;

View File

@@ -1,19 +0,0 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

View File

@@ -1,10 +0,0 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import Icons from 'unplugin-icons/vite'
export default defineConfig({
plugins: [
sveltekit(),
Icons({ compiler: 'svelte' })
],
});

View File

@@ -1,15 +1,13 @@
package workout
import (
"api/src/middleware"
"api/src/utils"
"api/utils"
"database/sql"
"net/http"
"strconv"
"time"
"firebase.google.com/go/auth"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
@@ -56,9 +54,10 @@ func NewWorkout(db *sql.DB) http.HandlerFunc {
return
}
token := r.Context().Value(middleware.TOKEN_KEY).(*auth.Token)
//TODO: Ensure auth
// token := r.Context().Value(middleware.TOKEN_KEY).(*auth.Token)
_, err = db.Exec("INSERT INTO workout (user_id, date, type, sets, reps) VALUES (?, ?, ?, ?, ?)", token.UID, date, typeStr, sets, reps)
_, err = db.Exec("INSERT INTO workout (user_id, date, type, sets, reps) VALUES (?, ?, ?, ?, ?)", "", date, typeStr, sets, reps)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
@@ -71,8 +70,9 @@ func GetWorkouts(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
metrics.WithLabelValues("get").Inc()
token := r.Context().Value(middleware.TOKEN_KEY).(*auth.Token)
var userId = token.UID
// token := r.Context().Value(middleware.TOKEN_KEY).(*auth.Token)
// var userId = token.UID
var userId = ""
rows, err := db.Query("SELECT rowid, date, type, sets, reps FROM workout WHERE user_id = ?", userId)
if err != nil {
@@ -112,8 +112,9 @@ func DeleteWorkout(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
metrics.WithLabelValues("delete").Inc()
token := r.Context().Value(middleware.TOKEN_KEY).(*auth.Token)
var userId = token.UID
// token := r.Context().Value(middleware.TOKEN_KEY).(*auth.Token)
// var userId = token.UID
var userId = ""
rowId := r.FormValue("id")
if rowId == "" {