62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
package router
|
|
|
|
import (
|
|
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/neo-f/soda"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func RegisterAuthRouter(app *soda.Soda) {
|
|
app.Get("/auth/sign-in", GetSignInURL).
|
|
AddTags("Auth").
|
|
SetSummary("登录").
|
|
SetParameters(OauthSchema{}).
|
|
OK()
|
|
|
|
app.Get("/auth/callback", TokenCallback).
|
|
AddTags("Auth").
|
|
SetSummary("Oauth回调地址").
|
|
SetParameters(OauthSchema{}).
|
|
OK()
|
|
}
|
|
|
|
type OauthSchema struct {
|
|
Code string `query:"code"`
|
|
State string `query:"state"`
|
|
}
|
|
|
|
func TokenCallback(c *fiber.Ctx) error {
|
|
k := c.Locals(soda.KeyParameter).(*OauthSchema)
|
|
token, err := casdoorsdk.GetOAuthToken(k.Code, k.State)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.JSON(token)
|
|
}
|
|
|
|
func GetSignInURL(c *fiber.Ctx) error {
|
|
url := casdoorsdk.GetSigninUrl("http://localhost:8080/auth/callback")
|
|
return c.Redirect(url)
|
|
}
|
|
|
|
var userKey = struct{}{}
|
|
|
|
func JWTRequired(c *fiber.Ctx) error {
|
|
jwt := c.Get("Authorization")
|
|
if jwt == "" {
|
|
return fiber.ErrUnauthorized
|
|
}
|
|
claims, err := casdoorsdk.ParseJwtToken(jwt[7:])
|
|
if err != nil {
|
|
log.Ctx(c.UserContext()).Error().Err(err).Msg("Unauthorized user")
|
|
return fiber.ErrUnauthorized
|
|
}
|
|
c.Locals(userKey, &claims.User)
|
|
return nil
|
|
}
|
|
|
|
func getAuth(c *fiber.Ctx) *casdoorsdk.User {
|
|
return c.Locals(userKey).(*casdoorsdk.User)
|
|
}
|