Merge branch 'dev/cedric' into dev/guerby

This commit is contained in:
gom-by
2025-01-17 15:40:06 +01:00
26 changed files with 515 additions and 97 deletions

View File

@@ -53,13 +53,8 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
return return
} }
var user core.User user, err := core.Verify(context.Background(), login.Email, login.Password)
count, err := core.DB.NewSelect(). if user == nil {
Model(&user).
Where("email = ? AND password = ?", login.Email, login.Password).
Limit(1).
ScanAndCount(context.Background())
if count == 0 {
core.JSONError{ core.JSONError{
Status: core.Error, Status: core.Error,
Message: "User not found.", Message: "User not found.",
@@ -140,8 +135,10 @@ func AuthJWT(next http.Handler) http.Handler {
return return
} }
ctx := context.WithValue(r.Context(), "token", token)
// Call the next handler if the JWT is valid // Call the next handler if the JWT is valid
next.ServeHTTP(w, r) next.ServeHTTP(w, r.WithContext(ctx))
}) })
} }

View File

@@ -36,8 +36,8 @@ const (
type Status string type Status string
const ( const (
Active Status = "Active" Active Status = "Active"
Inactive Status = "Inactive" Inactive Status = "Inactive"
) )
type User struct { type User struct {
@@ -56,6 +56,43 @@ type User struct {
Articles []*Blog `bun:"rel:has-many,join:user_id=blog_id" json:"articles,omitempty"` Articles []*Blog `bun:"rel:has-many,join:user_id=blog_id" json:"articles,omitempty"`
} }
func (u *User) Insert(ctx context.Context) (sql.Result, error) {
u.Password = fmt.Sprintf("crypt('%s', gen_salt('bf'))", u.Password)
return DB.NewInsert().
Model(u).
Value("password", u.Password).
Exec(ctx)
}
func Verify(ctx context.Context, email, password string) (*User, error) {
// var user User
// query := `
// SELECT *
// FROM users
// WHERE email = ? AND password = crypt(?, password)
// `
//
// err := DB.NewRaw(query, email, password).Scan(ctx, user)
var user User
count, err := DB.NewSelect().
Model(&user).
Where("email = ? AND password = crypt(?, password)", email, password).
Limit(1).
ScanAndCount(context.Background())
if count == 0 {
return nil, fmt.Errorf("invalid email or password")
}
if err != nil {
if err == sql.ErrNoRows {
return nil, fmt.Errorf("invalid email or password")
}
return nil, err
}
return &user, nil
}
type Event struct { type Event struct {
bun.BaseModel `bun:"table:events"` bun.BaseModel `bun:"table:events"`
@@ -103,12 +140,18 @@ func InitDatabase(dsn DSN) (*bun.DB, error) {
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn.ToString()))) sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn.ToString())))
db := bun.NewDB(sqldb, pgdialect.New()) db := bun.NewDB(sqldb, pgdialect.New())
ctx := context.Background()
_, err := db.ExecContext(ctx, "CREATE EXTENSION IF NOT EXISTS pgcrypto;")
if err != nil {
return nil, err
}
db.RegisterModel((*EventToUser)(nil)) db.RegisterModel((*EventToUser)(nil))
_, err := db.NewCreateTable().Model((*User)(nil)).IfNotExists().Exec(context.Background()) _, err = db.NewCreateTable().Model((*User)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*Event)(nil)).IfNotExists().Exec(context.Background()) _, err = db.NewCreateTable().Model((*Event)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*EventToUser)(nil)).IfNotExists().Exec(context.Background()) _, err = db.NewCreateTable().Model((*EventToUser)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*Blog)(nil)).IfNotExists().Exec(context.Background()) _, err = db.NewCreateTable().Model((*Blog)(nil)).IfNotExists().Exec(ctx)
_, err = db.NewCreateTable().Model((*WebsiteSettings)(nil)).IfNotExists().Exec(context.Background()) _, err = db.NewCreateTable().Model((*WebsiteSettings)(nil)).IfNotExists().Exec(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }

33
backend/api/get_me.go Normal file
View File

