This repository has been archived by the owner on Oct 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
74 lines (66 loc) · 1.46 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
log "github.com/sirupsen/logrus"
)
type Auth struct{}
func (auth Auth) skipper(c echo.Context) bool {
method := c.Request().Method
path := c.Path()
switch path {
case "/login":
return true
}
if method != "GET" {
return false
}
if path == "" {
return true
}
return false
}
func (auth Auth) checkUserAuth(userName string, password string) bool {
user := User{}
userInfo, err := user.GetUserByName(userName)
if err != nil {
return false
}
log.Info("Auth:", userInfo)
return true
}
// 登录
func (auth Auth) Login(c echo.Context) error {
username := c.FormValue("username")
password := c.FormValue("password")
// 从数据库中操作
if auth.checkUserAuth(username, password) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["name"] = username
claims["admin"] = false
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
t, err := token.SignedString([]byte(conf.Secret))
if err != nil {
log.Warn("认证不通过,请检查")
return c.JSON(http.StatusForbidden, &Response{
Success: false,
Result: "",
Message: "请获取 token 并在 HEADER 中设置 token!",
})
}
type Token struct {
Token string `json:"token"`
}
return c.JSON(http.StatusOK, &Response{
Success: true,
Result: Token{
Token: t,
},
Message: "",
})
}
return echo.ErrUnauthorized
}