62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.haelnorr.com/h/golib/hws"
|
|
"git.haelnorr.com/h/oslstats/internal/config"
|
|
"git.haelnorr.com/h/oslstats/pkg/oauth"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
func Callback(server *hws.Server, cfg *config.Config) http.Handler {
|
|
return http.HandlerFunc(
|
|
func(w http.ResponseWriter, r *http.Request) {
|
|
state := r.URL.Query().Get("state")
|
|
code := r.URL.Query().Get("code")
|
|
if state == "" && code == "" {
|
|
http.Redirect(w, r, "/", http.StatusBadRequest)
|
|
return
|
|
}
|
|
data, err := verifyState(cfg.OAuth, w, r, state)
|
|
if err != nil {
|
|
err = server.ThrowError(w, r, hws.HWSError{
|
|
StatusCode: http.StatusForbidden,
|
|
Message: "OAuth state verification failed",
|
|
Error: err,
|
|
Level: hws.ErrorLevel("debug"),
|
|
RenderErrorPage: true,
|
|
})
|
|
if err != nil {
|
|
server.ThrowFatal(w, err)
|
|
}
|
|
return
|
|
}
|
|
switch data {
|
|
case "login":
|
|
w.Write([]byte(code))
|
|
return
|
|
}
|
|
},
|
|
)
|
|
}
|
|
|
|
func verifyState(cfg *oauth.Config, w http.ResponseWriter, r *http.Request, state string) (string, error) {
|
|
if r == nil {
|
|
return "", errors.New("request cannot be nil")
|
|
}
|
|
if state == "" {
|
|
return "", errors.New("state param field is empty")
|
|
}
|
|
uak, err := oauth.GetStateCookie(r)
|
|
if err != nil {
|
|
return "", errors.Wrap(err, "oauth.GetStateCookie")
|
|
}
|
|
data, err := oauth.VerifyState(cfg, state, uak)
|
|
if err != nil {
|
|
return "", errors.Wrap(err, "oauth.VerifyState")
|
|
}
|
|
oauth.DeleteStateCookie(w)
|
|
return data, nil
|
|
}
|