89 lines
2.0 KiB
Go
89 lines
2.0 KiB
Go
package users
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"backend/modules/users"
|
|
"backend/pkg/pg"
|
|
"backend/providers/jwt"
|
|
"backend/providers/storage"
|
|
"backend/providers/wechat"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/jinzhu/copier"
|
|
"github.com/pkg/errors"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// @provider
|
|
type Controller struct {
|
|
jwt *jwt.JWT
|
|
storagePath *storage.Config
|
|
userSvc *users.Service
|
|
client *wechat.Client
|
|
}
|
|
|
|
func (c *Controller) Render(ctx fiber.Ctx) error {
|
|
jwtToken := ctx.Cookies("token")
|
|
ctx.Set("Content-Type", "text/html")
|
|
b, err := os.ReadFile(filepath.Join(c.storagePath.Asset, "index.html"))
|
|
if err != nil {
|
|
return errors.Wrap(err, "failed to read file")
|
|
}
|
|
|
|
if jwtToken != "" {
|
|
html := strings.ReplaceAll(string(b), "{{JWT}}", jwtToken)
|
|
return ctx.SendString(html)
|
|
}
|
|
|
|
code := ctx.Query("code")
|
|
|
|
// get the openid
|
|
token, err := c.client.AuthorizeCode2Token(code)
|
|
if err != nil {
|
|
return errors.Wrap(err, "failed to get openid")
|
|
}
|
|
log.Debugf("tokenInfo %+v", token)
|
|
|
|
tenantSlug := ctx.Params("tenant")
|
|
tenant, err := c.userSvc.GetTenantBySlug(ctx.Context(), tenantSlug)
|
|
if err != nil {
|
|
return errors.Wrap(err, "failed to get tenant id")
|
|
}
|
|
|
|
var oauthInfo pg.UserOAuth
|
|
if err := copier.Copy(&oauthInfo, token); err != nil {
|
|
return errors.Wrap(err, "failed to copy oauth info")
|
|
}
|
|
log.Debugf("oauthInfo %+v", oauthInfo)
|
|
|
|
user, err := c.userSvc.GetOrNew(ctx.Context(), tenant.ID, token.Openid, oauthInfo)
|
|
if err != nil {
|
|
return errors.Wrap(err, "failed to get user")
|
|
}
|
|
|
|
claim := c.jwt.CreateClaims(jwt.BaseClaims{
|
|
OpenID: user.OpenID,
|
|
Tenant: tenantSlug,
|
|
UserID: user.ID,
|
|
TenantID: tenant.ID,
|
|
})
|
|
jwtToken, err = c.jwt.CreateToken(claim)
|
|
if err != nil {
|
|
return errors.Wrap(err, "failed to create token")
|
|
}
|
|
|
|
ctx.Cookie(&fiber.Cookie{
|
|
Name: "token",
|
|
Value: jwtToken,
|
|
Expires: time.Now().Add(6 * time.Hour),
|
|
HTTPOnly: true,
|
|
})
|
|
|
|
html := strings.ReplaceAll(string(b), "{{JWT}}", jwtToken)
|
|
return ctx.SendString(html)
|
|
}
|