woj-server/internal/api/oauth/login.go

37 lines
940 B
Go
Raw Normal View History

2024-01-03 00:55:41 +08:00
package oauth
import (
"context"
"fmt"
2024-01-03 00:55:41 +08:00
"git.0x7f.app/WOJ/woj-server/internal/e"
"git.0x7f.app/WOJ/woj-server/pkg/utils"
"github.com/gin-gonic/gin"
"net/http"
)
// LoginHandler
// @Summary Login with OAuth2
// @Description Get OAuth2 Login URL
// @Tags oauth
// @Produce json
// @Response 200 {object} e.Response[string] "random string"
// @Router /oauth/login [post]
2024-01-05 00:57:43 +08:00
func (h *handler) LoginHandler() gin.HandlerFunc {
2024-01-03 00:55:41 +08:00
return func(c *gin.Context) {
state := utils.RandomString(64)
key := utils.RandomString(16)
2024-01-05 00:57:43 +08:00
err := h.cache.Get().Set(context.Background(), fmt.Sprintf(oauthStateKey, key), state, oauthStateLiveness).Err()
if err != nil {
e.Pong[any](c, e.RedisError, nil)
return
}
2024-01-03 00:55:41 +08:00
c.SetSameSite(http.SameSiteStrictMode)
2024-01-05 00:57:43 +08:00
c.SetCookie(oauthStateCookieName, key, int(oauthStateLiveness.Seconds()), "/", "", false, true)
2024-01-03 00:55:41 +08:00
2024-01-05 00:57:43 +08:00
url := h.conf.AuthCodeURL(state)
2024-01-03 00:55:41 +08:00
e.Pong(c, e.Success, url)
}
}