58 lines
1.5 KiB
Go
58 lines
1.5 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
|
|
"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.
|
|
// SESSION_COOKIE_DOMAIN (optional) shares the session across subdomains,
|
|
// e.g. ".where-woof.com" so apex + www both see the login.
|
|
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
|
|
}
|
|
if d := os.Getenv("SESSION_COOKIE_DOMAIN"); d != "" {
|
|
Store.Options.Domain = d
|
|
}
|
|
}
|
|
|
|
// 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)
|
|
}
|