quartzgun/middleware/middleware.go

53 lines
1.3 KiB
Go

package middleware
import (
"context"
"net/http"
"nilfm.cc/git/quartzgun/auth"
"nilfm.cc/git/quartzgun/cookie"
)
func Protected(next http.Handler, userStore auth.UserStore) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
user, err := cookie.GetToken("user", req)
if err == nil {
session, err := cookie.GetToken("session", req)
if err == nil {
login, err := userStore.ValidateUser(user, session)
if err == nil && login {
next.ServeHTTP(w, req)
return
}
}
}
req.Method = http.MethodGet
http.Redirect(w, req, "/login", http.StatusTemporaryRedirect)
}
return http.HandlerFunc(handlerFunc)
}
func Authorize(next string, userStore auth.UserStore) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
err := auth.Login(
req.FormValue("user"),
req.FormValue("password"),
userStore,
w,
24*7*52)
if err == nil {
req.Method = http.MethodGet
http.Redirect(w, req, next, http.StatusOK)
} else {
*req = *req.WithContext(
context.WithValue(
req.Context(),
"message",
"Incorrect credentials"))
req.Method = http.MethodGet
http.Redirect(w, req, "/login", http.StatusTemporaryRedirect)
}
}
return http.HandlerFunc(handlerFunc)
}