90 lines
1.9 KiB
Go
90 lines
1.9 KiB
Go
package server
|
|
|
|
import (
|
|
"MiauInv/config"
|
|
"MiauInv/frontend"
|
|
"MiauInv/handlers"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
)
|
|
|
|
type Server struct {
|
|
Port string
|
|
JWTSecret []byte
|
|
DatabasePath string
|
|
CertificatePath string
|
|
PrivateKeyPath string
|
|
}
|
|
|
|
func InitServer() *Server {
|
|
|
|
err := config.CheckIfExists()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
return nil
|
|
}
|
|
|
|
cfg, err := config.LoadConfig()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
return nil
|
|
}
|
|
|
|
jwtSecret := os.Getenv("JWT_SECRET")
|
|
if jwtSecret == "" {
|
|
log.Fatal("JWT_SECRET environment variable not set.")
|
|
return nil
|
|
}
|
|
if len(jwtSecret) < 32 {
|
|
log.Fatal("JWT_SECRET must be at least 32 characters long.")
|
|
return nil
|
|
}
|
|
|
|
return &Server{
|
|
Port: cfg.Port,
|
|
JWTSecret: []byte(jwtSecret),
|
|
DatabasePath: cfg.DatabasePath,
|
|
CertificatePath: cfg.CertificatePath,
|
|
PrivateKeyPath: cfg.PrivateKeyPath,
|
|
}
|
|
}
|
|
|
|
func (this *Server) Run() {
|
|
log.Println("Starting server...")
|
|
mux := http.NewServeMux()
|
|
|
|
//
|
|
// FRONTEND
|
|
//
|
|
mux.HandleFunc("/", frontend.Home)
|
|
mux.HandleFunc("/dashboard", frontend.Dashboard)
|
|
|
|
//
|
|
// API
|
|
//
|
|
|
|
// Public
|
|
mux.HandleFunc("/api/login", handlers.Login)
|
|
mux.HandleFunc("/api/register", handlers.Register)
|
|
mux.HandleFunc("/api/refresh", handlers.RefreshToken)
|
|
mux.HandleFunc("/api/logout", handlers.Logout)
|
|
|
|
mux.HandleFunc("/api/items", handlers.GetItems)
|
|
mux.HandleFunc("/api/items/create", handlers.CreateItem)
|
|
mux.HandleFunc("/api/locations/create", handlers.CreateLocation)
|
|
mux.HandleFunc("/api/projects/create", handlers.CreateProject)
|
|
mux.HandleFunc("/api/stock/add", handlers.AddStock)
|
|
mux.HandleFunc("/api/project-items/add", handlers.AllocateToProject)
|
|
|
|
// Assets
|
|
mux.HandleFunc("/assets/", frontend.Assets)
|
|
|
|
// Login required
|
|
|
|
// Admin-only
|
|
|
|
log.Printf("Listening on port %s", this.Port)
|
|
log.Fatal(http.ListenAndServeTLS(":"+this.Port, this.CertificatePath, this.PrivateKeyPath, mux))
|
|
}
|