package oauthapi import ( "crypto/rand" "crypto/rsa" "net/http" "time" "git.keks.cloud/kekskurse/miniauth/pkg/miniauth" "github.com/gin-gonic/gin" "github.com/ory/fosite" "github.com/ory/fosite/compose" "github.com/ory/fosite/storage" "github.com/rs/zerolog" "github.com/rs/zerolog/log" ) type OauthAPIConf struct{} type OAuthAPI struct { config OauthAPIConf ma miniauth.Miniauth log zerolog.Logger oauth fosite.OAuth2Provider } func NewOauthAPI(config OauthAPIConf, ma miniauth.Miniauth) OAuthAPI { w := OAuthAPI{} w.config = config w.ma = ma l := log.With().Str("pkg", "oauthapi").Logger() w.log = l storage := storage.NewExampleStore() secret := []byte("my super secret signing password") privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { w.log.Fatal().Err(err).Msg("cant create privatekey") } oconfig := &fosite.Config{ AccessTokenLifespan: time.Minute * 30, GlobalSecret: secret, } oauth2Provider := compose.ComposeAllEnabled(oconfig, storage, privateKey) w.oauth = oauth2Provider return w } func (w OAuthAPI) RegisterRoutes(routing *gin.RouterGroup) error { routing.GET("/auth", w.authGet) routing.POST("/auth", w.authPost) routing.POST("/token", w.token) return nil } func (w OAuthAPI) authGet(ctx *gin.Context) { ar, err := w.oauth.NewAuthorizeRequest(ctx, ctx.Request) if err != nil { log.Error().Err(err).Msg("cant create authorize request") w.oauth.WriteAuthorizeError(ctx, ctx.Writer, ar, err) return } w.log.Debug().Interface("ar", err).Msg("AuthorizeRequest") ctx.HTML(http.StatusOK, "login.html", nil) } func (w OAuthAPI) authPost(ctx *gin.Context) { ar, err := w.oauth.NewAuthorizeRequest(ctx, ctx.Request) if err != nil { log.Error().Err(err).Msg("cant create authorize request") w.oauth.WriteAuthorizeError(ctx, ctx.Writer, ar, err) return } mySessionData := &fosite.DefaultSession{ Username: ctx.PostForm("username"), } response, err := w.oauth.NewAuthorizeResponse(ctx.Request.Context(), ar, mySessionData) if err != nil { log.Error().Err(err).Msg("cant create response") w.oauth.WriteAuthorizeError(ctx, ctx.Writer, ar, err) return } w.oauth.WriteAuthorizeResponse(ctx, ctx.Writer, ar, response) } func (w OAuthAPI) token(ctx *gin.Context) { mySessionData := new(fosite.DefaultSession) accessRequest, err := w.oauth.NewAccessRequest(ctx, ctx.Request, mySessionData) if err != nil { w.oauth.WriteAccessError(ctx.Request.Context(), ctx.Writer, accessRequest, err) return } response, err := w.oauth.NewAccessResponse(ctx, accessRequest) if err != nil { w.oauth.WriteAccessError(ctx, ctx.Writer, accessRequest, err) return } w.oauth.WriteAccessResponse(ctx, ctx.Writer, accessRequest, response) }