48 lines
1.3 KiB
Go
48 lines
1.3 KiB
Go
package hwsauth
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.haelnorr.com/h/golib/cookies"
|
|
"git.haelnorr.com/h/golib/jwt"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
// Logout revokes the user's authentication tokens and clears their cookies.
|
|
// This operation requires a database transaction to revoke tokens.
|
|
//
|
|
// Parameters:
|
|
// - tx: Database transaction for revoking tokens
|
|
// - w: HTTP response writer for clearing cookies
|
|
// - r: HTTP request containing the tokens to revoke
|
|
//
|
|
// Example:
|
|
//
|
|
// func logoutHandler(w http.ResponseWriter, r *http.Request) {
|
|
// tx, _ := db.BeginTx(r.Context(), nil)
|
|
// defer tx.Rollback()
|
|
// if err := auth.Logout(tx, w, r); err != nil {
|
|
// http.Error(w, "Logout failed", http.StatusInternalServerError)
|
|
// return
|
|
// }
|
|
// tx.Commit()
|
|
// http.Redirect(w, r, "/", http.StatusSeeOther)
|
|
// }
|
|
func (auth *Authenticator[T, TX]) Logout(tx TX, w http.ResponseWriter, r *http.Request) error {
|
|
aT, rT, err := auth.getTokens(tx, r)
|
|
if err != nil {
|
|
return errors.Wrap(err, "auth.getTokens")
|
|
}
|
|
err = aT.Revoke(jwt.DBTransaction(tx))
|
|
if err != nil {
|
|
return errors.Wrap(err, "aT.Revoke")
|
|
}
|
|
err = rT.Revoke(jwt.DBTransaction(tx))
|
|
if err != nil {
|
|
return errors.Wrap(err, "rT.Revoke")
|
|
}
|
|
cookies.DeleteCookie(w, "access", "/")
|
|
cookies.DeleteCookie(w, "refresh", "/")
|
|
return nil
|
|
}
|