go-twitch/auth/callback.go

67 lines
1.3 KiB
Go
Raw Normal View History

2024-03-04 18:14:38 -05:00
package auth
import (
"fmt"
"net/http"
)
type CallbackHandler struct {
client *Client
handler TokenHandler
}
var _ http.Handler = (*CallbackHandler)(nil)
// CallbackHandler returns an http.Handler that handles callback responses
// from the twitch authentication server.
func (c *Client) CallbackHandler(h TokenHandler) http.Handler {
return &CallbackHandler{
client: c,
handler: h,
}
}
// ServeHTTP implements http.Handler.
func (c *CallbackHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
state := q.Get("state")
if state == "" {
http.Error(w, "state is empty", http.StatusBadRequest)
return
}
storedState, err := c.client.stateStorage.Get(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if state != storedState {
http.Error(w, "state mismatch", http.StatusBadRequest)
return
}
if q.Has("error") {
err := q.Get("error")
desc := q.Get("error_description")
errMsg := fmt.Sprintf("%s: %s", err, desc)
http.Error(w, errMsg, http.StatusBadRequest)
return
}
code := q.Get("code")
scope := q.Get("scope")
_ = scope
2024-03-08 13:05:54 -05:00
token, err := c.client.GetToken(r.Context(), code)
2024-03-04 18:14:38 -05:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
c.handler.Handle(state, token.AccessToken)
}