frontend-foundation: GOAT front-end Phase 1 — auth, tag management, public tag page (22/22 spec scenarios pass)
This commit is contained in:
18
frontend/internal/auth/passwords.go
Normal file
18
frontend/internal/auth/passwords.go
Normal file
@@ -0,0 +1,18 @@
|
||||
// Package auth provides password hashing and session handling for WhereWoof.
|
||||
package auth
|
||||
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
|
||||
// HashPassword returns a bcrypt hash of the given plaintext password.
|
||||
func HashPassword(password string) (string, error) {
|
||||
b, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// CheckPassword reports whether the plaintext password matches the bcrypt hash.
|
||||
func CheckPassword(hash, password string) bool {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
||||
}
|
||||
51
frontend/internal/auth/session.go
Normal file
51
frontend/internal/auth/session.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
)
|
||||
|
||||
// SessionName is the cookie name for authenticated sessions.
|
||||
const SessionName = "ww_session"
|
||||
|
||||
// Store is the signed + encrypted cookie store, initialised by InitSessionStore.
|
||||
var Store *sessions.CookieStore
|
||||
|
||||
// InitSessionStore creates the cookie store with the server secret.
|
||||
func InitSessionStore(secret string) {
|
||||
Store = sessions.NewCookieStore([]byte(secret))
|
||||
Store.Options = &sessions.Options{
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: 30 * 24 * 3600, // 30 days
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserID returns the authenticated user id from the request, if any.
|
||||
func GetUserID(r *http.Request) (int64, bool) {
|
||||
if Store == nil {
|
||||
return 0, false
|
||||
}
|
||||
s, err := Store.Get(r, SessionName)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
id, ok := s.Values["user_id"].(int64)
|
||||
return id, ok
|
||||
}
|
||||
|
||||
// SetUserID records the user id in the session cookie.
|
||||
func SetUserID(w http.ResponseWriter, r *http.Request, id int64) error {
|
||||
s, _ := Store.Get(r, SessionName)
|
||||
s.Values["user_id"] = id
|
||||
return s.Save(r, w)
|
||||
}
|
||||
|
||||
// Clear destroys the session (logout).
|
||||
func Clear(w http.ResponseWriter, r *http.Request) error {
|
||||
s, _ := Store.Get(r, SessionName)
|
||||
s.Options.MaxAge = -1
|
||||
return s.Save(r, w)
|
||||
}
|
||||
Reference in New Issue
Block a user