@@ -0,0 +1,33 @@
package api
import (
"net/http"
"fr.latosa-escrima/api/core"
"github.com/golang-jwt/jwt/v5"
)
func HandleGetMe(w http.ResponseWriter, r *http.Request) {
token, ok := r.Context().Value("token").(*jwt.Token)
if !ok {
core.JSONError{
Status: core.Error,
Message: "Couldn't retrieve your JWT.",
}.Respond(w, http.StatusInternalServerError)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
core.JSONError{
Status: core.Error,
Message: "Invalid token claims.",
}.Respond(w, http.StatusInternalServerError)
return
}
uuid := claims["user_id"].(string)
r.SetPathValue("user_uuid", uuid)
HandleGetUser(w, r)
}

View File

@@ -46,6 +46,6 @@ func HandleCreateBlog(w http.ResponseWriter, r *http.Request) {
core.JSONSuccess{ core.JSONSuccess{
Status: core.Success, Status: core.Success,
Message: "Blog inserted", Message: "Blog inserted",
Data: blog, Data: blog,
}.Respond(w, http.StatusCreated) }.Respond(w, http.StatusCreated)
} }

View File

@@ -32,14 +32,15 @@ func HandleCreateUser(w http.ResponseWriter, r *http.Request) {
log.Println(user) log.Println(user)
res, err := core.DB.NewInsert().Model(&user).Exec(context.Background()) res, err := user.Insert(context.Background())
if res == nil { log.Println(res)
core.JSONError{ // if res == nil {
Status: core.Error, // core.JSONError{
Message: "The user couldn't be inserted.", // Status: core.Error,
}.Respond(w, http.StatusNotAcceptable) // Message: "The user couldn't be inserted.",
return // }.Respond(w, http.StatusNotAcceptable)
} // return
// }
if err != nil { if err != nil {
core.JSONError{ core.JSONError{

View File

@@ -49,6 +49,7 @@ func HandleUpdateUser(w http.ResponseWriter, r *http.Request) {
for i := 0; i < val.NumField(); i++ { for i := 0; i < val.NumField(); i++ {
field := val.Field(i) field := val.Field(i)
fieldname := typ.Field(i).Name
tag := typ.Field(i).Tag.Get("bun") tag := typ.Field(i).Tag.Get("bun")
if tag == "" { if tag == "" {
@@ -57,7 +58,11 @@ func HandleUpdateUser(w http.ResponseWriter, r *http.Request) {
// Only add fields that are non-nil and non-zero // Only add fields that are non-nil and non-zero
if field.IsValid() && !field.IsNil() && !field.IsZero() { if field.IsValid() && !field.IsNil() && !field.IsZero() {
updateQuery.Set(fmt.Sprintf("%s = ?", strings.Split(tag, ",")[0]), field.Interface()) if fieldname == "Password" {
updateQuery.Set(fmt.Sprintf("%s = crypt(?, gen_salt('bf'))", strings.Split(tag, ",")[0]), field.Interface())
} else {
updateQuery.Set(fmt.Sprintf("%s = ?", strings.Split(tag, ",")[0]), field.Interface())
}
} }
} }

View File

@@ -13,9 +13,13 @@ require (
) )
require ( require (
github.com/fatih/color v1.18.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/puzpuzpuz/xsync/v3 v3.4.0 // indirect github.com/puzpuzpuz/xsync/v3 v3.4.0 // indirect
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect
github.com/uptrace/bun/extra/bundebug v1.2.8 // indirect
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
golang.org/x/crypto v0.31.0 // indirect golang.org/x/crypto v0.31.0 // indirect

View File

@@ -1,5 +1,7 @@
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/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
@@ -12,6 +14,11 @@ github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
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.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
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/puzpuzpuz/xsync/v3 v3.4.0 h1:DuVBAdXuGFHv8adVXjWWZ63pJq+NRXOWVXlKDBZ+mJ4= github.com/puzpuzpuz/xsync/v3 v3.4.0 h1:DuVBAdXuGFHv8adVXjWWZ63pJq+NRXOWVXlKDBZ+mJ4=
@@ -26,12 +33,16 @@ github.com/uptrace/bun/dialect/pgdialect v1.2.8 h1:9n3qVh6yc+u7F3lpXzsWrAFJG1yLH
github.com/uptrace/bun/dialect/pgdialect v1.2.8/go.mod h1:plksD43MjAlPGYLD9/SzsLUpGH5poXE9IB1+ka/sEzE= github.com/uptrace/bun/dialect/pgdialect v1.2.8/go.mod h1:plksD43MjAlPGYLD9/SzsLUpGH5poXE9IB1+ka/sEzE=
github.com/uptrace/bun/driver/pgdriver v1.2.8 h1:5XrNn/9enSrWhhrUpz+6PY9S1vcg/jhCQPJu+ZmsKX4= github.com/uptrace/bun/driver/pgdriver v1.2.8 h1:5XrNn/9enSrWhhrUpz+6PY9S1vcg/jhCQPJu+ZmsKX4=
github.com/uptrace/bun/driver/pgdriver v1.2.8/go.mod h1:cwRRwqabgePwYBiLlXtbeNmPD7LGJnqP21J2ZKP4ah8= github.com/uptrace/bun/driver/pgdriver v1.2.8/go.mod h1:cwRRwqabgePwYBiLlXtbeNmPD7LGJnqP21J2ZKP4ah8=
github.com/uptrace/bun/extra/bundebug v1.2.8 h1:Epv0ycLOnoKWPky+rufP2F/PrcSlKkd4tmVIFOdq90A=
github.com/uptrace/bun/extra/bundebug v1.2.8/go.mod h1:ucnmuPw/5ePbNFj2SPmV0lQh3ZvL+3HCrpvRxIYZyWQ=
github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8= github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
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.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View File

@@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"github.com/joho/godotenv" "github.com/joho/godotenv"
"github.com/uptrace/bun/extra/bundebug"
"log" "log"
"net/http" "net/http"
"os" "os"
@@ -16,6 +17,21 @@ import (
func handler(w http.ResponseWriter, r *http.Request) { func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<html><body><h1>Hello, World!</h1></body></html>") fmt.Fprintf(w, "<html><body><h1>Hello, World!</h1></body></html>")
} }
func Cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Allow all origins (can restrict to specific origins)
w.Header().Set("Access-Control-Allow-Origin", "*")
// Allow certain HTTP methods (you can customize these as needed)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
// Allow certain headers (you can add more as needed)
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Handle OPTIONS pre-flight request
if r.Method == http.MethodOptions {
return
}
next.ServeHTTP(w, r)
})
}
func main() { func main() {
err := godotenv.Load() err := godotenv.Load()
@@ -23,6 +39,7 @@ func main() {
log.Fatalf("Error loading .env file: %v", err) log.Fatalf("Error loading .env file: %v", err)
} }
environ := os.Getenv("ENVIRONMENT") environ := os.Getenv("ENVIRONMENT")
port := os.Getenv("BACKEND_DOCKER_PORT") port := os.Getenv("BACKEND_DOCKER_PORT")
if environ == "DEV" { if environ == "DEV" {
port = os.Getenv("BACKEND_PORT") port = os.Getenv("BACKEND_PORT")
@@ -41,15 +58,22 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
core.DB.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))
defer core.DB.Close()
mux := http.NewServeMux() mux := http.NewServeMux()
core.HandleRoutes(mux, map[string]core.Handler{ core.HandleRoutes(mux, map[string]core.Handler{
"/": { "/": {
Handler: handler, Handler: handler,
Middlewares: []core.Middleware{api.Methods("post")}}, Middlewares: []core.Middleware{api.Methods("get")}},
"/users/login": { "/users/login": {
Handler: api.HandleLogin, Handler: api.HandleLogin,
Middlewares: []core.Middleware{api.Methods("POST")}}, Middlewares: []core.Middleware{api.Methods("POST")}},
"/users/me": {
Handler: api.HandleGetMe,
Middlewares: []core.Middleware{api.Methods("GET"), api.AuthJWT}},
"/users": { "/users": {
Handler: api.HandleGetUsers, Handler: api.HandleGetUsers,
Middlewares: []core.Middleware{api.Methods("GET"), api.AuthJWT}}, Middlewares: []core.Middleware{api.Methods("GET"), api.AuthJWT}},
@@ -76,7 +100,7 @@ func main() {
}) })
fmt.Printf("Serving on port %s\n", port) fmt.Printf("Serving on port %s\n", port)
err = http.ListenAndServe(fmt.Sprintf(":%s", port), mux) err = http.ListenAndServe(fmt.Sprintf(":%s", port), Cors(mux))
if err != nil { if err != nil {
fmt.Printf("Error starting server: %s\n", err) fmt.Printf("Error starting server: %s\n", err)
} }

View File

@@ -1,8 +1,15 @@
import { GalleryVerticalEnd } from "lucide-react"; import Image from "next/image";
import { LoginForm } from "@/components/login-form"; import { LoginForm } from "@/components/login-form";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
export default async function LoginPage() {
const cookiesObj = await cookies();
const token = cookiesObj.get("auth_token")?.value;
if (token) redirect("/dashboard");
export default function LoginPage() {
return ( return (
<div className="grid min-h-svh lg:grid-cols-2"> <div className="grid min-h-svh lg:grid-cols-2">
<div className="flex flex-col gap-4 p-6 md:p-10"> <div className="flex flex-col gap-4 p-6 md:p-10">
@@ -13,7 +20,9 @@ export default function LoginPage() {
</div> </div>
</div> </div>
<div className="relative hidden bg-muted lg:block"> <div className="relative hidden bg-muted lg:block">
<img <Image
width={20}
height={20}
src="/placeholder.svg" src="/placeholder.svg"
alt="Image" alt="Image"
className="absolute inset-0 h-full w-full object-cover dark:brightness-[0.2] dark:grayscale" className="absolute inset-0 h-full w-full object-cover dark:brightness-[0.2] dark:grayscale"

View File

@@ -1,7 +1,7 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google"; import { Geist, Geist_Mono } from "next/font/google";
import "@/app/globals.css"; import "@/app/globals.css";
import { SWRConfig } from "swr"; import SWRLayout from "@/components/layouts/swr-layout";
const geistSans = Geist({ const geistSans = Geist({
variable: "--font-geist-sans", variable: "--font-geist-sans",
@@ -24,19 +24,12 @@ export default function RootLayout({
children: React.ReactNode; children: React.ReactNode;
}>) { }>) {
return ( return (
//<SWRConfig <html lang="fr">
// value={{ <body
// fetcher: (url: string) => fetch(url).then((res) => res.json()), className={`${geistSans.variable} ${geistMono.variable} antialiased`}
// revalidateOnFocus: false, >
// }} <SWRLayout>{children}</SWRLayout>
//> </body>
<html lang="fr"> </html>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
//</SWRConfig>
); );
} }

View File

@@ -10,6 +10,7 @@ import {
GalleryVerticalEnd, GalleryVerticalEnd,
Settings2, Settings2,
Calendar, Calendar,
Loader2,
} from "lucide-react"; } from "lucide-react";
import { NavMain } from "@/components/nav-main"; import { NavMain } from "@/components/nav-main";
@@ -23,6 +24,8 @@ import {
SidebarHeader, SidebarHeader,
SidebarRail, SidebarRail,
} from "@/components/ui/sidebar"; } from "@/components/ui/sidebar";
import useMe from "@/hooks/use-me";
import { useEffect } from "react";
// This is sample data. // This is sample data.
const data = { const data = {
@@ -93,6 +96,8 @@ const data = {
}; };
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) { export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const { user, isLoading, success, error } = useMe();
return ( return (
<Sidebar collapsible="icon" {...props}> <Sidebar collapsible="icon" {...props}>
<SidebarHeader> <SidebarHeader>
@@ -102,7 +107,11 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
<NavMain items={data.navMain} /> <NavMain items={data.navMain} />
</SidebarContent> </SidebarContent>
<SidebarFooter> <SidebarFooter>
<NavUser user={data.user} /> {isLoading ? (
<Loader2 className="flex w-full min-w-0 flex-col gap-1 justify-center animate-spin" />
) : (
<NavUser user={user!} />
)}
</SidebarFooter> </SidebarFooter>
<SidebarRail /> <SidebarRail />
</Sidebar> </Sidebar>

View File

@@ -0,0 +1,27 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Hammed Abass. <3 All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
"use client";
import { SWRConfig } from "swr";
interface SWRLayoutProps {
children: React.ReactNode;
}
const SWRLayout: React.FC<SWRLayoutProps> = ({ children }) => (
<SWRConfig
value={{
fetcher: (url: string) =>
fetch(url, { credentials: "include" }).then((res) =>
res.json(),
),
revalidateOnFocus: false,
}}
>
{children}
</SWRConfig>
);
export default SWRLayout;

View File

@@ -1,14 +1,39 @@
"use client";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { useState } from "react";
import { useRouter } from "next/navigation";
import useLogin from "@/hooks/use-login";
import { Loader2 } from "lucide-react";
export function LoginForm({ export function LoginForm({
className, className,
...props ...props
}: React.ComponentPropsWithoutRef<"form">) { }: React.ComponentPropsWithoutRef<"form">) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { login, loading, isSuccess } = useLogin();
const router = useRouter();
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
try {
const res = await login({ email, password });
if (res.status === "Success") router.push("/dashboard");
console.log(res);
} catch (err: any) {
console.log(err.message);
}
};
return ( return (
<form className={cn("flex flex-col gap-6", className)} {...props}> <form
onSubmit={handleSubmit}
className={cn("flex flex-col gap-6", className)}
{...props}
>
<div className="flex flex-col items-center gap-2 text-center"> <div className="flex flex-col items-center gap-2 text-center">
<h1 className="text-2xl font-bold"> <h1 className="text-2xl font-bold">
Connectez-vous à votre compte. Connectez-vous à votre compte.
@@ -23,6 +48,9 @@ export function LoginForm({
<Input <Input
id="email" id="email"
type="email" type="email"
value={email}
disabled={loading}
onChange={(e) => setEmail(e.currentTarget.value)}
placeholder="m@example.com" placeholder="m@example.com"
required required
/> />
@@ -37,9 +65,21 @@ export function LoginForm({
Forgot your password? Forgot your password?
</a> </a>
</div> </div>
<Input id="password" type="password" required /> <Input
value={password}
onChange={(e) => setPassword(e.currentTarget.value)}
disabled={loading}
id="password"
type="password"
required
/>
</div> </div>
<Button type="submit" className="w-full"> <Button
disabled={loading}
type="submit"
className="w-full transition-all ease-in-out"
>
{loading && <Loader2 className="animate-spin" />}
Se connecter Se connecter
</Button> </Button>
<div className="relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t after:border-border"> <div className="relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t after:border-border">

View File

@@ -68,7 +68,7 @@ const subMenuItemsTwo = [
const Navbar = () => { const Navbar = () => {
return ( return (
<section className="p-4 bg-white top-0 sticky z-[100]"> <section className="p-4 bg-white top-0 sticky z-50">
<div> <div>
<nav className="hidden justify-between lg:flex"> <nav className="hidden justify-between lg:flex">
<div className="flex items-center gap-6"> <div className="flex items-center gap-6">
@@ -103,7 +103,8 @@ const Navbar = () => {
variant: "ghost", variant: "ghost",
}), }),
)} )}
href="/"> href="/"
>
Planning Planning
</a> </a>
<a <a

View File

@@ -25,17 +25,16 @@ import {
SidebarMenuItem, SidebarMenuItem,
useSidebar, useSidebar,
} from "@/components/ui/sidebar"; } from "@/components/ui/sidebar";
import { deleteCookie } from "cookies-next";
import { useRouter } from "next/navigation";
import IUser from "@/interfaces/IUser";
export function NavUser({ export const NavUser: React.FC<{ user: IUser }> = ({ user }) => {
user,
}: {
user: {
name: string;
email: string;
avatar: string;
};
}) {
const { isMobile } = useSidebar(); const { isMobile } = useSidebar();
const router = useRouter();
const name = `${user.firstname} ${user.lastname}`;
const image = `https://avatar.vercel.sh/${name}`;
return ( return (
<SidebarMenu> <SidebarMenu>
@@ -47,17 +46,14 @@ export function NavUser({
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground" className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
> >
<Avatar className="h-8 w-8 rounded-lg"> <Avatar className="h-8 w-8 rounded-lg">
<AvatarImage <AvatarImage src={image} alt={name} />
src={user.avatar}
alt={user.name}
/>
<AvatarFallback className="rounded-lg"> <AvatarFallback className="rounded-lg">
CN CN
</AvatarFallback> </AvatarFallback>
</Avatar> </Avatar>
<div className="grid flex-1 text-left text-sm leading-tight"> <div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-semibold"> <span className="truncate font-semibold">
{user.name} {name}
</span> </span>
<span className="truncate text-xs"> <span className="truncate text-xs">
{user.email} {user.email}
@@ -75,17 +71,14 @@ export function NavUser({
<DropdownMenuLabel className="p-0 font-normal"> <DropdownMenuLabel className="p-0 font-normal">
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm"> <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
<Avatar className="h-8 w-8 rounded-lg"> <Avatar className="h-8 w-8 rounded-lg">
<AvatarImage <AvatarImage src={image} alt={name} />
src={user.avatar}
alt={user.name}
/>
<AvatarFallback className="rounded-lg"> <AvatarFallback className="rounded-lg">
CN CN
</AvatarFallback> </AvatarFallback>
</Avatar> </Avatar>
<div className="grid flex-1 text-left text-sm leading-tight"> <div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-semibold"> <span className="truncate font-semibold">
{user.name} {name}
</span> </span>
<span className="truncate text-xs"> <span className="truncate text-xs">
{user.email} {user.email}
@@ -116,7 +109,12 @@ export function NavUser({
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuGroup> </DropdownMenuGroup>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem> <DropdownMenuItem
onClick={async () => {
await deleteCookie("auth_token");
router.push("/");
}}
>
<LogOut /> <LogOut />
Log out Log out
</DropdownMenuItem> </DropdownMenuItem>
@@ -125,4 +123,4 @@ export function NavUser({
</SidebarMenuItem> </SidebarMenuItem>
</SidebarMenu> </SidebarMenu>
); );
} };

109
frontend/hooks/use-api.tsx Normal file
View File

@@ -0,0 +1,109 @@
"use client";
import { API_URL } from "@/lib/constants";
import { getCookie } from "cookies-next";
import useSWR, { SWRConfiguration } from "swr";
import useSWRMutation, { type SWRMutationConfiguration } from "swr/mutation";
export interface ApiResponse<T> {
status: "Error" | "Success";
message: string;
data?: T;
}
async function request<T>(
url: string,
options: {
method?: "GET" | "POST" | "PATCH" | "DELETE";
body?: any;
requiresAuth?: boolean;
} = {},
): Promise<ApiResponse<T>> {
const { method = "GET", body, requiresAuth = true } = options;
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (requiresAuth) {
const authToken = getCookie("auth_token");
if (!authToken) {
throw new Error("User is not authenticated");
}
headers.Authorization = `Bearer ${authToken}`;
}
const response = await fetch(`${API_URL}${url}`, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
});
const apiResponse: ApiResponse<T> = await response.json();
if (apiResponse.status === "Error") {
throw new Error(apiResponse.message || "An unexpected error occurred");
}
return apiResponse;
}
async function fetcher<T>(
url: string,
requiresAuth: boolean = true,
): Promise<ApiResponse<T>> {
return request(url, { requiresAuth });
}
async function mutationHandler<T, A>(
url: string,
{
arg,
method,
requiresAuth,
}: {
arg: A;
method: "GET" | "POST" | "PATCH" | "DELETE";
requiresAuth: boolean;
},
): Promise<ApiResponse<T>> {
return request(url, { method, body: arg, requiresAuth });
}
export function useApi<T>(
url: string,
config?: SWRConfiguration,
requiresAuth: boolean = true,
) {
const swr = useSWR<ApiResponse<T>>(
url,
() => fetcher(url, requiresAuth),
config,
);
return {
...swr,
data: swr.data?.data,
isLoading: swr.isLoading || swr.isValidating,
success: swr.data?.status === "Success",
};
}
export default function useApiMutation<T, A>(
endpoint: string,
config?: SWRMutationConfiguration<ApiResponse<T>, Error, string, A>,
method: "GET" | "POST" | "PATCH" | "DELETE" = "GET",
requiresAuth: boolean = false,
) {
const mutation = useSWRMutation<ApiResponse<T>, Error, string, A>(
endpoint,
(url, { arg }) => mutationHandler(url, { arg, method, requiresAuth }),
config,
);
return {
...mutation,
trigger: mutation.trigger as (
arg: A,
) => Promise<ApiResponse<T> | undefined>,
data: mutation.data?.data,
isSuccess: mutation.data?.status === "Success",
};
}

View File

@@ -0,0 +1,31 @@
"use client";
import { setCookie } from "cookies-next";
import useApiMutation from "./use-api";
export interface LoginArgs {
email: string;
password: string;
}
export default function useLogin() {
const {
trigger,
isMutating: loading,
isSuccess,
} = useApiMutation<string, LoginArgs>("/users/login", undefined, "POST");
const login = async (inputs: LoginArgs) => {
try {
const res = await trigger(inputs);
if (!res) throw new Error("The server hasn't responded.");
if (res.status === "Error") throw new Error(res.message);
if (res.data) setCookie("auth_token", res.data);
return res;
} catch (error: any) {
throw new Error(error.message);
}
};
return { login, loading, isSuccess };
}

16
frontend/hooks/use-me.tsx Normal file
View File

@@ -0,0 +1,16 @@
"use client";
import IUser from "@/interfaces/IUser";
import { useApi } from "./use-api";
export default function useMe() {
const {
data: user,
isLoading,
mutate,
error,
success,
} = useApi<IUser>("/users/me", undefined, true);
return { user, isLoading, success, error, mutate };
}

View File

@@ -0,0 +1,10 @@
export default interface IUser {
userId: string;
firstname: string;
lastname: string;
email: string;
phone: string;
role: string;
createdAt: Date;
updatedAt: Date;
}

View File

@@ -0,0 +1 @@
export const API_URL = `http://localhost:${process.env.NEXT_PUBLIC_BACKEND_PORT}`;

43
frontend/middleware.ts Normal file
View File

@@ -0,0 +1,43 @@
import { NextRequest, NextResponse } from "next/server";
import { ApiResponse } from "./hooks/use-api";
import { API_URL } from "./lib/constants";
import IUser from "./interfaces/IUser";
export async function middleware(request: NextRequest) {
const sessionCookie = request.cookies.get("auth_token")?.value;
if (!sessionCookie) {
return NextResponse.redirect(
new URL(
`/login?redirectTo=${encodeURIComponent(request.url)}`,
request.url,
),
);
}
try {
const res = await fetch(`${API_URL}/users/me`, {
headers: { Authorization: `Bearer ${sessionCookie}` },
});
const js: ApiResponse<IUser> = await res.json();
if (js.status === "Error")
return NextResponse.redirect(
new URL(
`/login?redirectTo=${encodeURIComponent(request.url)}`,
request.url,
),
);
} catch (e: any) {
return NextResponse.redirect(
new URL(
`/login?redirectTo=${encodeURIComponent(request.url)}`,
request.url,
),
);
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};

View File

@@ -3,19 +3,16 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
/* config options here */ /* config options here */
output: "standalone", output: "standalone",
async redirects() { images: {
if (!process.env.BACKEND_PORT) { remotePatterns: [
throw new Error(
"Environment variable BACKEND_PORT is not defined.",
);
}
return [
{ {
source: "/api/:path", protocol: "https",
destination: `http://localhost:${process.env.BACKEND_PORT}/:path`, hostname: "avatar.vercel.sh",
permanent: false,
}, },
]; ],
},
env: {
NEXT_PUBLIC_BACKEND_PORT: process.env.BACKEND_PORT,
}, },
}; };

View File

@@ -22,6 +22,7 @@
"@radix-ui/react-tooltip": "^1.1.6", "@radix-ui/react-tooltip": "^1.1.6",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cookies-next": "^5.1.0",
"embla-carousel-react": "^8.5.2", "embla-carousel-react": "^8.5.2",
"lucide-react": "^0.471.1", "lucide-react": "^0.471.1",
"next": "15.1.4", "next": "15.1.4",
@@ -2734,6 +2735,28 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/cookie": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz",
"integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/cookies-next": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/cookies-next/-/cookies-next-5.1.0.tgz",
"integrity": "sha512-9Ekne+q8hfziJtnT9c1yDUBqT0eDMGgPrfPl4bpR3xwQHLTd/8gbSf6+IEkP/pjGsDZt1TGbC6emYmFYRbIXwQ==",
"license": "MIT",
"dependencies": {
"cookie": "^1.0.1"
},
"peerDependencies": {
"next": ">=15.0.0",
"react": ">= 16.8.0"
}
},
"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",

View File

@@ -23,6 +23,7 @@
"@radix-ui/react-tooltip": "^1.1.6", "@radix-ui/react-tooltip": "^1.1.6",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cookies-next": "^5.1.0",
"embla-carousel-react": "^8.5.2", "embla-carousel-react": "^8.5.2",
"lucide-react": "^0.471.1", "lucide-react": "^0.471.1",
"next": "15.1.4", "next": "15.1.4",

View File

@@ -8,12 +8,4 @@ server {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
} }
location /api {
proxy_pass http://localhost:BACKEND_PORT; # Set backend port based on what you have exposed
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
} }