2021-03-09 12:56:53 +00:00
|
|
|
package oauth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"gopkg.in/oauth2.v3/errors"
|
|
|
|
"gopkg.in/oauth2.v3/manage"
|
|
|
|
"gopkg.in/oauth2.v3/server"
|
|
|
|
"gopkg.in/oauth2.v3/store"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
var srv *server.Server
|
|
|
|
|
|
|
|
func InitOAuth() {
|
|
|
|
manager := manage.NewDefaultManager()
|
|
|
|
// token store
|
|
|
|
manager.MustTokenStorage(store.NewMemoryTokenStore())
|
|
|
|
|
2021-03-19 18:10:13 +00:00
|
|
|
// create new secretstore
|
|
|
|
clientStore := NewCustomStore()
|
|
|
|
manager.MapClientStorage(clientStore)
|
2021-03-09 12:56:53 +00:00
|
|
|
|
|
|
|
srv = server.NewServer(server.NewConfig(), manager)
|
|
|
|
srv.SetClientInfoHandler(server.ClientFormHandler)
|
|
|
|
manager.SetRefreshTokenCfg(manage.DefaultRefreshTokenCfg)
|
|
|
|
|
|
|
|
srv.SetInternalErrorHandler(func(err error) (re *errors.Response) {
|
|
|
|
log.Println("Internal Error:", err.Error())
|
|
|
|
return
|
|
|
|
})
|
|
|
|
|
|
|
|
srv.SetResponseErrorHandler(func(re *errors.Response) {
|
|
|
|
log.Println("Response Error:", re.Error.Error())
|
|
|
|
})
|
|
|
|
|
|
|
|
http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
err := srv.HandleAuthorizeRequest(w, r)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
err := srv.HandleTokenRequest(w, r)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-04-16 20:44:56 +00:00
|
|
|
func ValidateToken(f func(rw http.ResponseWriter, req *http.Request, node int), node int) http.HandlerFunc {
|
2021-03-09 12:56:53 +00:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
_, err := srv.ValidationBearerToken(r)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-04-16 20:44:56 +00:00
|
|
|
f(w, r, node)
|
2021-03-09 12:56:53 +00:00
|
|
|
}
|
|
|
|
}
|