fix: token reload

This commit is contained in:
Rogee
2024-12-15 01:19:03 +08:00
parent ed3d8b0e6c
commit 4a606bd824
9 changed files with 62 additions and 23 deletions

1
backend/map.json Executable file
View File

@@ -0,0 +1 @@
[]

View File

@@ -95,12 +95,8 @@ func (d *DiscoverMedias) processVideo(video, to, hash string) (media_store.Video
return info, errors.Wrapf(err, "ensure directory: %s", to) return info, errors.Wrapf(err, "ensure directory: %s", to)
} }
if err := d.ensureDirectory(filepath.Join(to, "posters")); err != nil {
return info, errors.Wrapf(err, "ensure directory: %s", to)
}
// extract poster // extract poster
posterFile := filepath.Join(to, "posters", hash+".jpg") posterFile := filepath.Join(to, hash+".jpg")
if err := d.ffmpegVideoToPoster(video, posterFile); err != nil { if err := d.ffmpegVideoToPoster(video, posterFile); err != nil {
return info, errors.Wrapf(err, "ffmpeg video to poster: %s", posterFile) return info, errors.Wrapf(err, "ffmpeg video to poster: %s", posterFile)
} }
@@ -269,6 +265,10 @@ func (d *DiscoverMedias) runCleanup(to string) {
if err := os.RemoveAll(filepath.Join(to, dir)); err != nil { if err := os.RemoveAll(filepath.Join(to, dir)); err != nil {
d.log.Errorf("Remove dir: %s", dir) d.log.Errorf("Remove dir: %s", dir)
} }
if err := os.RemoveAll(filepath.Join(to, dir+".jpg")); err != nil {
d.log.Errorf("Remove poster: %s", dir+".jpg")
}
} }
} }

View File

