go-twitch/auth/state_storage.go

45 lines
848 B
Go

package auth
import (
"net/http"
)
type StateStorage interface {
Get(r *http.Request) (string, error)
Save(w http.ResponseWriter, code string) error
}
const (
StateStorageCookie = "state"
)
type HttpCookieStateStorage struct {
cookieName string
}
func NewHttpCookieStateStorage(cookieName string) *HttpCookieStateStorage {
return &HttpCookieStateStorage{
cookieName: cookieName,
}
}
var _ StateStorage = (*HttpCookieStateStorage)(nil)
func (s *HttpCookieStateStorage) Get(r *http.Request) (string, error) {
code, err := r.Cookie(s.cookieName)
if err != nil {
return "", err
}
if err := code.Valid(); err != nil {
return "", err
}
return code.Value, nil
}
func (s *HttpCookieStateStorage) Save(w http.ResponseWriter, state string) error {
http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: state})
return nil
}