x-movie/server/loginHandler.go

66 lines
1.6 KiB
Go

package main
import (
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
var jwtSecret = []byte("eson1238752372fs")
func loginHandler(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
// 在这里验证用户名和密码。在此示例中,我们仅检查它们是否为空。
if username == "" || password == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Username and password required"})
return
}
if username != "eson" || password != "6601502.." {
c.JSON(http.StatusBadRequest, gin.H{"error": "Username and password error"})
return
}
// 创建 JWT
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["username"] = username
claims["exp"] = time.Now().Add(time.Hour * 24 * 7).Unix()
tokenString, err := token.SignedString(jwtSecret)
if err != nil {
log.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate JWT"})
return
}
c.JSON(http.StatusOK, gin.H{"token": tokenString})
}
func jwtMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
return
}
tokenString := authHeader[7:]
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
return
}
c.Next()
}
}