63 lines
1.2 KiB
Go
63 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
"github.com/gin-contrib/sessions/cookie"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const (
|
|
// SessionUser 用户登录的Session标签
|
|
SessionUser = "token"
|
|
)
|
|
|
|
func auth(ctx *gin.Context) {
|
|
if ctx.Request.RequestURI != "/api/login" {
|
|
session := sessions.Default(ctx)
|
|
if token := session.Get(SessionUser); token == nil {
|
|
ctx.Redirect(http.StatusNotModified, "/api/login")
|
|
return
|
|
}
|
|
}
|
|
ctx.Next()
|
|
}
|
|
|
|
func login(ctx *gin.Context) {
|
|
ctx.Request.ParseForm()
|
|
user := ctx.PostForm("user")
|
|
|
|
if realPassword, ok := GlobalConfig.GetUser(user); ok {
|
|
|
|
pwd := ctx.PostForm("pwd")
|
|
if realPassword == pwd {
|
|
session := sessions.Default(ctx)
|
|
session.Set(SessionUser, user)
|
|
session.Save()
|
|
} else {
|
|
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"})
|
|
return
|
|
}
|
|
} else {
|
|
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "不存在该用户"})
|
|
return
|
|
}
|
|
|
|
ctx.JSON(http.StatusOK, gin.H{"message": "登录成功"})
|
|
// ctx.Redirect(http.StatusOK, "/worker")
|
|
|
|
}
|
|
|
|
func main() {
|
|
|
|
eg := gin.New()
|
|
|
|
eg.Use(sessions.Sessions(SessionUser, cookie.NewStore([]byte("yame"))))
|
|
eg.Use(auth)
|
|
|
|
eg.POST("/api/login", login)
|
|
log.Fatal(eg.Run(":3001"))
|
|
}
|