Reorganize project structure and fix SQLite usage

This commit is contained in:
bronku 2025-03-23 10:45:42 +01:00
parent 0e762841a3
commit e2dda0ade7
20 changed files with 76 additions and 46 deletions

78
internal/auth/auth.go Normal file
View file

@ -0,0 +1,78 @@
package auth
import (
_ "embed"
"fmt"
"net/http"
"time"
)
//go:embed login.html
var loginPage string
//go:embed wrongPassword.html
var wrongPassword string
type Authenticator struct {
sessions map[string]token
}
func New() *Authenticator {
return &Authenticator{sessions: make(map[string]token)}
}
func (a *Authenticator) login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("content-type", "text/html")
fmt.Fprint(w, loginPage)
return
}
err := r.ParseForm()
if err != nil {
w.Header().Set("content-type", "text/html")
fmt.Fprint(w, loginPage)
return
}
login := r.PostFormValue("login")
password := r.PostFormValue("password")
if login != "admin" || password != "secret" {
w.Header().Set("content-type", "text/html")
fmt.Fprint(w, wrongPassword)
return
}
key := generateKey()
a.sessions[key] = token{userName: login, created: time.Now(), lastAccess: time.Now()}
c := http.Cookie{
Name: "token",
Value: key,
HttpOnly: true,
// #todo (in prod) uncomment this line
//Secure: true,
SameSite: http.SameSiteStrictMode,
Path: "/",
}
http.SetCookie(w, &c)
http.Redirect(w, r, "/", http.StatusFound)
}
func (a *Authenticator) Middleware(in http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.String() == "/login" {
a.login(w, r)
return
}
c, err := r.Cookie("token")
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
value, ok := a.sessions[c.Value]
if !ok || time.Since(value.lastAccess) > time.Hour*24 || time.Since(value.lastAccess) > time.Hour*240 {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
value.lastAccess = time.Now()
a.sessions[c.Value] = value
in.ServeHTTP(w, r)
})
}

12
internal/auth/login.html Normal file
View file

@ -0,0 +1,12 @@
<header>
<h1>Login</h1>
</header>
<main>
<form method="post">
<label>Login</label>
<input type="text" name="login" />
<label>Password</label>
<input type="password" name="password" />
<button type="submit">login</button>
</form>
</main>

19
internal/auth/token.go Normal file
View file

@ -0,0 +1,19 @@
package auth
import (
"crypto/rand"
"encoding/base64"
"time"
)
type token struct {
userName string
created time.Time
lastAccess time.Time
}
func generateKey() string {
key := [32]byte{}
rand.Read(key[:])
return base64.StdEncoding.EncodeToString(key[:])
}

View file

@ -0,0 +1,12 @@
<header>
<h1>Wrong Password</h1>
</header>
<main>
<form method="post">
<label>Login</label>
<input type="text" name="login" />
<label>Password</label>
<input type="password" name="password" />
<button type="submit">login</button>
</form>
</main>