Added skeleton for basic admin auth system

This commit is contained in:
2026-05-16 17:01:34 +02:00
parent d5c4cfa9d0
commit 4d53a6b471
9 changed files with 179 additions and 12 deletions
+21
View File
@@ -0,0 +1,21 @@
package auth
import (
"golang.org/x/crypto/bcrypt"
)
func HashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hash), nil
}
func CheckPassword(hash, password string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
}
func NeedsSetup(adminUser string) bool {
return adminUser == ""
}
+2 -2
View File
@@ -18,7 +18,7 @@ type Config struct {
func Load(path string) Config { func Load(path string) Config {
configData := Config{ configData := Config{
SiteName: "Unnamed Download Listing", SiteName: "Unnamed Download Listing",
Port: "8080", Port: ":8080",
DataDir: "data", DataDir: "data",
} }
@@ -46,7 +46,7 @@ func Save(path string, configData Config) error {
if configData.AdminUser != "" { if configData.AdminUser != "" {
file.WriteString("admin_user = \"" + configData.AdminUser + "\"\n") file.WriteString("admin_user = \"" + configData.AdminUser + "\"\n")
file.WriteString("admin_password_hash = \"" + configData.AdminPasswordHash + "\"\n") file.WriteString("admin_password_hash = \"" + configData.AdminPasswordHash + "\"\n")
file.WriteString("# This admin_password_hash above is a hashed password, not your actual\"") file.WriteString("# This admin_password_hash above is a hashed password, not your actual\n")
file.WriteString("# written password. You can't change your admin password here.\n") file.WriteString("# written password. You can't change your admin password here.\n")
file.WriteString("# If you've lost your password, delete admin_user and admin_hash\n") file.WriteString("# If you've lost your password, delete admin_user and admin_hash\n")
file.WriteString("# from this file and restart the app to create a new account.\n") file.WriteString("# from this file and restart the app to create a new account.\n")
BIN
View File
Binary file not shown.
+5 -2
View File
@@ -2,6 +2,9 @@ module 192.168.1.180/odonax/filehost-athome
go 1.26.2 go 1.26.2
require github.com/mattn/go-sqlite3 v1.14.44 require (
github.com/mattn/go-sqlite3 v1.14.44
golang.org/x/crypto v0.51.0
)
require github.com/BurntSushi/toml v1.6.0 // indirect require github.com/BurntSushi/toml v1.6.0
+2
View File
@@ -2,3 +2,5 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/mattn/go-sqlite3 v1.14.44 h1:3VSe+xafpbzsLbdr2AWlAZk9yRHiBhTBakioXaCKTF8= github.com/mattn/go-sqlite3 v1.14.44 h1:3VSe+xafpbzsLbdr2AWlAZk9yRHiBhTBakioXaCKTF8=
github.com/mattn/go-sqlite3 v1.14.44/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ= github.com/mattn/go-sqlite3 v1.14.44/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ=
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
+80
View File
@@ -0,0 +1,80 @@
package handlers
import (
"html/template"
"net/http"
"192.168.1.180/odonax/filehost-athome/auth"
"192.168.1.180/odonax/filehost-athome/config"
)
var Cfg *config.Config
var CfgPath string
func Setup(tmpl *template.Template) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !auth.NeedsSetup(Cfg.AdminUser) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
if r.Method == "GET" {
tmpl.Execute(w, nil)
return
}
username := r.FormValue("username")
password := r.FormValue("password")
confirm := r.FormValue("confirm")
if username == "" || password == "" {
tmpl.Execute(w, map[string]string{"Error": "Please fill in all fields."})
return
}
if password != confirm {
tmpl.Execute(w, map[string]string{"Error": "Passwords do not match."})
return
}
hash, err := auth.HashPassword(password)
if err != nil {
tmpl.Execute(w, map[string]string{"Error": "Something went wrong. Refresh the page and try again. If the issue persists, contact the developer of this application and tell them what happened."})
return
}
Cfg.AdminUser = username
Cfg.AdminPasswordHash = hash
config.Save(CfgPath, *Cfg)
http.Redirect(w, r, "/admin", http.StatusSeeOther)
}
}
func Login(tmpl *template.Template) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if auth.NeedsSetup(Cfg.AdminUser) {
http.Redirect(w, r, "/setup", http.StatusSeeOther)
return
}
if r.Method == "GET" {
tmpl.Execute(w, map[string]string{"SiteName": Cfg.SiteName})
return
}
username := r.FormValue("username")
password := r.FormValue("password")
if username != Cfg.AdminUser || !auth.CheckPassword(Cfg.AdminPasswordHash, password) {
tmpl.Execute(w, map[string]string{
"SiteName": Cfg.SiteName,
"Error": "Invalid credentials.",
})
return
}
// TODO: create a session so the admin stays logged in
http.Redirect(w, r, "/admin", http.StatusSeeOther)
}
}
+18 -8
View File
@@ -8,29 +8,39 @@ import (
"192.168.1.180/odonax/filehost-athome/config" "192.168.1.180/odonax/filehost-athome/config"
"192.168.1.180/odonax/filehost-athome/database" "192.168.1.180/odonax/filehost-athome/database"
"192.168.1.180/odonax/filehost-athome/handlers"
) )
func main() { func main() {
cfg := config.Load("config.toml") cfgPath := "config.toml"
cfg := config.Load(cfgPath)
handlers.Cfg = &cfg
handlers.CfgPath = cfgPath
os.MkdirAll(cfg.DataDir+"/files", 0755) os.MkdirAll(cfg.DataDir+"/files", 0755)
db := database.Open(cfg.DataDir+"/hub.db") db := database.Open(cfg.DataDir+"/hub.db")
defer db.Close() defer db.Close()
tmpl, err := template.ParseFiles("templates/home.html") tmpl := template.Must(template.ParseGlob("templates/*.html"))
if err != nil {
log.Fatal("Failed to load template:", err) // tmpl, err := template.ParseFiles("templates/home.html")
} // if err != nil {
// log.Fatal("Failed to load template:", err)
// }
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
data := map[string]string{ data := map[string]string{
"Name": cfg.SiteName, "Name": cfg.SiteName,
"Description": "This is where you'll own your files and share them freely.", "Description": "This is where you'll own your files and share them freely.",
} }
tmpl.Execute(w, data) tmpl.ExecuteTemplate(w, "home.html", data)
}) })
log.Println("Starting filehost on :8080") http.HandleFunc("/setup", handlers.Setup(tmpl.Lookup("setup.html")))
log.Fatal(http.ListenAndServe(":8080", nil)) http.HandleFunc("/login", handlers.Login(tmpl.Lookup("login.html")))
log.Printf("Starting filehost on %s\n", cfg.Port)
log.Fatal(http.ListenAndServe(cfg.Port, nil))
} }
+23
View File
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Log in - {{ .SiteName }}</title>
</head>
<body>
<h1>Log in</h1>
{{ if .Error }}
<p><strong>{{ .Error }}</strong></p>
{{ end }}
<form method="POST" action="/login">
<label for="username">Username</label>
<input type="text" id="username" name="username" required>
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<button type="submit">Log in</button>
</form>
</body>
</html>
+28
View File
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set up your filehost</title>
</head>
<body>
<h1>Welcome! It's time to get you set up.</h1>
<p>Create your admin account to start managing your site. Consider picking a username different than 'admin' or your standard internet alias to make it harder for people to guess your admin credentials.</p>
<p>If you ever lose your credentials or your admin account is compromised, you can reset it by editing the 'config.toml' file and removing the credentials there. You can then recreate your admin account without losing your listings.</p>
{{ if .Error }}
<p><strong>{{ .Error }}</strong></p>
{{ end }}
<form method="POST" action="/setup">
<label for="username">Username</label>
<input type="text" id="username" name="username" required>
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<label for="confirm">Confirm password</label>
<input type="password" id="confirm" name="confirm" required>
<button type="submit">Create account</button>
</form>
</body>
</html>