Login

This commit is contained in:
2024-02-02 00:53:22 +08:00
parent 434773976f
commit 19e1775476
15 changed files with 236 additions and 165 deletions

View File

@ -11,19 +11,24 @@ import (
"golang.org/x/oauth2"
)
var cfg = oauth2.Config{
RedirectURL: fmt.Sprintf("https://%s/api/auth/callback", viper.GetString("domain")),
ClientID: viper.GetString("passport.client_id"),
ClientSecret: viper.GetString("passport.client_secret"),
Scopes: []string{"openid"},
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("%s/auth/o/connect", viper.GetString("passport.endpoint")),
TokenURL: fmt.Sprintf("%s/api/auth/token", viper.GetString("passport.endpoint")),
AuthStyle: oauth2.AuthStyleInParams,
},
var cfg oauth2.Config
func buildOauth2Config() {
cfg = oauth2.Config{
RedirectURL: fmt.Sprintf("https://%s/auth/callback", viper.GetString("domain")),
ClientID: viper.GetString("passport.client_id"),
ClientSecret: viper.GetString("passport.client_secret"),
Scopes: []string{"openid"},
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("%s/auth/o/connect", viper.GetString("passport.endpoint")),
TokenURL: fmt.Sprintf("%s/api/auth/token", viper.GetString("passport.endpoint")),
AuthStyle: oauth2.AuthStyleInParams,
},
}
}
func doLogin(c *fiber.Ctx) error {
buildOauth2Config()
url := cfg.AuthCodeURL(uuid.NewString())
return c.JSON(fiber.Map{
@ -32,6 +37,7 @@ func doLogin(c *fiber.Ctx) error {
}
func doPostLogin(c *fiber.Ctx) error {
buildOauth2Config()
code := c.Query("code")
token, err := cfg.Exchange(context.Background(), code)

View File

@ -56,6 +56,8 @@ func NewServer() {
api := A.Group("/api").Name("API")
{
api.Get("/users/me", auth, getUserinfo)
api.Get("/auth", doLogin)
api.Get("/auth/callback", doPostLogin)
api.Post("/auth/refresh", doRefreshToken)

20
pkg/server/users_api.go Normal file
View File

@ -0,0 +1,20 @@
package server
import (
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
"github.com/gofiber/fiber/v2"
)
func getUserinfo(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
var data models.Account
if err := database.C.
Where(&models.Account{BaseModel: models.BaseModel{ID: user.ID}}).
First(&data).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
return c.JSON(data)
}