79 lines
1.7 KiB
Go
79 lines
1.7 KiB
Go
package middlewares
|
||
|
||
import (
|
||
"net/url"
|
||
"strings"
|
||
|
||
"quyun/v2/app/services"
|
||
"quyun/v2/pkg/utils"
|
||
|
||
"github.com/gofiber/fiber/v3"
|
||
log "github.com/sirupsen/logrus"
|
||
)
|
||
|
||
func (f *Middlewares) AuthFrontend(ctx fiber.Ctx) error {
|
||
if strings.HasPrefix(ctx.Path(), "/v1/auth/") {
|
||
return ctx.Next()
|
||
}
|
||
|
||
if ctx.Path() == "/v1/posts" {
|
||
return ctx.Next()
|
||
}
|
||
if strings.HasPrefix(ctx.Path(), "/v1/posts/") && strings.HasSuffix(ctx.Path(), "show") {
|
||
return ctx.Next()
|
||
}
|
||
if strings.HasPrefix(ctx.Path(), "/v1/posts/") && strings.HasSuffix(ctx.Path(), "play") {
|
||
return ctx.Next()
|
||
}
|
||
|
||
if f.app.IsDevMode() && false {
|
||
user, err := services.Users.FindByID(ctx.Context(), 1001)
|
||
if err != nil {
|
||
return ctx.Send([]byte("User not found"))
|
||
}
|
||
ctx.Locals("user", user)
|
||
return ctx.Next()
|
||
}
|
||
|
||
fullUrl := utils.FullURI(ctx)
|
||
u, err := url.Parse(fullUrl)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
query := u.Query()
|
||
query.Set("redirect", fullUrl)
|
||
u.RawQuery = query.Encode()
|
||
u.Path = "/v1/auth/phone"
|
||
fullUrl = u.String()
|
||
|
||
// 仅使用 Header 的 Bearer Token(前端 localStorage 存储,随请求透传)。
|
||
token := ctx.Get("Authorization")
|
||
if token == "" {
|
||
log.Infof("auth redirect_uri: %s", fullUrl)
|
||
if ctx.XHR() {
|
||
return ctx.SendStatus(fiber.StatusUnauthorized)
|
||
}
|
||
return ctx.Redirect().To(fullUrl)
|
||
}
|
||
|
||
jwt, err := f.jwt.Parse(token)
|
||
if err != nil {
|
||
if ctx.XHR() {
|
||
return ctx.SendStatus(fiber.StatusUnauthorized)
|
||
}
|
||
return ctx.Redirect().To(fullUrl)
|
||
}
|
||
|
||
user, err := services.Users.FindByID(ctx.Context(), jwt.UserID)
|
||
if err != nil {
|
||
if ctx.XHR() {
|
||
return ctx.SendStatus(fiber.StatusUnauthorized)
|
||
}
|
||
return ctx.Redirect().To(fullUrl)
|
||
}
|
||
|
||
ctx.Locals("user", user)
|
||
|
||
return ctx.Next()
|
||
}
|