feat: complete
This commit is contained in:
75
backend/modules/wechat/controller.go
Normal file
75
backend/modules/wechat/controller.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"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 {
|
||||
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")
|
||||
}
|
||||
|
||||
b, err := os.ReadFile(filepath.Join(c.storagePath.Asset, "index.html"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to read file")
|
||||
}
|
||||
|
||||
html := strings.ReplaceAll(string(b), "{{JWT}}", jwtToken)
|
||||
|
||||
ctx.Set("Content-Type", "text/html")
|
||||
return ctx.SendString(html)
|
||||
}
|
||||
Reference in New Issue
Block a user