Compare commits
5 Commits
6395b98f11
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4eb2efb33 | ||
|
|
435ad8e6e6 | ||
|
|
7ec17e1e8b | ||
| a047d57824 | |||
| c6de2481e6 |
29
Dockerfile.backend
Normal file
29
Dockerfile.backend
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# =========================
|
||||||
|
# Build stage
|
||||||
|
# =========================
|
||||||
|
FROM golang:1.25.5-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY backend/go.mod backend/go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
|
||||||
|
COPY backend/ ./
|
||||||
|
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
|
||||||
|
go build -o server ./cmd/server
|
||||||
|
|
||||||
|
|
||||||
|
# =========================
|
||||||
|
# Runtime stage
|
||||||
|
# =========================
|
||||||
|
FROM gcr.io/distroless/base-debian12
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY --from=builder /app/server ./server
|
||||||
|
|
||||||
|
EXPOSE 8081
|
||||||
|
|
||||||
|
USER nonroot:nonroot
|
||||||
|
ENTRYPOINT ["./server"]
|
||||||
30
Dockerfile.frontend
Normal file
30
Dockerfile.frontend
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# =========================
|
||||||
|
# Build stage
|
||||||
|
# =========================
|
||||||
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY frontend/studia/package*.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY frontend/studia/ ./
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
|
||||||
|
# =========================
|
||||||
|
# Runtime stage
|
||||||
|
# =========================
|
||||||
|
FROM nginx:1.27-alpine
|
||||||
|
|
||||||
|
# Remove default nginx config
|
||||||
|
RUN rm /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
# Custom nginx config
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
# Vite build output
|
||||||
|
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
@@ -8,7 +8,6 @@ Studia is an open-source web app for efficient learning with index cards (flashc
|
|||||||
- Import/export decks (JSON/CSV)
|
- Import/export decks (JSON/CSV)
|
||||||
- Progress tracking and basic statistics
|
- Progress tracking and basic statistics
|
||||||
- Keyboard-first study experience and mobile-friendly UI
|
- Keyboard-first study experience and mobile-friendly UI
|
||||||
- Offline support (cached decks) and theming
|
|
||||||
|
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
@@ -18,4 +17,3 @@ Contributions welcome. Please:
|
|||||||
- Add tests for new behavior and follow code style
|
- Add tests for new behavior and follow code style
|
||||||
|
|
||||||
## License
|
## License
|
||||||
A
|
|
||||||
BIN
backend/cli
Executable file
BIN
backend/cli
Executable file
Binary file not shown.
8
backend/cmd/cli/main.go
Normal file
8
backend/cmd/cli/main.go
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
// cmd/cli/main.go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import "studia/cmd/cli/root"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
root.Execute()
|
||||||
|
}
|
||||||
25
backend/cmd/cli/root/root.go
Normal file
25
backend/cmd/cli/root/root.go
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
package root
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"studia/cmd/cli/user"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var RootCmd = &cobra.Command{
|
||||||
|
Use: "studia",
|
||||||
|
Short: "studia admin CLI",
|
||||||
|
}
|
||||||
|
|
||||||
|
func Execute() {
|
||||||
|
if err := RootCmd.Execute(); err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RootCmd.AddCommand(user.UserCmd)
|
||||||
|
}
|
||||||
44
backend/cmd/cli/user/get.go
Normal file
44
backend/cmd/cli/user/get.go
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
// cmd/cli/user/get.go
|
||||||
|
package user
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"studia/internal/config"
|
||||||
|
"studia/internal/database"
|
||||||
|
"studia/internal/user"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var email string
|
||||||
|
|
||||||
|
var getCmd = &cobra.Command{
|
||||||
|
|
||||||
|
Use: "get",
|
||||||
|
Short: "Get user by ID",
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
cfg := config.New()
|
||||||
|
|
||||||
|
cfg.DatabaseHost = "192.168.178.171"
|
||||||
|
cfg.DatabasePort = "5432"
|
||||||
|
cfg.DatabaseUser = "admin"
|
||||||
|
cfg.DatabasePassword = "12345678"
|
||||||
|
cfg.DatabaseName = "studia"
|
||||||
|
|
||||||
|
database := database.New(cfg)
|
||||||
|
|
||||||
|
user, err := user.GetUserByEmail(database, email)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("ID: %d\nEmail: %s\nName: %s\n",
|
||||||
|
user.ID, user.Email, user.Username)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
getCmd.Flags().StringVar(&email, "email", "", "user email")
|
||||||
|
getCmd.MarkFlagRequired("email")
|
||||||
|
}
|
||||||
13
backend/cmd/cli/user/user.go
Normal file
13
backend/cmd/cli/user/user.go
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import "github.com/spf13/cobra"
|
||||||
|
|
||||||
|
var UserCmd = &cobra.Command{
|
||||||
|
Use: "user",
|
||||||
|
Short: "User management",
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
// UserCmd.AddCommand(listCmd)
|
||||||
|
UserCmd.AddCommand(getCmd)
|
||||||
|
}
|
||||||
@@ -1,12 +1,24 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"studia/internal/config"
|
||||||
|
"studia/internal/logger"
|
||||||
"studia/internal/server"
|
"studia/internal/server"
|
||||||
|
|
||||||
"log"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
log.Println("Starting server...")
|
logger.Init()
|
||||||
server.StartServer()
|
|
||||||
|
cfg := config.New()
|
||||||
|
|
||||||
|
cfg.DatabaseHost = "192.168.178.171"
|
||||||
|
cfg.DatabasePort = "5432"
|
||||||
|
cfg.DatabaseUser = "admin"
|
||||||
|
cfg.DatabasePassword = "12345678"
|
||||||
|
cfg.DatabaseName = "studia"
|
||||||
|
|
||||||
|
logger.Log.Info().Msgf("Configuration loaded: %+v", cfg)
|
||||||
|
|
||||||
|
logger.Log.Info().Msg("Starting server...")
|
||||||
|
server.StartServer(cfg)
|
||||||
}
|
}
|
||||||
|
|||||||
21
backend/db/schema.sql
Normal file
21
backend/db/schema.sql
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
|
||||||
|
-- Table: public.users
|
||||||
|
|
||||||
|
-- DROP TABLE IF EXISTS public.users;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS public.users
|
||||||
|
(
|
||||||
|
id character varying(255) COLLATE pg_catalog."default" NOT NULL DEFAULT uuid_generate_v4(),
|
||||||
|
email character varying(255) COLLATE pg_catalog."default" NOT NULL,
|
||||||
|
username character varying(255) COLLATE pg_catalog."default" NOT NULL,
|
||||||
|
password_hash character varying(255) COLLATE pg_catalog."default" NOT NULL,
|
||||||
|
created_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at timestamp with time zone ,
|
||||||
|
CONSTRAINT users_pkey PRIMARY KEY (id),
|
||||||
|
CONSTRAINT users_email_key UNIQUE (email)
|
||||||
|
)
|
||||||
|
|
||||||
|
TABLESPACE pg_default;
|
||||||
|
|
||||||
|
ALTER TABLE IF EXISTS public.users
|
||||||
|
OWNER to admin;
|
||||||
@@ -7,27 +7,37 @@ require (
|
|||||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/gin-gonic/contrib v0.0.0-20250521004450-2b1292699c15 // indirect
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.9 // indirect
|
||||||
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/bytedance/sonic v1.14.0 // indirect
|
github.com/bytedance/sonic v1.14.0 // indirect
|
||||||
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.9 // indirect
|
||||||
|
github.com/gin-contrib/cors v1.7.6
|
||||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||||
github.com/go-playground/locales v0.14.1 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/go-playground/validator/v10 v10.27.0 // indirect
|
github.com/go-playground/validator/v10 v10.27.0 // indirect
|
||||||
github.com/goccy/go-json v0.10.2 // indirect
|
github.com/goccy/go-json v0.10.5 // indirect
|
||||||
github.com/goccy/go-yaml v1.18.0 // indirect
|
github.com/goccy/go-yaml v1.18.0 // indirect
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
github.com/lib/pq v1.10.9
|
github.com/lib/pq v1.10.9
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||||
github.com/quic-go/qpack v0.5.1 // indirect
|
github.com/quic-go/qpack v0.5.1 // indirect
|
||||||
github.com/quic-go/quic-go v0.54.0 // indirect
|
github.com/quic-go/quic-go v0.54.0 // indirect
|
||||||
|
github.com/rs/zerolog v1.34.0
|
||||||
|
github.com/spf13/cobra v1.10.2
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||||
go.uber.org/mock v0.5.0 // indirect
|
go.uber.org/mock v0.5.0 // indirect
|
||||||
|
|||||||
@@ -4,13 +4,21 @@ github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZw
|
|||||||
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
||||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||||
|
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||||
|
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
|
||||||
|
github.com/gin-contrib/cors v1.7.6 h1:3gQ8GMzs1Ylpf70y8bMw4fVpycXIeX1ZemuSQIsnQQY=
|
||||||
|
github.com/gin-contrib/cors v1.7.6/go.mod h1:Ulcl+xN4jel9t1Ry8vqph23a60FwH9xVLd+3ykmTjOk=
|
||||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||||
|
github.com/gin-gonic/contrib v0.0.0-20250521004450-2b1292699c15 h1:AoSudS8CW8Mc9rRf5sO1vBtNxr2Ok6TaAICjgg5oKUY=
|
||||||
|
github.com/gin-gonic/contrib v0.0.0-20250521004450-2b1292699c15/go.mod h1:iqneQ2Df3omzIVTkIfn7c1acsVnMGiSLn4XF5Blh3Yg=
|
||||||
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
||||||
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
||||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
@@ -23,13 +31,18 @@ github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHO
|
|||||||
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||||
|
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||||
|
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||||
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
|
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
|
||||||
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||||
|
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||||
@@ -38,20 +51,35 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
|||||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
|
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||||
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||||
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
|
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
|
||||||
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
||||||
|
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||||
|
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
|
||||||
|
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
|
||||||
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
|
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||||
|
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||||
|
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||||
|
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
@@ -67,6 +95,7 @@ github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA
|
|||||||
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||||
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||||
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
|
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
|
||||||
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
|
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
|
||||||
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
|
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
|
||||||
@@ -77,7 +106,9 @@ golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
|
|||||||
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
|
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
|
||||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||||
|
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||||
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
|
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"studia/internal/logger"
|
||||||
"studia/internal/user"
|
"studia/internal/user"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -11,42 +13,77 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type LoginRequest struct {
|
type LoginRequest struct {
|
||||||
Email string `json:"email"`
|
Email string
|
||||||
Password string `json:"password"`
|
Password string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type RegisterRequest struct {
|
||||||
|
Email string
|
||||||
|
Password string
|
||||||
|
Username string
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultRole = "user"
|
||||||
|
|
||||||
var secret = []byte("secret")
|
var secret = []byte("secret")
|
||||||
|
|
||||||
func LoginHandler(c *gin.Context, db *sql.DB) {
|
func Login(c *gin.Context, db *sql.DB) error {
|
||||||
var req LoginRequest
|
var req LoginRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.Email == "" || req.Password == "" {
|
if req.Email == "" || req.Password == "" {
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Email and password are required"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Email and password are required"})
|
||||||
return
|
return errors.New("Email and password are required")
|
||||||
}
|
}
|
||||||
|
|
||||||
User, err := user.GetUserByEmail(db, req.Email)
|
User, err := user.GetUserByEmail(db, req.Email)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email or password"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email "})
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
|
logger.Log.Info().Msgf("User: %+v", User)
|
||||||
|
|
||||||
if !user.CheckPasswordHash(db, User.Email, req.Password) {
|
err = user.CheckPasswordHash(db, User.Email, req.Password)
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email or password"})
|
if err != nil {
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
token, err := GenerateJWT(User.ID, User.Email, User.Role)
|
token, err := GenerateJWT(User.ID, User.Email, User.Role)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not generate token"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not generate token"})
|
||||||
return
|
return err
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"token": token})
|
c.JSON(http.StatusOK, gin.H{"token": token})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Register(c *gin.Context, db *sql.DB) error {
|
||||||
|
var req RegisterRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
// Log the error for debugging purposes
|
||||||
|
logger.Log.Error().Err(err).Msg("Failed to bind JSON for registration")
|
||||||
|
// Respond with a bad request status and an error message
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
||||||
|
return errors.New("Invalid request")
|
||||||
|
}
|
||||||
|
logger.Log.Info().Msgf("Register Request: %+v", req)
|
||||||
|
if req.Email == "" || req.Password == "" || req.Username == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Email and password are required"})
|
||||||
|
return errors.New("Email and password are required")
|
||||||
|
}
|
||||||
|
|
||||||
|
err := user.CreateUser(db, req.Email, req.Username, req.Password, []string{defaultRole})
|
||||||
|
if err != nil {
|
||||||
|
logger.Log.Error().Err(err).Msg("Failed to create user")
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "User created successfully"})
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func GenerateJWT(uuid string, email string, roles []string) (any, error) {
|
func GenerateJWT(uuid string, email string, roles []string) (any, error) {
|
||||||
|
|||||||
48
backend/internal/config/config.go
Normal file
48
backend/internal/config/config.go
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Port string
|
||||||
|
Env string
|
||||||
|
DatabaseDriver string
|
||||||
|
DatabaseHost string
|
||||||
|
DatabasePort string
|
||||||
|
DatabaseName string
|
||||||
|
DatabaseUser string
|
||||||
|
DatabasePassword string
|
||||||
|
FrontendURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
func New() *Config {
|
||||||
|
|
||||||
|
return generateConfig()
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateConfig() *Config {
|
||||||
|
|
||||||
|
cfg := Config{
|
||||||
|
Port: getEnv("PORT", "8080"),
|
||||||
|
DatabaseDriver: getEnv("DB_DRIVER", "postgres"),
|
||||||
|
DatabaseHost: getEnv("database", "localhost"),
|
||||||
|
DatabasePort: getEnv("DB_PORT", "5432"),
|
||||||
|
DatabaseName: getEnv("DB_NAME", "studia"),
|
||||||
|
DatabaseUser: getEnv("DB_USER", "user"),
|
||||||
|
DatabasePassword: getEnv("DB_PASSWORD", "password"),
|
||||||
|
Env: getEnv("ENV", "development"),
|
||||||
|
FrontendURL: getEnv("FRONTEND_URL", "http://localhost:5173"),
|
||||||
|
}
|
||||||
|
|
||||||
|
return &cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
// helper function to get env var or default
|
||||||
|
func getEnv(key, defaultVal string) string {
|
||||||
|
value, exists := os.LookupEnv(key)
|
||||||
|
if !exists || value == "" {
|
||||||
|
return defaultVal
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
98
backend/internal/database/database.go
Normal file
98
backend/internal/database/database.go
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"studia/internal/config"
|
||||||
|
"studia/internal/logger"
|
||||||
|
|
||||||
|
_ "github.com/lib/pq" // Import the PostgreSQL driver
|
||||||
|
)
|
||||||
|
|
||||||
|
var expectedTables = []string{
|
||||||
|
"users",
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(cfg *config.Config) *sql.DB {
|
||||||
|
db := setupDatabase(cfg)
|
||||||
|
|
||||||
|
existing, err := getExistingTables(db, `
|
||||||
|
SELECT table_name
|
||||||
|
FROM information_schema.tables
|
||||||
|
WHERE table_schema = 'public'
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
logger.Log.Error().Err(err).Msg("Failed to query existing tables")
|
||||||
|
}
|
||||||
|
|
||||||
|
missing := checkTables(expectedTables, existing)
|
||||||
|
|
||||||
|
if len(missing) > 0 {
|
||||||
|
log.Println("Missing tables detected:", missing)
|
||||||
|
// Here you would normally run migrations to create the missing tables
|
||||||
|
// For simplicity, we just log the missing tables
|
||||||
|
} else {
|
||||||
|
logger.Log.Info().Msg("All expected tables are present.")
|
||||||
|
}
|
||||||
|
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
|
func setupDatabase(cfg *config.Config) *sql.DB {
|
||||||
|
// Database connection setup logic here
|
||||||
|
|
||||||
|
logger.Log.Println(cfg)
|
||||||
|
switch cfg.DatabaseDriver {
|
||||||
|
case "postgres":
|
||||||
|
// Setup Postgres connection
|
||||||
|
log.Println("Setting up Postgres connection")
|
||||||
|
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
|
||||||
|
cfg.DatabaseHost, cfg.DatabasePort, cfg.DatabaseUser, cfg.DatabasePassword, cfg.DatabaseName)
|
||||||
|
db, err := sql.Open("postgres", psqlInfo)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("Failed to connect to database:", err)
|
||||||
|
}
|
||||||
|
return db
|
||||||
|
case "mysql":
|
||||||
|
// Setup MySQL connection
|
||||||
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s",
|
||||||
|
cfg.DatabaseUser, cfg.DatabasePassword, cfg.DatabaseHost, cfg.DatabasePort, cfg.DatabaseName)
|
||||||
|
db, err := sql.Open("mysql", dsn)
|
||||||
|
if err != nil {
|
||||||
|
// Handle error
|
||||||
|
}
|
||||||
|
return db
|
||||||
|
default:
|
||||||
|
// Handle unsupported database driver
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getExistingTables(db *sql.DB, query string) (map[string]bool, error) {
|
||||||
|
rows, err := db.Query(query)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
tables := make(map[string]bool)
|
||||||
|
for rows.Next() {
|
||||||
|
var name string
|
||||||
|
if err := rows.Scan(&name); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tables[name] = true
|
||||||
|
}
|
||||||
|
return tables, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkTables(expected []string, existing map[string]bool) []string {
|
||||||
|
var missing []string
|
||||||
|
for _, table := range expected {
|
||||||
|
if !existing[table] {
|
||||||
|
missing = append(missing, table)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return missing
|
||||||
|
}
|
||||||
46
backend/internal/logger/logger.go
Normal file
46
backend/internal/logger/logger.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
// internal/logger/logger.go
|
||||||
|
package logger
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/rs/zerolog"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Log zerolog.Logger
|
||||||
|
|
||||||
|
// Init initializes the global logger.
|
||||||
|
// It configures console output, timestamps, and log level from environment.
|
||||||
|
func Init() {
|
||||||
|
// Determine output writer
|
||||||
|
consoleWriter := zerolog.ConsoleWriter{
|
||||||
|
Out: os.Stdout,
|
||||||
|
TimeFormat: time.RFC3339,
|
||||||
|
}
|
||||||
|
|
||||||
|
// You can switch to JSON output by replacing with os.Stdout directly:
|
||||||
|
// writer := os.Stdout
|
||||||
|
|
||||||
|
// Create the global logger
|
||||||
|
Log = zerolog.New(consoleWriter).
|
||||||
|
Level(zerolog.TraceLevel).With().Caller().Logger().
|
||||||
|
With().
|
||||||
|
Timestamp().
|
||||||
|
Logger()
|
||||||
|
|
||||||
|
// Set log level from environment variable, default to InfoLevel
|
||||||
|
level := zerolog.InfoLevel
|
||||||
|
if lvlStr, ok := os.LookupEnv("LOG_LEVEL"); ok {
|
||||||
|
if parsedLevel, err := zerolog.ParseLevel(lvlStr); err == nil {
|
||||||
|
level = parsedLevel
|
||||||
|
}
|
||||||
|
}
|
||||||
|
zerolog.SetGlobalLevel(level)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetOutput allows changing output (e.g., to a file)
|
||||||
|
func SetOutput(w io.Writer) {
|
||||||
|
Log = Log.Output(w)
|
||||||
|
}
|
||||||
@@ -1,26 +1,70 @@
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"studia/internal/auth"
|
||||||
|
"studia/internal/config"
|
||||||
|
"studia/internal/database"
|
||||||
|
"studia/internal/logger"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-contrib/cors"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var secret = []byte("secret")
|
func StartServer(cfg *config.Config) {
|
||||||
|
|
||||||
func StartServer() {
|
router := gin.Default()
|
||||||
|
|
||||||
r := gin.Default()
|
db := database.New(cfg)
|
||||||
|
|
||||||
r.POST("/login", func(c *gin.Context) {
|
// 2. CORS-Konfiguration
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
// Lese die Frontend-URL aus den Umgebungsvariablen
|
||||||
"user": "demo",
|
// frontendURL := os.Getenv("FRONTEND_URL")
|
||||||
"role": "admin",
|
|
||||||
"exp": time.Now().Add(24 * time.Hour).Unix(),
|
// Lokaler Fallback (wichtig für die Entwicklung)
|
||||||
})
|
allowedOrigins := []string{
|
||||||
signed, _ := token.SignedString(secret)
|
"http://localhost:5173", // Gängiger Vite-Dev-Port
|
||||||
c.JSON(200, gin.H{"token": signed})
|
"http://127.0.0.1:5173",
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.FrontendURL != "" {
|
||||||
|
allowedOrigins = append(allowedOrigins, cfg.FrontendURL)
|
||||||
|
logger.Log.Printf("CORS: Erlaubte Produktiv-URL hinzugefügt: %s\n", cfg.FrontendURL)
|
||||||
|
} else {
|
||||||
|
logger.Log.Error().Msg("ACHTUNG: FRONTEND_URL fehlt in den Umgebungsvariablen. Nur lokale URLs erlaubt.")
|
||||||
|
}
|
||||||
|
|
||||||
|
// CORS
|
||||||
|
// Konfiguriere die CORS-Middleware
|
||||||
|
config := cors.Config{
|
||||||
|
// Setze die erlaubten Ursprünge (deine React-URLs)
|
||||||
|
AllowOrigins: allowedOrigins,
|
||||||
|
// Erlaube die notwendigen HTTP-Methoden
|
||||||
|
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
|
||||||
|
// Erlaube Header (z.B. für JSON und Authentifizierung)
|
||||||
|
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
|
||||||
|
// Erlaube Cookies und Credentials (falls du Tokens oder Sessions nutzt)
|
||||||
|
AllowCredentials: true,
|
||||||
|
// Wie lange die Preflight-Anfrage (OPTIONS) gecacht werden darf
|
||||||
|
MaxAge: 12 * time.Hour,
|
||||||
|
}
|
||||||
|
router.Use(cors.New(config))
|
||||||
|
|
||||||
|
router.POST("/login", func(c *gin.Context) {
|
||||||
|
err := auth.Login(c, db)
|
||||||
|
if err != nil {
|
||||||
|
logger.Log.Error().Msg(err.Error())
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
router.POST("/register", func(c *gin.Context) {
|
||||||
|
er := auth.Register(c, db)
|
||||||
|
if er != nil {
|
||||||
|
logger.Log.Error().Msg("register error")
|
||||||
|
}
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
router.Run(":" + cfg.Port)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package user
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"studia/internal/logger"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
@@ -10,7 +11,7 @@ import (
|
|||||||
type User struct {
|
type User struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Name string `json:"name"`
|
Username string `json:"username"`
|
||||||
PasswordHash string `json:"-"`
|
PasswordHash string `json:"-"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
@@ -28,26 +29,33 @@ type User struct {
|
|||||||
// }
|
// }
|
||||||
|
|
||||||
func GetUserByEmail(db *sql.DB, email string) (*User, error) {
|
func GetUserByEmail(db *sql.DB, email string) (*User, error) {
|
||||||
row := db.QueryRow("SELECT id, email, password_hash, role FROM users WHERE email=$1", email)
|
row := db.QueryRow("SELECT id, email, username FROM users WHERE email=$1", email)
|
||||||
var user User
|
var user User
|
||||||
err := row.Scan(&user.ID, &user.Email, &user.PasswordHash, &user.Role)
|
err := row.Scan(&user.ID, &user.Email, &user.Username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func CheckPasswordHash(db *sql.DB, email string, password string) bool {
|
func CheckPasswordHash(db *sql.DB, email string, password string) error {
|
||||||
row := db.QueryRow("SELECT password_hash FROM users WHERE email=$1", email)
|
row := db.QueryRow("SELECT password_hash FROM users WHERE email=$1", email)
|
||||||
var hash string
|
var hash []byte
|
||||||
if err := row.Scan(&hash); err != nil {
|
if err := row.Scan(&hash); err != nil {
|
||||||
return false
|
return err
|
||||||
}
|
}
|
||||||
UserPasswordHash, error := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
UserPasswordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
if error != nil {
|
if err != nil {
|
||||||
return false
|
return err
|
||||||
}
|
}
|
||||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(UserPasswordHash)) == nil
|
logger.Log.Info().Msgf("UserPasswordHash: %s", UserPasswordHash)
|
||||||
|
logger.Log.Info().Msgf("hash: %s", hash)
|
||||||
|
logger.Log.Info().Msgf("password: %s", []byte(password))
|
||||||
|
logger.Log.Info().Msgf("email: %s", []byte(email))
|
||||||
|
|
||||||
|
err = bcrypt.CompareHashAndPassword(hash, []byte(password))
|
||||||
|
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateUser(db *sql.DB, email string, name string, password string, role []string) error {
|
func CreateUser(db *sql.DB, email string, name string, password string, role []string) error {
|
||||||
@@ -56,7 +64,7 @@ func CreateUser(db *sql.DB, email string, name string, password string, role []s
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = db.Exec("INSERT INTO users (email, name, password_hash, role, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6)",
|
_, err = db.Exec("INSERT INTO users (email, username, password_hash) VALUES ($1, $2, $3)",
|
||||||
email, name, string(passwordHash), role, time.Now(), time.Now())
|
email, name, string(passwordHash))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
24
docker-compose.yaml
Normal file
24
docker-compose.yaml
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
version: "3.9"
|
||||||
|
|
||||||
|
services:
|
||||||
|
backend:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile.backend
|
||||||
|
container_name: studia-backend
|
||||||
|
expose:
|
||||||
|
- "9090"
|
||||||
|
environment:
|
||||||
|
- PORT=9090
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile.frontend
|
||||||
|
container_name: studia-frontend
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
depends_on:
|
||||||
|
- backend
|
||||||
|
restart: unless-stopped
|
||||||
155
frontend/studia/package-lock.json
generated
155
frontend/studia/package-lock.json
generated
@@ -9,8 +9,12 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tailwindcss/vite": "^4.1.18",
|
"@tailwindcss/vite": "^4.1.18",
|
||||||
|
"framer-motion": "^12.23.26",
|
||||||
|
"jwt-decode": "^4.0.0",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
"react-dom": "^19.2.0",
|
"react-dom": "^19.2.0",
|
||||||
|
"react-router": "^7.10.1",
|
||||||
|
"react-router-dom": "^6.30.2",
|
||||||
"tailwindcss": "^4.1.18"
|
"tailwindcss": "^4.1.18"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -59,7 +63,6 @@
|
|||||||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/code-frame": "^7.27.1",
|
"@babel/code-frame": "^7.27.1",
|
||||||
"@babel/generator": "^7.28.5",
|
"@babel/generator": "^7.28.5",
|
||||||
@@ -981,6 +984,15 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@remix-run/router": {
|
||||||
|
"version": "1.23.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.1.tgz",
|
||||||
|
"integrity": "sha512-vDbaOzF7yT2Qs4vO6XV1MHcJv+3dgR1sT+l3B8xxOVhUC336prMvqrvsLL/9Dnw2xr6Qhz4J0dmS0llNAbnUmQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@rolldown/pluginutils": {
|
"node_modules/@rolldown/pluginutils": {
|
||||||
"version": "1.0.0-beta.53",
|
"version": "1.0.0-beta.53",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.53.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.53.tgz",
|
||||||
@@ -1595,7 +1607,6 @@
|
|||||||
"integrity": "sha512-gqkrWUsS8hcm0r44yn7/xZeV1ERva/nLgrLxFRUGb7aoNMIJfZJ3AC261zDQuOAKC7MiXai1WCpYc48jAHoShQ==",
|
"integrity": "sha512-gqkrWUsS8hcm0r44yn7/xZeV1ERva/nLgrLxFRUGb7aoNMIJfZJ3AC261zDQuOAKC7MiXai1WCpYc48jAHoShQ==",
|
||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"undici-types": "~7.16.0"
|
"undici-types": "~7.16.0"
|
||||||
}
|
}
|
||||||
@@ -1606,7 +1617,6 @@
|
|||||||
"integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==",
|
"integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"csstype": "^3.2.2"
|
"csstype": "^3.2.2"
|
||||||
}
|
}
|
||||||
@@ -1666,7 +1676,6 @@
|
|||||||
"integrity": "sha512-N9lBGA9o9aqb1hVMc9hzySbhKibHmB+N3IpoShyV6HyQYRGIhlrO5rQgttypi+yEeKsKI4idxC8Jw6gXKD4THA==",
|
"integrity": "sha512-N9lBGA9o9aqb1hVMc9hzySbhKibHmB+N3IpoShyV6HyQYRGIhlrO5rQgttypi+yEeKsKI4idxC8Jw6gXKD4THA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/scope-manager": "8.49.0",
|
"@typescript-eslint/scope-manager": "8.49.0",
|
||||||
"@typescript-eslint/types": "8.49.0",
|
"@typescript-eslint/types": "8.49.0",
|
||||||
@@ -1918,7 +1927,6 @@
|
|||||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"acorn": "bin/acorn"
|
"acorn": "bin/acorn"
|
||||||
},
|
},
|
||||||
@@ -2024,7 +2032,6 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"baseline-browser-mapping": "^2.9.0",
|
"baseline-browser-mapping": "^2.9.0",
|
||||||
"caniuse-lite": "^1.0.30001759",
|
"caniuse-lite": "^1.0.30001759",
|
||||||
@@ -2121,6 +2128,19 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/cookie": {
|
||||||
|
"version": "1.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
|
||||||
|
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/express"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/cross-spawn": {
|
"node_modules/cross-spawn": {
|
||||||
"version": "7.0.6",
|
"version": "7.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||||
@@ -2267,7 +2287,6 @@
|
|||||||
"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==",
|
"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@eslint-community/eslint-utils": "^4.8.0",
|
"@eslint-community/eslint-utils": "^4.8.0",
|
||||||
"@eslint-community/regexpp": "^4.12.1",
|
"@eslint-community/regexpp": "^4.12.1",
|
||||||
@@ -2535,6 +2554,33 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/framer-motion": {
|
||||||
|
"version": "12.23.26",
|
||||||
|
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.23.26.tgz",
|
||||||
|
"integrity": "sha512-cPcIhgR42xBn1Uj+PzOyheMtZ73H927+uWPDVhUMqxy8UHt6Okavb6xIz9J/phFUHUj0OncR6UvMfJTXoc/LKA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"motion-dom": "^12.23.23",
|
||||||
|
"motion-utils": "^12.23.6",
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@emotion/is-prop-valid": "*",
|
||||||
|
"react": "^18.0.0 || ^19.0.0",
|
||||||
|
"react-dom": "^18.0.0 || ^19.0.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@emotion/is-prop-valid": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/fsevents": {
|
"node_modules/fsevents": {
|
||||||
"version": "2.3.3",
|
"version": "2.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||||
@@ -2761,6 +2807,15 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/jwt-decode": {
|
||||||
|
"version": "4.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
|
||||||
|
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/keyv": {
|
"node_modules/keyv": {
|
||||||
"version": "4.5.4",
|
"version": "4.5.4",
|
||||||
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
|
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
|
||||||
@@ -3089,6 +3144,21 @@
|
|||||||
"node": "*"
|
"node": "*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/motion-dom": {
|
||||||
|
"version": "12.23.23",
|
||||||
|
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.23.23.tgz",
|
||||||
|
"integrity": "sha512-n5yolOs0TQQBRUFImrRfs/+6X4p3Q4n1dUEqt/H58Vx7OW6RF+foWEgmTVDhIWJIMXOuNNL0apKH2S16en9eiA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"motion-utils": "^12.23.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/motion-utils": {
|
||||||
|
"version": "12.23.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-12.23.6.tgz",
|
||||||
|
"integrity": "sha512-eAWoPgr4eFEOFfg2WjIsMoqJTW6Z8MTUCgn/GZ3VRpClWBdnbjryiA3ZSNLyxCTmCQx4RmYX6jX1iWHbenUPNQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/ms": {
|
"node_modules/ms": {
|
||||||
"version": "2.1.3",
|
"version": "2.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||||
@@ -3222,7 +3292,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
|
||||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
},
|
},
|
||||||
@@ -3283,7 +3352,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
|
||||||
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
|
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
@@ -3310,6 +3378,60 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/react-router": {
|
||||||
|
"version": "7.10.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.10.1.tgz",
|
||||||
|
"integrity": "sha512-gHL89dRa3kwlUYtRQ+m8NmxGI6CgqN+k4XyGjwcFoQwwCWF6xXpOCUlDovkXClS0d0XJN/5q7kc5W3kiFEd0Yw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"cookie": "^1.0.1",
|
||||||
|
"set-cookie-parser": "^2.6.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=18",
|
||||||
|
"react-dom": ">=18"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/react-router-dom": {
|
||||||
|
"version": "6.30.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.2.tgz",
|
||||||
|
"integrity": "sha512-l2OwHn3UUnEVUqc6/1VMmR1cvZryZ3j3NzapC2eUXO1dB0sYp5mvwdjiXhpUbRb21eFow3qSxpP8Yv6oAU824Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@remix-run/router": "1.23.1",
|
||||||
|
"react-router": "6.30.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8",
|
||||||
|
"react-dom": ">=16.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/react-router-dom/node_modules/react-router": {
|
||||||
|
"version": "6.30.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.2.tgz",
|
||||||
|
"integrity": "sha512-H2Bm38Zu1bm8KUE5NVWRMzuIyAV8p/JrOaBJAwVmp37AXG72+CZJlEBw6pdn9i5TBgLMhNDgijS4ZlblpHyWTA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@remix-run/router": "1.23.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/resolve-from": {
|
"node_modules/resolve-from": {
|
||||||
"version": "4.0.0",
|
"version": "4.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
|
||||||
@@ -3377,6 +3499,12 @@
|
|||||||
"semver": "bin/semver.js"
|
"semver": "bin/semver.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/set-cookie-parser": {
|
||||||
|
"version": "2.7.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
|
||||||
|
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/shebang-command": {
|
"node_modules/shebang-command": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||||
@@ -3483,6 +3611,12 @@
|
|||||||
"typescript": ">=4.8.4"
|
"typescript": ">=4.8.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/tslib": {
|
||||||
|
"version": "2.8.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
||||||
|
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||||
|
"license": "0BSD"
|
||||||
|
},
|
||||||
"node_modules/type-check": {
|
"node_modules/type-check": {
|
||||||
"version": "0.4.0",
|
"version": "0.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
||||||
@@ -3502,7 +3636,6 @@
|
|||||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"tsc": "bin/tsc",
|
"tsc": "bin/tsc",
|
||||||
"tsserver": "bin/tsserver"
|
"tsserver": "bin/tsserver"
|
||||||
@@ -3588,7 +3721,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.2.7.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-7.2.7.tgz",
|
||||||
"integrity": "sha512-ITcnkFeR3+fI8P1wMgItjGrR10170d8auB4EpMLPqmx6uxElH3a/hHGQabSHKdqd4FXWO1nFIp9rRn7JQ34ACQ==",
|
"integrity": "sha512-ITcnkFeR3+fI8P1wMgItjGrR10170d8auB4EpMLPqmx6uxElH3a/hHGQabSHKdqd4FXWO1nFIp9rRn7JQ34ACQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "^0.25.0",
|
"esbuild": "^0.25.0",
|
||||||
"fdir": "^6.5.0",
|
"fdir": "^6.5.0",
|
||||||
@@ -3710,7 +3842,6 @@
|
|||||||
"integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==",
|
"integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/colinhacks"
|
"url": "https://github.com/sponsors/colinhacks"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,12 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tailwindcss/vite": "^4.1.18",
|
"@tailwindcss/vite": "^4.1.18",
|
||||||
|
"framer-motion": "^12.23.26",
|
||||||
|
"jwt-decode": "^4.0.0",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
"react-dom": "^19.2.0",
|
"react-dom": "^19.2.0",
|
||||||
|
"react-router": "^7.10.1",
|
||||||
|
"react-router-dom": "^6.30.2",
|
||||||
"tailwindcss": "^4.1.18"
|
"tailwindcss": "^4.1.18"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -1,20 +1,50 @@
|
|||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||||
|
import { AuthProvider, useAuth } from "./components/AuthContext";
|
||||||
|
import ProtectedRoute from "./components/ProtectedRoute";
|
||||||
|
|
||||||
import Landing from "./pages/Landing";
|
import Landing from "./pages/Landing";
|
||||||
// import Dashboard from "./pages/Dashboard";
|
|
||||||
import Dashboard from "./pages/Dashboard"
|
import Dashboard from "./pages/Dashboard"
|
||||||
import LoginModal from "./components/LoginModal";
|
import LoginModal from "./components/LoginModal";
|
||||||
|
import Navigation from "./components/Navigation";
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const [token, setToken] = useState(localStorage.getItem("token"));
|
// const [token] = useState(localStorage.getItem("token"));
|
||||||
const [showLogin, setShowLogin] = useState(false);
|
// const [showLogin, setShowLogin] = useState(false);
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
// const {token, logout } = useAuth();
|
||||||
|
|
||||||
if (!token)
|
// useEffect(() => {
|
||||||
|
// if (token) {
|
||||||
|
// // setShowLogin(false);
|
||||||
|
// setModalOpen(false);
|
||||||
|
// }
|
||||||
|
// }, [token]);
|
||||||
|
|
||||||
|
|
||||||
|
// if (!token)
|
||||||
return (
|
return (
|
||||||
<>
|
<AuthProvider>
|
||||||
<Landing onLogin={() => setShowLogin(true)} />
|
<BrowserRouter>
|
||||||
{showLogin && <LoginModal onSuccess={setToken} />}
|
<Navigation onLogin={() => setModalOpen(true)} />
|
||||||
</>
|
<LoginModal isOpen={modalOpen} onClose={() => setModalOpen(false)} />
|
||||||
|
|
||||||
|
<Routes>
|
||||||
|
<Route path="/" element={<Landing onLogin={() => setModalOpen(true)} />} />
|
||||||
|
{/* <Route path="/signup" element={<SignUp/>} /> */}
|
||||||
|
|
||||||
|
<Route path="/dashboard" element={ <ProtectedRoute><Dashboard /></ProtectedRoute> } />
|
||||||
|
</Routes>
|
||||||
|
</BrowserRouter>
|
||||||
|
</AuthProvider>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// <>
|
||||||
|
// <Landing onLogin={() => setShowLogin(true)} />
|
||||||
|
// {showLogin && <LoginModal onSuccess={setToken} />}
|
||||||
|
// </>
|
||||||
);
|
);
|
||||||
|
|
||||||
return <Dashboard />;
|
// return <Dashboard />;
|
||||||
}
|
}
|
||||||
|
|||||||
30
frontend/studia/src/api/user.tsx
Normal file
30
frontend/studia/src/api/user.tsx
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
const API_URL = 'http://localhost:8080';
|
||||||
|
|
||||||
|
|
||||||
|
export async function loginUser(Email:string, Password: string) {
|
||||||
|
const res = await fetch(`${API_URL}/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ Email, Password }),
|
||||||
|
});
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function registerUser(request: { Email: string; Username: string; Password: string; }){
|
||||||
|
console.log(request);
|
||||||
|
const res = await fetch(`${API_URL}/register`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(request),
|
||||||
|
});
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchUserProfile(token: string) {
|
||||||
|
const res = await fetch(`${API_URL}/profile`, {
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error('Profil konnte nicht geladen werden');
|
||||||
|
return res.json(); // { id: number, email: string, name: string }
|
||||||
|
}
|
||||||
109
frontend/studia/src/components/AuthContext.tsx
Normal file
109
frontend/studia/src/components/AuthContext.tsx
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
import { createContext, useState, useContext, useEffect } from "react";
|
||||||
|
import type { JSX } from 'react';
|
||||||
|
import { getUserFromToken } from '../utils/jwt';
|
||||||
|
// import { loginUser } from "../api/user";
|
||||||
|
|
||||||
|
// type AuthUser = { token: string } | null;
|
||||||
|
type AuthContextType = {
|
||||||
|
token: string | null;
|
||||||
|
userId: string | null;
|
||||||
|
login: (token: string, userId: string, role?: string[]) => void;
|
||||||
|
logout: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const AuthContext = createContext<AuthContextType | null>(null);
|
||||||
|
|
||||||
|
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||||
|
// export const AuthProvider = ({ children }: { children: JSX.Element }) => {
|
||||||
|
const [token, setToken] = useState<string | null>(null);
|
||||||
|
const [userId, setUserId] = useState<string | null>(null);
|
||||||
|
// const [userEmail, setuserEmail] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// useEffect(() => {
|
||||||
|
// const storedToken = localStorage.getItem('token');
|
||||||
|
// console.log(storedToken);
|
||||||
|
// const storedUserId = localStorage.getItem('userId');
|
||||||
|
// if (!storedToken) {
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
// // if (storedToken && storedUserId) {
|
||||||
|
// // setToken(storedToken);
|
||||||
|
// // setUserId(storedUserId);
|
||||||
|
// // }
|
||||||
|
// if (storedToken!==null) {
|
||||||
|
// setToken(storedToken);
|
||||||
|
// }
|
||||||
|
// if (storedUserId) {
|
||||||
|
// setUserId(storedUserId);
|
||||||
|
// }
|
||||||
|
// console.log(token);
|
||||||
|
|
||||||
|
|
||||||
|
// const user = getUserFromToken(storedToken);
|
||||||
|
// if (!user) {
|
||||||
|
// logout(); // z. B. localStorage.clear() + navigate("/login")
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
// // ⏳ Logout bei Ablauf
|
||||||
|
// const timeout = setTimeout(() => {
|
||||||
|
// logout();
|
||||||
|
// }, user.exp * 1000 - Date.now());
|
||||||
|
|
||||||
|
// return () => clearTimeout(timeout);
|
||||||
|
// }, [token]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const storedToken = localStorage.getItem('token');
|
||||||
|
const storedUserId = localStorage.getItem('userId');
|
||||||
|
if (!storedToken) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (storedToken && storedUserId) {
|
||||||
|
setToken(storedToken);
|
||||||
|
setUserId(storedUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = getUserFromToken(storedToken);
|
||||||
|
if (!user) {
|
||||||
|
logout(); // z.B. localStorage.clear() + navigate("/login")
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// ⏳ Logout bei Ablauf
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
logout();
|
||||||
|
}, user.exp * 1000 - Date.now());
|
||||||
|
|
||||||
|
return () => clearTimeout(timeout);
|
||||||
|
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const login = (token: string, userId: string, role: string[] = []) => {
|
||||||
|
setToken(token);
|
||||||
|
setUserId(userId);
|
||||||
|
|
||||||
|
localStorage.setItem('token', token);
|
||||||
|
localStorage.setItem('userId', userId);
|
||||||
|
localStorage.setItem('role', JSON.stringify(role)); // Store array as string
|
||||||
|
};
|
||||||
|
|
||||||
|
const logout = () => {
|
||||||
|
setToken(null);
|
||||||
|
setUserId(null);
|
||||||
|
localStorage.removeItem('token');
|
||||||
|
localStorage.removeItem('userId');
|
||||||
|
localStorage.clear();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthContext.Provider value={{ token, userId, login, logout }}>
|
||||||
|
{children}
|
||||||
|
</AuthContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useAuth() {
|
||||||
|
const context = useContext(AuthContext);
|
||||||
|
if (!context) throw new Error('useAuth must be used within AuthProvider');
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
// export const useAuth = () => useContext(AuthContext);
|
||||||
71
frontend/studia/src/components/Card.tsx
Normal file
71
frontend/studia/src/components/Card.tsx
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { motion } from "framer-motion";
|
||||||
|
|
||||||
|
export default function FlipCard({ front, back }: { front: string; back: string }) {
|
||||||
|
const [flipped, setFlipped] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="w-80 h-52 perspective cursor-pointer"
|
||||||
|
onClick={() => setFlipped(!flipped)}
|
||||||
|
onKeyDown={(e) => e.key === " " && setFlipped(!flipped)}
|
||||||
|
tabIndex={0}
|
||||||
|
role="button"
|
||||||
|
aria-label="Flip card"
|
||||||
|
>
|
||||||
|
<motion.div
|
||||||
|
className="relative w-full h-full"
|
||||||
|
animate={{ rotateY: flipped ? 180 : 0 }}
|
||||||
|
transition={{ duration: 0.45, ease: "easeInOut" }}
|
||||||
|
style={{ transformStyle: "preserve-3d" }}
|
||||||
|
>
|
||||||
|
{/* Front */}
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center rounded-2xl bg-white shadow-lg backface-hidden">
|
||||||
|
<p className="text-xl font-semibold text-center px-4 text-black ">
|
||||||
|
{front}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Back */}
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center rounded-2xl bg-white shadow-lg backface-hidden rotate-y-180">
|
||||||
|
<p className="text-xl text-center px-4 text-black">
|
||||||
|
{back}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* Tailwind can't handle these directly */}
|
||||||
|
<style>{`
|
||||||
|
.perspective {
|
||||||
|
perspective: 1000px;
|
||||||
|
}
|
||||||
|
.backface-hidden {
|
||||||
|
backface-visibility: hidden;
|
||||||
|
}
|
||||||
|
.rotate-y-180 {
|
||||||
|
transform: rotateY(180deg);
|
||||||
|
}
|
||||||
|
`}</style>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
USAGE (Vite + Tailwind):
|
||||||
|
|
||||||
|
<FlipCard
|
||||||
|
front="What is the capital of France?"
|
||||||
|
back="Paris"
|
||||||
|
/>
|
||||||
|
|
||||||
|
Stack:
|
||||||
|
- Vite
|
||||||
|
- React
|
||||||
|
- Tailwind CSS
|
||||||
|
- Framer Motion
|
||||||
|
|
||||||
|
Behavior:
|
||||||
|
- Quizlet-style flip
|
||||||
|
- Click or spacebar to flip
|
||||||
|
- Smooth 3D animation
|
||||||
|
*/
|
||||||
@@ -1,23 +1,155 @@
|
|||||||
|
import {loginUser, registerUser} from "../api/user";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { useAuth } from './AuthContext';
|
||||||
|
|
||||||
export default function LoginModal({ onSuccess }: any) {
|
export default function LoginModal({ isOpen, onClose, onSuccess }: any) {
|
||||||
const login = async () => {
|
const navigate = useNavigate(); // ← Navigation-Hook
|
||||||
const res = await fetch("http://localhost:8080/login", { method: "POST" });
|
const { login } = useAuth();
|
||||||
const data = await res.json();
|
const [isRegistering, setIsRegistering] = useState(false);
|
||||||
localStorage.setItem("token", data.token);
|
if (!isOpen) return null; // 👈 THIS is the key
|
||||||
onSuccess(data.token);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return(
|
||||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center">
|
<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center">
|
||||||
<div className="bg-white rounded-2xl p-8 w-96 shadow-xl">
|
<div className="bg-white rounded-2xl p-8 w-96 shadow-xl">
|
||||||
<h2 className="text-2xl font-bold mb-6">Login</h2>
|
<div className="flex justify-between items-center mb-6">
|
||||||
|
<h2 className="text-2xl font-bold">Login</h2>
|
||||||
|
<button onClick={onClose} className="text-gray-400 hover:text-gray-600 p-2">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="size-6">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{isRegistering ? (
|
||||||
|
<form
|
||||||
|
onSubmit={async (e: any) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const fd = new FormData(e.currentTarget);
|
||||||
|
const email = fd.get("email");
|
||||||
|
const username = fd.get("username");
|
||||||
|
const password = fd.get("password");
|
||||||
|
const confirmPassword = fd.get("confirmPassword");
|
||||||
|
|
||||||
|
if (password !== confirmPassword) {
|
||||||
|
alert("Passwords do not match!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!username) {
|
||||||
|
alert("Please enter a username!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await registerUser(
|
||||||
|
{ Email: email as string, Username: username as string, Password: password as string }
|
||||||
|
);
|
||||||
|
console.log(res);
|
||||||
|
if (!res.ok) {
|
||||||
|
alert("Registration failed!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Implement actual registration logic here
|
||||||
|
console.log("Registering with:", email, password);
|
||||||
|
// For now, let's just switch back to login after a "successful" registration
|
||||||
|
setIsRegistering(false);
|
||||||
|
}}
|
||||||
|
className="space-y-4"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
placeholder="Email"
|
||||||
|
required
|
||||||
|
className="w-full border rounded-xl px-3 py-2"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
name="username"
|
||||||
|
type="text"
|
||||||
|
placeholder="Username"
|
||||||
|
required
|
||||||
|
className="w-full border rounded-xl px-3 py-2"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
placeholder="Password"
|
||||||
|
required
|
||||||
|
className="w-full border rounded-xl px-3 py-2"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
name="confirmPassword"
|
||||||
|
type="password"
|
||||||
|
placeholder="Confirm Password"
|
||||||
|
required
|
||||||
|
className="w-full border rounded-xl px-3 py-2"
|
||||||
|
/>
|
||||||
<button
|
<button
|
||||||
onClick={login}
|
type="submit"
|
||||||
className="w-full bg-indigo-600 text-white py-3 rounded-xl hover:bg-indigo-700"
|
className="w-full bg-indigo-600 text-white py-3 rounded-xl hover:bg-indigo-700"
|
||||||
>
|
>
|
||||||
Login as Demo
|
Register
|
||||||
</button>
|
</button>
|
||||||
</div>
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsRegistering(false)}
|
||||||
|
className="w-full bg-gray-200 text-gray-800 py-3 rounded-xl hover:bg-gray-300 mt-2"
|
||||||
|
>
|
||||||
|
Back to Login
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<form
|
||||||
|
onSubmit={async (e: any) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const fd = new FormData(e.currentTarget);
|
||||||
|
const email = fd.get("email");
|
||||||
|
const password = fd.get("password");
|
||||||
|
const res = await loginUser(email as string, password as string);
|
||||||
|
if (!res.ok) {
|
||||||
|
alert("Login failed!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = await res.json();
|
||||||
|
console.log(data);
|
||||||
|
login(data.token, data.userId,[]);
|
||||||
|
// localStorage.setItem("token", data.token);
|
||||||
|
|
||||||
|
onClose();
|
||||||
|
navigate("/");
|
||||||
|
}}
|
||||||
|
className="space-y-4"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
placeholder="Email"
|
||||||
|
required
|
||||||
|
className="w-full border rounded-xl px-3 py-2"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
placeholder="Password"
|
||||||
|
required
|
||||||
|
className="w-full border rounded-xl px-3 py-2"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="w-full bg-indigo-600 text-white py-3 rounded-xl hover:bg-indigo-700"
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsRegistering(true)}
|
||||||
|
className="w-full bg-gray-200 text-gray-800 py-3 rounded-xl hover:bg-gray-300 mt-2"
|
||||||
|
>
|
||||||
|
Register
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
39
frontend/studia/src/components/Navigation.tsx
Normal file
39
frontend/studia/src/components/Navigation.tsx
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import { useAuth } from './AuthContext';
|
||||||
|
|
||||||
|
export default function Navigation({ onLogin }: { onLogin: () => void }) {
|
||||||
|
const { token, logout } = useAuth();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<nav className="bg-white shadow p-4 flex justify-between items-center">
|
||||||
|
<div className="text-2xl font-bold text-indigo-700"><Link to="/">Studia</Link></div>
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
{token && (
|
||||||
|
<>
|
||||||
|
<a href="/dashboard" className="text-gray-600 hover:text-indigo-700">
|
||||||
|
Dashboard
|
||||||
|
</a>
|
||||||
|
<a href="#" className="text-gray-600 hover:text-indigo-700">
|
||||||
|
Settings
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{token ? (
|
||||||
|
<button
|
||||||
|
onClick={logout}
|
||||||
|
className="bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition"
|
||||||
|
>
|
||||||
|
Logout
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={onLogin}
|
||||||
|
className="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition"
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
17
frontend/studia/src/components/ProtectedRoute.tsx
Normal file
17
frontend/studia/src/components/ProtectedRoute.tsx
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { Navigate } from "react-router-dom";
|
||||||
|
import { useAuth } from "../components/AuthContext";
|
||||||
|
import type { JSX } from 'react';
|
||||||
|
|
||||||
|
const ProtectedRoute = ({ children }: { children: JSX.Element }) => {
|
||||||
|
// const { token } = useAuth();
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
// console.log(token);
|
||||||
|
if(token!=null)
|
||||||
|
return children;
|
||||||
|
else
|
||||||
|
console.log(token)
|
||||||
|
return <Navigate to="/" />;
|
||||||
|
// return token ? children : <Navigate to="/" />;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ProtectedRoute;
|
||||||
@@ -1,14 +1,17 @@
|
|||||||
import Builder from "./Builder";
|
import Builder from "./Builder";
|
||||||
import Learn from "./Learn";
|
import Learn from "./Learn";
|
||||||
import Admin from "./Admin";
|
import Admin from "./Admin";
|
||||||
|
// import { useAuth } from "../components/AuthContext";
|
||||||
|
|
||||||
export default function Dashboard() {
|
export default function Dashboard() {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-100 p-6 space-y-10">
|
<div className="min-h-screen bg-gray-100">
|
||||||
<Builder />
|
<div className="p-6 space-y-10">
|
||||||
<Learn />
|
<Builder />
|
||||||
<Admin />
|
<Learn />
|
||||||
|
<Admin />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,42 @@
|
|||||||
|
import { useEffect } from "react";
|
||||||
|
import { useAuth } from "../components/AuthContext";
|
||||||
|
import Card from "../components/Card"
|
||||||
|
|
||||||
export default function Landing({ onLogin }: { onLogin: () => void }) {
|
export default function Landing({ onLogin }: { onLogin: () => void }) {
|
||||||
|
const {token} = useAuth();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
console.log(token)
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gradient-to-br from-indigo-600 to-purple-700 text-white">
|
<div className="min-h-screen bg-gradient-to-br from-indigo-600 to-purple-700 text-white">
|
||||||
<div className="max-w-6xl mx-auto px-6 py-24 text-center">
|
<div className="max-w-6xl mx-auto px-6 py-24 text-center">
|
||||||
<h1 className="text-5xl font-bold mb-6">Cardify</h1>
|
<h1 className="text-5xl font-bold mb-6">Studia</h1>
|
||||||
<p className="text-xl opacity-90 mb-12">
|
<p className="text-xl opacity-90 mb-12">
|
||||||
Learn smarter with flashcards & spaced repetition
|
Learn smarter with flashcards & spaced repetition
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div className="grid md:grid-cols-3 gap-6 mb-12">
|
<div className="grid md:grid-cols-3 gap-6 mb-12">
|
||||||
{["HTTP", "JWT", "REST"].map(t => (
|
{["HTTP", "JWT", "REST"].map(t => (
|
||||||
<div key={t} className="bg-white/10 p-6 rounded-xl backdrop-blur">
|
// <div key={t} className="bg-white/10 p-6 rounded-xl backdrop-blur">
|
||||||
<h3 className="font-semibold text-lg">{t}</h3>
|
// <h3 className="font-semibold text-lg">{t}</h3>
|
||||||
<p className="opacity-80 mt-2">Sample definition</p>
|
// <p className="opacity-80 mt-2">Sample definition</p>
|
||||||
</div>
|
// </div>
|
||||||
|
<Card front={t} back="Sample definition"></Card>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
{token? (
|
||||||
<button
|
<div> </div>
|
||||||
|
) :
|
||||||
|
(
|
||||||
|
<button
|
||||||
onClick={onLogin}
|
onClick={onLogin}
|
||||||
className="bg-white text-indigo-700 px-8 py-3 rounded-xl font-semibold hover:scale-105 transition"
|
className="bg-white text-indigo-700 px-8 py-3 rounded-xl font-semibold hover:scale-105 transition"
|
||||||
>
|
>
|
||||||
Get Started
|
Get Started
|
||||||
</button>
|
</button>
|
||||||
|
) }
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
0
frontend/studia/src/pages/SignUp.tsx
Normal file
0
frontend/studia/src/pages/SignUp.tsx
Normal file
23
frontend/studia/src/utils/jwt.tsx
Normal file
23
frontend/studia/src/utils/jwt.tsx
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
// utils/jwt.ts
|
||||||
|
import { jwtDecode } from 'jwt-decode';
|
||||||
|
|
||||||
|
export interface TokenPayload {
|
||||||
|
userId: string;
|
||||||
|
email: string;
|
||||||
|
role: string[];
|
||||||
|
exp: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getUserFromToken(token: string): TokenPayload | null {
|
||||||
|
try {
|
||||||
|
const decoded = jwtDecode<TokenPayload>(token);
|
||||||
|
if (decoded.exp && decoded.exp < Date.now() / 1000) {
|
||||||
|
console.warn("Token ist abgelaufen");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return decoded;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Fehler beim Decodieren des Tokens:", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
17
nginx.conf
Normal file
17
nginx.conf
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
server {
|
||||||
|
listen 3000;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://backend:8081;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user