From 56efbfa472c5c0185da2c5c1f0b6e7665ea87d36 Mon Sep 17 00:00:00 2001 From: Axel Berardino Date: Mon, 12 Aug 2019 01:43:08 +0200 Subject: [PATCH] Remove hardcoded passwords and use an external password file for the server part --- .gitignore | 1 + README | 1 - cmd/server/main.go | 56 +++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 002c335..bedbebc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ poe-stash data/*.html data/cache/* +pass.txt diff --git a/README b/README index 7a92766..5f6b055 100644 --- a/README +++ b/README @@ -10,5 +10,4 @@ go get -u github.com/gin-gonic/gin TODO More rigourous item description generation Shop id for the link after shop generation - Don't hardcode account passwords! Search bar? diff --git a/cmd/server/main.go b/cmd/server/main.go index bcbcf9c..941a00a 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -1,9 +1,13 @@ package main import ( + "bufio" "flag" "fmt" "html/template" + "io" + "os" + "strings" "github.com/gin-gonic/gin" @@ -13,7 +17,7 @@ import ( ) // setupRouter setups the http server and all its pages. -func setupRouter() *gin.Engine { +func setupRouter(passwords map[string]string) *gin.Engine { router := gin.Default() t := template.Must(generate.LoadAllTemplates()) @@ -24,21 +28,61 @@ func setupRouter() *gin.Engine { router.GET("/", page.MainPageHandler) router.GET("/view/:account", page.ViewAccountHandler) - authorized := router.Group("/", gin.BasicAuth(gin.Accounts{ - "***": "***", - "****": "****", - })) + authorized := router.Group("/", gin.BasicAuth(passwords)) authorized.GET("/gen/:account", page.GenAccountHandler) return router } +// loadPasswords load passwords from a given file. +// Format is: +// login:pass +// login:pass +// login:pass +// ... +func loadPasswords(filename string) (r map[string]string, mainErr error) { + res := make(map[string]string, 2) + file, err := os.Open(filename) + if err != nil { + return nil, err + } + defer func() { + err := file.Close() + if err == nil { + mainErr = err + } + }() + + reader := bufio.NewReader(file) + for { + line, _, err := reader.ReadLine() + if err == io.EOF { + break + } + parts := strings.Split(string(line), ":") + // Invalid line is skipped + if len(parts) != 2 { + fmt.Println("Skipped invalid line:", string(line)) + } else { + res[parts[0]] = parts[1] + } + } + + return res, nil +} + // main is the main routine which launch the http server. // This server allows to generate and view account characters, // stash and items for given users. func main() { port := flag.Int("port", 2121, "port") + passwordFile := flag.String("passwords", "./pass.txt", "password file (containing login:pass in plain text)") flag.Parse() - r := setupRouter() + + passwords, err := loadPasswords(*passwordFile) + if err != nil { + panic(err) + } + r := setupRouter(passwords) r.Run(fmt.Sprintf(":%d", *port)) }