45 lines
885 B
Go
45 lines
885 B
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gorilla/sessions"
|
|
)
|
|
|
|
var store = sessions.NewCookieStore([]byte("super-secret-key")) // ToDo: Make global
|
|
|
|
func init() {
|
|
store.Options = &sessions.Options{
|
|
Path: "/",
|
|
MaxAge: 86400 * 1,
|
|
HttpOnly: true,
|
|
Secure: true,
|
|
SameSite: http.SameSiteStrictMode,
|
|
}
|
|
}
|
|
|
|
func GetSession(w http.ResponseWriter, r *http.Request) (*sessions.Session, error) {
|
|
return store.Get(r, "session-name")
|
|
}
|
|
|
|
func GetCurrentUserID(r *http.Request) (int, bool) {
|
|
session, err := GetSession(nil, r)
|
|
if err != nil {
|
|
return 0, false
|
|
}
|
|
|
|
id, ok := session.Values["user_id"].(int)
|
|
return id, ok
|
|
}
|
|
|
|
func RequireAuth(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
_, ok := GetCurrentUserID(r)
|
|
if !ok {
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
next(w, r)
|
|
}
|
|
}
|