47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
package hwsauth
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.haelnorr.com/h/golib/jwt"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
// Login authenticates a user and sets JWT tokens as HTTP-only cookies.
|
|
// The rememberMe parameter determines token expiration behavior.
|
|
//
|
|
// Parameters:
|
|
// - w: HTTP response writer for setting cookies
|
|
// - r: HTTP request
|
|
// - model: The authenticated user model
|
|
// - rememberMe: If true, tokens have extended expiry; if false, session-based
|
|
//
|
|
// Example:
|
|
//
|
|
// func loginHandler(w http.ResponseWriter, r *http.Request) {
|
|
// user, err := validateCredentials(username, password)
|
|
// if err != nil {
|
|
// http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
|
// return
|
|
// }
|
|
// err = auth.Login(w, r, user, true)
|
|
// if err != nil {
|
|
// http.Error(w, "Login failed", http.StatusInternalServerError)
|
|
// return
|
|
// }
|
|
// http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
|
|
// }
|
|
func (auth *Authenticator[T, TX]) Login(
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
model T,
|
|
rememberMe bool,
|
|
) error {
|
|
|
|
err := jwt.SetTokenCookies(w, r, auth.tokenGenerator, model.GetID(), true, rememberMe, auth.SSL)
|
|
if err != nil {
|
|
return errors.Wrap(err, "jwt.SetTokenCookies")
|
|
}
|
|
return nil
|
|
}
|