Implemented Authentication

+ Basic Authentication
This commit is contained in:
Daniel Legt 2024-01-21 18:40:40 +02:00
parent 07dec16aa4
commit cbe252fe94
4 changed files with 29 additions and 1 deletions

View File

@ -13,6 +13,8 @@ type DHConfig struct {
MaxHistoryAge int `json:"maxHistoryAge"` MaxHistoryAge int `json:"maxHistoryAge"`
DatabaseFilePath string DatabaseFilePath string
Listen string Listen string
IdentityUsername string
IdentityPassword string
} }
func GetConfiguration() DHConfig { func GetConfiguration() DHConfig {
@ -25,6 +27,8 @@ func GetConfiguration() DHConfig {
DiskFetchFrequency: 5, // default value DiskFetchFrequency: 5, // default value
MaxHistoryAge: 2592000, // default value MaxHistoryAge: 2592000, // default value
DatabaseFilePath: "./data.sqlite", DatabaseFilePath: "./data.sqlite",
IdentityUsername: "admin",
IdentityPassword: "admin",
Listen: ":8080", Listen: ":8080",
} }
@ -49,5 +53,13 @@ func GetConfiguration() DHConfig {
config.DatabaseFilePath = val config.DatabaseFilePath = val
} }
if val, exists := os.LookupEnv("IDENTITY_USERNAME"); exists {
config.IdentityUsername = val
}
if val, exists := os.LookupEnv("IDENTITY_PASSWORD"); exists {
config.IdentityPassword = val
}
return config return config
} }

View File

@ -0,0 +1,11 @@
package web
import "github.com/gin-gonic/gin"
func BasicAuthMiddleware(username, password string) gin.HandlerFunc {
authorized := gin.Accounts{
username: password,
}
return gin.BasicAuth(authorized)
}

View File

@ -2,12 +2,16 @@ package web
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"tea.chunkbyte.com/kato/drive-health/lib/config"
) )
func SetupRouter() *gin.Engine { func SetupRouter() *gin.Engine {
// Initialize the Gin engine // Initialize the Gin engine
cfg := config.GetConfiguration()
r := gin.Default() r := gin.Default()
r.Use(BasicAuthMiddleware(cfg.IdentityUsername, cfg.IdentityPassword))
// Setup Health Pings // Setup Health Pings
setupHealth(r) setupHealth(r)
// Setup Api // Setup Api

View File

@ -17,11 +17,12 @@ import (
func main() { func main() {
// Init the database // Init the database
svc.InitDB() svc.InitDB()
cfg := config.GetConfiguration()
router := web.SetupRouter() router := web.SetupRouter()
srv := &http.Server{ srv := &http.Server{
Addr: config.GetConfiguration().Listen, Addr: cfg.Listen,
Handler: router, Handler: router,
} }