videoplayer/main.go

115 lines
2.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"io"
"strings"
"videoplayer/dao"
"videoplayer/handler"
"videoplayer/worker"
)
var signingKey = []byte("aadafcvretmoi9")
func main() {
r := gin.Default()
dao.Init()
worker.InitRedis()
r.Use(handler.CrosHandler())
r.Use(JWTAuthMiddleware()) // 使用 JWT 认证中间件
handler.SetUpVideoGroup(r)
handler.SetUpUserGroup(r)
handler.SetUpDeviceGroup(r)
r.Run(":8083") // listen and serve on 0.0.0.0:8082
defer dao.Close()
defer worker.CloseRedis()
}
func writeLogger(c *gin.Context) {
ip := c.ClientIP()
method := c.Request.Method
path := c.Request.URL.Path
params := ""
if method == "GET" {
params = c.Request.URL.RawQuery
}
if method == "POST" {
params = c.Request.PostForm.Encode()
if params == "" {
// 请求体
bodyBytes, _ := io.ReadAll(c.Request.Body)
c.Request.Body = io.NopCloser(strings.NewReader(string(bodyBytes))) // Write body back, so other handler can read it too
params = string(bodyBytes)
}
}
res := dao.InsertLogToDB(path, ip, method, params)
if res == 0 {
fmt.Println("insert log failed")
}
}
func JWTAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
writeLogger(c)
// 从请求头中获取 JWT 令牌
tokenString := c.Request.Header.Get("token")
//请求方式为get时从url中获取token
if tokenString == "" {
tokenString = c.Query("token")
}
//如果请求为login或register则不需要验证token
if strings.Contains(c.Request.URL.Path, "/login") || strings.Contains(c.Request.URL.Path, "/register") || strings.Contains(c.Request.URL.Path, "/uuid") || strings.Contains(c.Request.URL.Path, "/gqr") {
c.Next()
return
}
if tokenString == "" {
//c.AbortWithStatus(200)
c.JSON(200, gin.H{
"message": "Unauthorized",
"error": "token is empty",
"code": "3",
})
return
}
redisToken := worker.GetRedis(tokenString)
if redisToken == "" {
c.AbortWithStatus(200)
c.JSON(200, gin.H{
"message": "NOT_LOGIN",
"error": "server token is empty",
"code": "3",
})
return
}
// 解析 JWT 令牌
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return signingKey, nil
})
// 验证令牌
if err != nil || !token.Valid {
c.AbortWithStatus(200)
c.JSON(200, gin.H{
"message": "NOT_LOGIN",
"error": "Invalid token",
"code": "4",
})
return
}
// 将用户信息添加到上下文中
c.Set("id", token.Claims.(jwt.MapClaims)["id"])
c.Set("username", token.Claims.(jwt.MapClaims)["username"])
// 继续处理请求
c.Next()
}
}