goshort/internal/util/oidc/oidc.go
2024-03-09 04:44:22 -05:00

45 lines
1.0 KiB
Go

package oidcutil
import (
"net/http"
"time"
"git.maronato.dev/maronato/goshort/internal/errs"
oidcservice "git.maronato.dev/maronato/goshort/internal/service/oidc"
)
const (
stateCookieName = "gs_oidc_state"
stateCookieExpiration = time.Minute * 5
)
// SetStateCookie sets the OIDC code parameter as a cookie.
func SetStateCookie(w http.ResponseWriter, r *http.Request, state string) {
c := &http.Cookie{
Name: stateCookieName,
Value: state,
MaxAge: int(stateCookieExpiration.Seconds()),
Secure: r.TLS != nil,
HttpOnly: true,
}
http.SetCookie(w, c)
}
func ValidateRequestState(r *http.Request) error {
state, err := r.Cookie(stateCookieName)
if err != nil {
return errs.ErrOIDCStateCookieMissing
}
if r.URL.Query().Get("state") != state.Value {
return errs.ErrOIDCStateCookieInvalid
}
return nil
}
func DoRedirect(w http.ResponseWriter, r *http.Request, params *oidcservice.RedirectParams) {
SetStateCookie(w, r, params.State)
http.Redirect(w, r, params.URL, http.StatusFound)
}