Compare commits
3 Commits
a047d57824
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4eb2efb33 | ||
|
|
435ad8e6e6 | ||
|
|
7ec17e1e8b |
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;"]
|
||||
BIN
backend/cli
Executable file
BIN
backend/cli
Executable file
Binary file not shown.
@@ -9,8 +9,8 @@ import (
|
||||
)
|
||||
|
||||
var RootCmd = &cobra.Command{
|
||||
Use: "myapp",
|
||||
Short: "MyApp admin CLI",
|
||||
Use: "studia",
|
||||
Short: "studia admin CLI",
|
||||
}
|
||||
|
||||
func Execute() {
|
||||
|
||||
@@ -3,36 +3,42 @@ package user
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
// "studia/internal/db"
|
||||
usersvc "studia/internal/user"
|
||||
"studia/internal/config"
|
||||
"studia/internal/database"
|
||||
"studia/internal/user"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var id int64
|
||||
var email string
|
||||
|
||||
var getCmd = &cobra.Command{
|
||||
|
||||
Use: "get",
|
||||
Short: "Get user by ID",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
database, err := db.New(getDSN())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg := config.New()
|
||||
|
||||
service := usersvc.NewService(database)
|
||||
user, err := service.GetByID(id)
|
||||
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.Name)
|
||||
user.ID, user.Email, user.Username)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
getCmd.Flags().Int64Var(&id, "id", 0, "user ID")
|
||||
getCmd.MarkFlagRequired("id")
|
||||
getCmd.Flags().StringVar(&email, "email", "", "user email")
|
||||
getCmd.MarkFlagRequired("email")
|
||||
}
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
// cmd/cli/user/list.go
|
||||
package user
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"myapp/internal/db"
|
||||
usersvc "myapp/internal/user"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var listCmd = &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List users",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
database, err := db.New(getDSN())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
service := usersvc.NewService(database)
|
||||
users, err := service.List()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, u := range users {
|
||||
fmt.Printf("%d | %s | %s\n", u.ID, u.Email, u.Name)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
@@ -8,6 +8,6 @@ var UserCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
func init() {
|
||||
UserCmd.AddCommand(listCmd)
|
||||
// UserCmd.AddCommand(listCmd)
|
||||
UserCmd.AddCommand(getCmd)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"studia/internal/config"
|
||||
"studia/internal/logger"
|
||||
"studia/internal/server"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger.Init()
|
||||
|
||||
cfg := config.New()
|
||||
|
||||
@@ -16,8 +17,8 @@ func main() {
|
||||
cfg.DatabasePassword = "12345678"
|
||||
cfg.DatabaseName = "studia"
|
||||
|
||||
log.Println("Configuration loaded:", cfg)
|
||||
logger.Log.Info().Msgf("Configuration loaded: %+v", cfg)
|
||||
|
||||
log.Println("Starting server...")
|
||||
logger.Log.Info().Msg("Starting server...")
|
||||
server.StartServer(cfg)
|
||||
}
|
||||
|
||||
@@ -7,10 +7,10 @@ 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,
|
||||
name 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 DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at timestamp with time zone ,
|
||||
CONSTRAINT users_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT users_email_key UNIQUE (email)
|
||||
)
|
||||
|
||||
@@ -8,7 +8,9 @@ require (
|
||||
)
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
@@ -34,6 +36,7 @@ require (
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/quic-go/qpack v0.5.1 // 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/ugorji/go/codec v1.3.0 // indirect
|
||||
|
||||
@@ -4,6 +4,7 @@ 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/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
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.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
@@ -16,6 +17,8 @@ github.com/gin-contrib/cors v1.7.6 h1:3gQ8GMzs1Ylpf70y8bMw4fVpycXIeX1ZemuSQIsnQQ
|
||||
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/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/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
@@ -32,6 +35,7 @@ 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/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/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
@@ -47,6 +51,10 @@ 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/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
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/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
@@ -57,12 +65,16 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
|
||||
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/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/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
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/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/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=
|
||||
@@ -94,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/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
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.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
|
||||
|
||||
@@ -2,7 +2,9 @@ package auth
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"net/http"
|
||||
"studia/internal/logger"
|
||||
"studia/internal/user"
|
||||
"time"
|
||||
|
||||
@@ -11,42 +13,77 @@ import (
|
||||
)
|
||||
|
||||
type LoginRequest struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
|
||||
type RegisterRequest struct {
|
||||
Email string
|
||||
Password string
|
||||
Username string
|
||||
}
|
||||
|
||||
const defaultRole = "user"
|
||||
|
||||
var secret = []byte("secret")
|
||||
|
||||
func Login(c *gin.Context, db *sql.DB) {
|
||||
func Login(c *gin.Context, db *sql.DB) error {
|
||||
var req LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
||||
return
|
||||
return err
|
||||
}
|
||||
|
||||
if req.Email == "" || req.Password == "" {
|
||||
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)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email or password"})
|
||||
return
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email "})
|
||||
return err
|
||||
}
|
||||
logger.Log.Info().Msgf("User: %+v", User)
|
||||
|
||||
if !user.CheckPasswordHash(db, User.Email, req.Password) {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid email or password"})
|
||||
return
|
||||
err = user.CheckPasswordHash(db, User.Email, req.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
token, err := GenerateJWT(User.ID, User.Email, User.Role)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not generate token"})
|
||||
return
|
||||
return err
|
||||
}
|
||||
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) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"studia/internal/config"
|
||||
"studia/internal/logger"
|
||||
|
||||
_ "github.com/lib/pq" // Import the PostgreSQL driver
|
||||
)
|
||||
@@ -22,7 +23,7 @@ func New(cfg *config.Config) *sql.DB {
|
||||
WHERE table_schema = 'public'
|
||||
`)
|
||||
if err != nil {
|
||||
log.Println("failed to query existing tables:", err)
|
||||
logger.Log.Error().Err(err).Msg("Failed to query existing tables")
|
||||
}
|
||||
|
||||
missing := checkTables(expectedTables, existing)
|
||||
@@ -32,7 +33,7 @@ func New(cfg *config.Config) *sql.DB {
|
||||
// Here you would normally run migrations to create the missing tables
|
||||
// For simplicity, we just log the missing tables
|
||||
} else {
|
||||
log.Println("All expected tables are present.")
|
||||
logger.Log.Info().Msg("All expected tables are present.")
|
||||
}
|
||||
|
||||
return db
|
||||
@@ -41,7 +42,7 @@ func New(cfg *config.Config) *sql.DB {
|
||||
func setupDatabase(cfg *config.Config) *sql.DB {
|
||||
// Database connection setup logic here
|
||||
|
||||
log.Println(cfg)
|
||||
logger.Log.Println(cfg)
|
||||
switch cfg.DatabaseDriver {
|
||||
case "postgres":
|
||||
// Setup Postgres connection
|
||||
|
||||
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,12 +1,10 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"studia/internal/auth"
|
||||
"studia/internal/config"
|
||||
"studia/internal/database"
|
||||
"studia/internal/logger"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
@@ -21,18 +19,19 @@ func StartServer(cfg *config.Config) {
|
||||
|
||||
// 2. CORS-Konfiguration
|
||||
// Lese die Frontend-URL aus den Umgebungsvariablen
|
||||
frontendURL := os.Getenv("FRONTEND_URL")
|
||||
// frontendURL := os.Getenv("FRONTEND_URL")
|
||||
|
||||
// Lokaler Fallback (wichtig für die Entwicklung)
|
||||
allowedOrigins := []string{
|
||||
"http://localhost:5173", // Gängiger Vite-Dev-Port
|
||||
"http://127.0.0.1:5173",
|
||||
}
|
||||
|
||||
if frontendURL != "" {
|
||||
allowedOrigins = append(allowedOrigins, frontendURL)
|
||||
fmt.Printf("CORS: Erlaubte Produktiv-URL hinzugefügt: %s\n", frontendURL)
|
||||
if cfg.FrontendURL != "" {
|
||||
allowedOrigins = append(allowedOrigins, cfg.FrontendURL)
|
||||
logger.Log.Printf("CORS: Erlaubte Produktiv-URL hinzugefügt: %s\n", cfg.FrontendURL)
|
||||
} else {
|
||||
log.Println("ACHTUNG: FRONTEND_URL fehlt in den Umgebungsvariablen. Nur lokale URLs erlaubt.")
|
||||
logger.Log.Error().Msg("ACHTUNG: FRONTEND_URL fehlt in den Umgebungsvariablen. Nur lokale URLs erlaubt.")
|
||||
}
|
||||
|
||||
// CORS
|
||||
@@ -52,7 +51,18 @@ func StartServer(cfg *config.Config) {
|
||||
router.Use(cors.New(config))
|
||||
|
||||
router.POST("/login", func(c *gin.Context) {
|
||||
auth.Login(c, db) // Pass the actual DB connection instead of nil
|
||||
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 (
|
||||
"database/sql"
|
||||
"studia/internal/logger"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
@@ -10,7 +11,7 @@ import (
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Username string `json:"username"`
|
||||
PasswordHash string `json:"-"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
@@ -28,26 +29,33 @@ type User struct {
|
||||
// }
|
||||
|
||||
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
|
||||
err := row.Scan(&user.ID, &user.Email, &user.PasswordHash, &user.Role)
|
||||
err := row.Scan(&user.ID, &user.Email, &user.Username)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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)
|
||||
var hash string
|
||||
var hash []byte
|
||||
if err := row.Scan(&hash); err != nil {
|
||||
return false
|
||||
return err
|
||||
}
|
||||
UserPasswordHash, error := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if error != nil {
|
||||
return false
|
||||
UserPasswordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
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 {
|
||||
@@ -56,7 +64,7 @@ func CreateUser(db *sql.DB, email string, name string, password string, role []s
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = db.Exec("INSERT INTO users (email, name, password_hash, role, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
email, name, string(passwordHash), role, time.Now(), time.Now())
|
||||
_, err = db.Exec("INSERT INTO users (email, username, password_hash) VALUES ($1, $2, $3)",
|
||||
email, name, string(passwordHash))
|
||||
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
|
||||
62
frontend/studia/package-lock.json
generated
62
frontend/studia/package-lock.json
generated
@@ -9,6 +9,7 @@
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"framer-motion": "^12.23.26",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
@@ -62,7 +63,6 @@
|
||||
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@babel/generator": "^7.28.5",
|
||||
@@ -1607,7 +1607,6 @@
|
||||
"integrity": "sha512-gqkrWUsS8hcm0r44yn7/xZeV1ERva/nLgrLxFRUGb7aoNMIJfZJ3AC261zDQuOAKC7MiXai1WCpYc48jAHoShQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"undici-types": "~7.16.0"
|
||||
}
|
||||
@@ -1618,7 +1617,6 @@
|
||||
"integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"csstype": "^3.2.2"
|
||||
}
|
||||
@@ -1678,7 +1676,6 @@
|
||||
"integrity": "sha512-N9lBGA9o9aqb1hVMc9hzySbhKibHmB+N3IpoShyV6HyQYRGIhlrO5rQgttypi+yEeKsKI4idxC8Jw6gXKD4THA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.49.0",
|
||||
"@typescript-eslint/types": "8.49.0",
|
||||
@@ -1930,7 +1927,6 @@
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -2036,7 +2032,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.9.0",
|
||||
"caniuse-lite": "^1.0.30001759",
|
||||
@@ -2292,7 +2287,6 @@
|
||||
"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.8.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -2560,6 +2554,33 @@
|
||||
"dev": true,
|
||||
"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": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
@@ -3123,6 +3144,21 @@
|
||||
"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": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
@@ -3256,7 +3292,6 @@
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -3317,7 +3352,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
|
||||
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -3327,7 +3361,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
|
||||
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
@@ -3578,6 +3611,12 @@
|
||||
"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": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
||||
@@ -3597,7 +3636,6 @@
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -3683,7 +3721,6 @@
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.2.7.tgz",
|
||||
"integrity": "sha512-ITcnkFeR3+fI8P1wMgItjGrR10170d8auB4EpMLPqmx6uxElH3a/hHGQabSHKdqd4FXWO1nFIp9rRn7JQ34ACQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.5.0",
|
||||
@@ -3805,7 +3842,6 @@
|
||||
"integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"framer-motion": "^12.23.26",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
|
||||
@@ -1,27 +1,39 @@
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||
import { AuthProvider } from "./components/AuthContext";
|
||||
import { AuthProvider, useAuth } from "./components/AuthContext";
|
||||
import ProtectedRoute from "./components/ProtectedRoute";
|
||||
|
||||
import Landing from "./pages/Landing";
|
||||
import Dashboard from "./pages/Dashboard"
|
||||
import LoginModal from "./components/LoginModal";
|
||||
import Navigation from "./components/Navigation";
|
||||
|
||||
export default function App() {
|
||||
const [token, setToken] = useState(localStorage.getItem("token"));
|
||||
// const [token] = useState(localStorage.getItem("token"));
|
||||
// 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 (
|
||||
<AuthProvider>
|
||||
<BrowserRouter>
|
||||
<Navigation onLogin={() => setModalOpen(true)} />
|
||||
<LoginModal isOpen={modalOpen} onClose={() => setModalOpen(false)} />
|
||||
|
||||
<Routes>
|
||||
<Route path="/" element={<Landing onLogin={() => setModalOpen(true)} />} />
|
||||
<Route path="/dashboard" element={ <ProtectedRoute><Dashboard /></ProtectedRoute> }
|
||||
{/* <Route path="/signup" element={<SignUp/>} /> */}
|
||||
|
||||
/>
|
||||
<Route path="/dashboard" element={ <ProtectedRoute><Dashboard /></ProtectedRoute> } />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</AuthProvider>
|
||||
@@ -34,5 +46,5 @@ export default function App() {
|
||||
// </>
|
||||
);
|
||||
|
||||
return <Dashboard />;
|
||||
// return <Dashboard />;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
const API_URL = 'http://localhost:8080';
|
||||
|
||||
|
||||
export async function loginUser(email:string, password: string) {
|
||||
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 }),
|
||||
body: JSON.stringify({ Email, Password }),
|
||||
});
|
||||
if (!res.ok) throw new Error('Login fehlgeschlagen');
|
||||
return res.json(); // { token: string }
|
||||
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) {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { createContext, useState, useContext, useEffect } from "react";
|
||||
import type { JSX } from 'react';
|
||||
import { getUserFromToken } from '../utils/jwt';
|
||||
import { loginUser } from "../api/user";
|
||||
// import { loginUser } from "../api/user";
|
||||
|
||||
type AuthUser = { token: string } | null;
|
||||
// type AuthUser = { token: string } | null;
|
||||
type AuthContextType = {
|
||||
token: string | null;
|
||||
userId: string | null;
|
||||
@@ -13,16 +13,50 @@ type AuthContextType = {
|
||||
|
||||
const AuthContext = createContext<AuthContextType | null>(null);
|
||||
|
||||
export const AuthProvider = ({ children }: { children: JSX.Element }) => {
|
||||
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);
|
||||
// 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;
|
||||
return
|
||||
}
|
||||
if (storedToken && storedUserId) {
|
||||
setToken(storedToken);
|
||||
@@ -31,7 +65,7 @@ export const AuthProvider = ({ children }: { children: JSX.Element }) => {
|
||||
|
||||
const user = getUserFromToken(storedToken);
|
||||
if (!user) {
|
||||
logout(); // z. B. localStorage.clear() + navigate("/login")
|
||||
logout(); // z.B. localStorage.clear() + navigate("/login")
|
||||
return;
|
||||
}
|
||||
// ⏳ Logout bei Ablauf
|
||||
@@ -40,14 +74,16 @@ export const AuthProvider = ({ children }: { children: JSX.Element }) => {
|
||||
}, 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
|
||||
localStorage.setItem('role', JSON.stringify(role)); // Store array as string
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
@@ -55,6 +91,7 @@ export const AuthProvider = ({ children }: { children: JSX.Element }) => {
|
||||
setUserId(null);
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('userId');
|
||||
localStorage.clear();
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -64,4 +101,9 @@ export const AuthProvider = ({ children }: { children: JSX.Element }) => {
|
||||
);
|
||||
};
|
||||
|
||||
export const useAuth = () => useContext(AuthContext);
|
||||
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,25 +1,121 @@
|
||||
import {loginUser} from "../api/user";
|
||||
import {loginUser, registerUser} from "../api/user";
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from './AuthContext';
|
||||
|
||||
export default function LoginModal({ isOpen, onSuccess }: any) {
|
||||
export default function LoginModal({ isOpen, onClose, onSuccess }: any) {
|
||||
const navigate = useNavigate(); // ← Navigation-Hook
|
||||
const { login } = useAuth();
|
||||
const [isRegistering, setIsRegistering] = useState(false);
|
||||
if (!isOpen) return null; // 👈 THIS is the key
|
||||
|
||||
return(
|
||||
<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">
|
||||
<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
|
||||
type="submit"
|
||||
className="w-full bg-indigo-600 text-white py-3 rounded-xl hover:bg-indigo-700"
|
||||
>
|
||||
Register
|
||||
</button>
|
||||
<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();
|
||||
localStorage.setItem("token", data.token);
|
||||
onSuccess(data.token);
|
||||
console.log(data);
|
||||
login(data.token, data.userId,[]);
|
||||
// localStorage.setItem("token", data.token);
|
||||
|
||||
onClose();
|
||||
navigate("/");
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
@@ -44,7 +140,15 @@ export default function LoginModal({ isOpen, onSuccess }: any) {
|
||||
>
|
||||
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>
|
||||
);
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -3,8 +3,15 @@ import { useAuth } from "../components/AuthContext";
|
||||
import type { JSX } from 'react';
|
||||
|
||||
const ProtectedRoute = ({ children }: { children: JSX.Element }) => {
|
||||
const { token } = useAuth() as { token?: string | null };
|
||||
return token ? children : <Navigate to="/" />;
|
||||
// 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 Learn from "./Learn";
|
||||
import Admin from "./Admin";
|
||||
|
||||
// import { useAuth } from "../components/AuthContext";
|
||||
|
||||
export default function Dashboard() {
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 p-6 space-y-10">
|
||||
<div className="min-h-screen bg-gray-100">
|
||||
<div className="p-6 space-y-10">
|
||||
<Builder />
|
||||
<Learn />
|
||||
<Admin />
|
||||
</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 }) {
|
||||
const {token} = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
console.log(token)
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<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">
|
||||
<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">
|
||||
Learn smarter with flashcards & spaced repetition
|
||||
</p>
|
||||
|
||||
<div className="grid md:grid-cols-3 gap-6 mb-12">
|
||||
{["HTTP", "JWT", "REST"].map(t => (
|
||||
<div key={t} className="bg-white/10 p-6 rounded-xl backdrop-blur">
|
||||
<h3 className="font-semibold text-lg">{t}</h3>
|
||||
<p className="opacity-80 mt-2">Sample definition</p>
|
||||
</div>
|
||||
// <div key={t} className="bg-white/10 p-6 rounded-xl backdrop-blur">
|
||||
// <h3 className="font-semibold text-lg">{t}</h3>
|
||||
// <p className="opacity-80 mt-2">Sample definition</p>
|
||||
// </div>
|
||||
<Card front={t} back="Sample definition"></Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{token? (
|
||||
<div> </div>
|
||||
) :
|
||||
(
|
||||
<button
|
||||
onClick={onLogin}
|
||||
className="bg-white text-indigo-700 px-8 py-3 rounded-xl font-semibold hover:scale-105 transition"
|
||||
>
|
||||
Get Started
|
||||
</button>
|
||||
) }
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
0
frontend/studia/src/pages/SignUp.tsx
Normal file
0
frontend/studia/src/pages/SignUp.tsx
Normal file
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