Added skeleton for basic admin auth system
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user