@@ -2,6 +2,8 @@ package store
import ( import (
"context" "context"
"fmt"
"path/filepath"
"backend/modules/medias" "backend/modules/medias"
"backend/pkg/media_store" "backend/pkg/media_store"
@@ -25,13 +27,16 @@ func (d *StoreMedias) Prepare() error {
func (d *StoreMedias) RunE(targetPath string) error { func (d *StoreMedias) RunE(targetPath string) error {
d.log.Infof("Store medias from: %s ", targetPath) d.log.Infof("Store medias from: %s ", targetPath)
tenantId := int64(1)
targetPath = filepath.Join(targetPath, fmt.Sprintf("%d", tenantId))
store, err := media_store.NewStore(targetPath) store, err := media_store.NewStore(targetPath)
if err != nil { if err != nil {
return errors.Wrapf(err, "new store: %s", targetPath) return errors.Wrapf(err, "store: %s", targetPath)
} }
for _, item := range store { for _, item := range store {
err := d.mediasSvc.Upsert(context.Background(), 1, item) err := d.mediasSvc.Upsert(context.Background(), tenantId, item)
if err != nil { if err != nil {
d.log.WithError(err).Errorf("upsert media: %s - %s", item.Hash, item.Name) d.log.WithError(err).Errorf("upsert media: %s - %s", item.Hash, item.Name)
} }

View File

@@ -213,16 +213,17 @@ func (svc *Service) HasUserBought(ctx context.Context, tenantId, userId, mediaId
func (svc *Service) Upsert(ctx context.Context, tenantId int64, item media_store.VideoInfo) error { func (svc *Service) Upsert(ctx context.Context, tenantId int64, item media_store.VideoInfo) error {
log := svc.log.WithField("method", "Upsert") log := svc.log.WithField("method", "Upsert")
tenantIdStr := fmt.Sprintf("%d", tenantId)
resources := pg.MediaResources{} resources := pg.MediaResources{}
if path.DirExists(filepath.Join(svc.storageConfig.Path, item.Hash, pg.MediaTypeVideo.String())) { if path.DirExists(filepath.Join(svc.storageConfig.Path, tenantIdStr, item.Hash, pg.MediaTypeVideo.String())) {
resources = append(resources, pg.MediaTypeVideo) resources = append(resources, pg.MediaTypeVideo)
} }
if path.DirExists(filepath.Join(svc.storageConfig.Path, item.Hash, pg.MediaTypeAudio.String())) { if path.DirExists(filepath.Join(svc.storageConfig.Path, tenantIdStr, item.Hash, pg.MediaTypeAudio.String())) {
resources = append(resources, pg.MediaTypeAudio) resources = append(resources, pg.MediaTypeAudio)
} }
if path.DirExists(filepath.Join(svc.storageConfig.Path, item.Hash, pg.MediaTypePdf.String())) { if path.DirExists(filepath.Join(svc.storageConfig.Path, tenantIdStr, item.Hash, pg.MediaTypePdf.String())) {
resources = append(resources, pg.MediaTypePdf) resources = append(resources, pg.MediaTypePdf)
} }

View File

@@ -16,7 +16,7 @@ func (f *Middlewares) ParseJWT(c fiber.Ctx) error {
token := tokens[0] token := tokens[0]
claim, err := f.jwt.Parse(token) claim, err := f.jwt.Parse(token)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to parse token") return errors.Wrapf(err, "failed to parse token: %s", token)
} }
// query user // query user

View File

@@ -1,7 +1,9 @@
package middlewares package middlewares
import ( import (
"fmt"
"strings" "strings"
"time"
"backend/providers/wechat" "backend/providers/wechat"
@@ -10,11 +12,26 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
const StatePrefix = "sns_basic_auth"
func (f *Middlewares) WeChatAuth(c fiber.Ctx) error { func (f *Middlewares) WeChatAuth(c fiber.Ctx) error {
log.WithField("module", "middleware.AuthUserInfo").Debugf("%s, query: %v", c.OriginalURL(), c.Queries()) log := log.WithField("module", "middleware.AuthUserInfo")
log.Debugf("%s, query: %v", c.OriginalURL(), c.Queries())
state := c.Query("state") state := c.Query("state")
code := c.Query("code") code := c.Query("code")
log.WithField("module", "middleware.AuthUserInfo").Debugf("code: %s, state: %s", code, state) log.Debugf("code: %s, state: %s", code, state)
jwtToken := c.Cookies("token")
if jwtToken != "" {
log.Debugf("jwtToken: %s", jwtToken)
if _, err := f.jwt.Parse(jwtToken); err != nil {
log.WithError(err).Error("failed to parse jwt token")
c.ClearCookie("token")
return c.Redirect().To(c.Path())
}
}
if state == "" && code == "" { if state == "" && code == "" {
url := string(c.Request().URI().FullURI()) url := string(c.Request().URI().FullURI())
@@ -27,7 +44,7 @@ func (f *Middlewares) WeChatAuth(c fiber.Ctx) error {
to, err := f.client.ScopeAuthorizeURL( to, err := f.client.ScopeAuthorizeURL(
wechat.ScopeAuthorizeURLWithRedirectURI(url), wechat.ScopeAuthorizeURLWithRedirectURI(url),
wechat.ScopeAuthorizeURLWithState("sns_basic_auth"), wechat.ScopeAuthorizeURLWithState(fmt.Sprintf("%s_%d", StatePrefix, time.Now().UnixNano())),
) )
if err != nil { if err != nil {
return errors.Wrap(err, "failed to get wechat auth url") return errors.Wrap(err, "failed to get wechat auth url")
@@ -38,7 +55,7 @@ func (f *Middlewares) WeChatAuth(c fiber.Ctx) error {
} }
if state != "sns_basic_auth" || code == "" { if !strings.HasPrefix(state, StatePrefix) || code == "" {
return errors.New("invalid request") return errors.New("invalid request")
} }

View File

@@ -26,6 +26,18 @@ type Controller struct {
} }
func (c *Controller) Render(ctx fiber.Ctx) error { 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") code := ctx.Query("code")
// get the openid // get the openid
@@ -58,18 +70,17 @@ func (c *Controller) Render(ctx fiber.Ctx) error {
UserID: user.ID, UserID: user.ID,
TenantID: tenant.ID, TenantID: tenant.ID,
}) })
jwtToken, err := c.jwt.CreateToken(claim) jwtToken, err = c.jwt.CreateToken(claim)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to create token") return errors.Wrap(err, "failed to create token")
} }
b, err := os.ReadFile(filepath.Join(c.storagePath.Asset, "index.html")) ctx.Cookie(&fiber.Cookie{
if err != nil { Name: "token",
return errors.Wrap(err, "failed to read file") Value: jwtToken,
} HTTPOnly: true,
})
html := strings.ReplaceAll(string(b), "{{JWT}}", jwtToken) html := strings.ReplaceAll(string(b), "{{JWT}}", jwtToken)
ctx.Set("Content-Type", "text/html")
return ctx.SendString(html) return ctx.SendString(html)
} }

View File

@@ -85,7 +85,6 @@ func Serve(cmd *cobra.Command, args []string) error {
return c.SendFile(filepath.Join( return c.SendFile(filepath.Join(
http.Storage.Path, http.Storage.Path,
tenant, tenant,
"posters",
hash+".jpg", hash+".jpg",
)) ))
}) })

View File

@@ -1,6 +1,8 @@
package tasks package tasks
import ( import (
"errors"
"backend/modules/commands/discover" "backend/modules/commands/discover"
"backend/modules/commands/store" "backend/modules/commands/store"
"backend/modules/medias" "backend/modules/medias"
@@ -56,6 +58,9 @@ func Command() atom.Option {
atom.RunE(func(cmd *cobra.Command, args []string) error { atom.RunE(func(cmd *cobra.Command, args []string) error {
return container.Container.Invoke(func(task *store.StoreMedias) error { return container.Container.Invoke(func(task *store.StoreMedias) error {
from := cmd.Flag("from").Value.String() from := cmd.Flag("from").Value.String()
if from == "" {
return errors.New("from is empty")
}
return task.RunE(from) return task.RunE(from)
}) })
}), }),