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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
|
package main
import (
"errors"
"fmt" "net/http" "os" "strconv" "strings" "time"
"github.com/fatih/color" "github.com/kataras/iris/v12/context"
"github.com/kataras/iris/v12"
"github.com/iris-contrib/middleware/cors" "github.com/iris-contrib/middleware/jwt" "github.com/jameskeane/bcrypt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/kataras/iris/v12/middleware/logger" "github.com/kataras/iris/v12/middleware/recover" _ "github.com/mattn/go-sqlite3"
)
var Db *gorm.DB
var err error
var dirverName string
var conn string
// 用户数据模型
type User struct {
gorm.Model
Name string `gorm:"not null VARCHAR(191)"`
Username string `gorm:"unique;VARCHAR(191)"`
Password string `gorm:"not null VARCHAR(191)"`
}
// 接口返回数据对想
type Response struct {
Status bool `json:"status"` //接口状态 true ,false Msg interface{} `json:"msg"` // 接口信息
Data interface{} `json:"data"` //接口数据
}
// token 数据模型
type OauthToken struct {
gorm.Model
Token string `gorm:"not null default '' comment('Token') VARCHAR(191)"`
UserId uint `gorm:"not null default '' comment('UserId') VARCHAR(191)"`
Secret string `gorm:"not null default '' comment('Secret') VARCHAR(191)"`
ExpressIn int64 `gorm:"not null default 0 comment('是否是标准库') BIGINT(20)"`
Revoked bool
}
// 创建 token
func (ot *OauthToken) OauthTokenCreate() (response Token) {
Db.Create(ot)
response = Token{ot.Token}
return
}
type Token struct {
Token string `json:"access_token"`
}
// 判断数据库是否返回 ErrRecordNotFound ,如果是说明数据库没有相关记录。
func IsNotFound(err error) {
if ok := errors.Is(err, gorm.ErrRecordNotFound); !ok && err != nil {
color.Red(fmt.Sprintf("error :%v \n ", err))
}
}
// 根据用户名查询用户
func UserAdminCheckLogin(username string) *User {
user := new(User)
IsNotFound(Db.Where("username = ?", username).First(user).Error)
return user
}
// 登陆处理程序
func UserLogin(ctx iris.Context) {
aul := new(User)
if err := ctx.ReadJSON(&aul); err != nil {
ctx.StatusCode(iris.StatusOK)
_, _ = ctx.JSON(Response{Status: false, Msg: nil, Data: "请求参数错误"})
return
}
ctx.StatusCode(iris.StatusOK)
response, status, msg := CheckLogin(aul.Username, aul.Password)
_, _ = ctx.JSON(Response{Status: status, Msg: response, Data: msg})
return
}
// 检查登陆用户,并生成登陆凭证 token
func CheckLogin(username, password string) (response Token, status bool, msg string) {
user := UserAdminCheckLogin(username)
if user.ID == 0 {
msg = "用户不存在"
return
} else {
if ok := bcrypt.Match(password, user.Password); ok {
token := jwt.NewTokenWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": time.Now().Add(time.Hour * time.Duration(1)).Unix(),
"iat": time.Now().Unix(),
})
tokenString, _ := token.SignedString([]byte("HS2JDFKhu7Y1av7b"))
oauthToken := new(OauthToken)
oauthToken.Token = tokenString
oauthToken.UserId = user.ID
oauthToken.Secret = "secret"
oauthToken.Revoked = false
oauthToken.ExpressIn = time.Now().Add(time.Hour * time.Duration(1)).Unix()
oauthToken.CreatedAt = time.Now()
response = oauthToken.OauthTokenCreate()
status = true
msg = "登陆成功"
return
} else {
msg = "用户名或密码错误"
return
}
}
}
// 作废token
func UpdateOauthTokenByUserId(userId uint) (ot *OauthToken) {
Db.Model(ot).Where("revoked = ?", false).
Where("user_id = ?", userId).
Updates(map[string]interface{}{"revoked": true})
return
}
// 登出用户
func UserAdminLogout(userId uint) bool {
ot := UpdateOauthTokenByUserId(userId)
return ot.Revoked
}
// 登出
func UserLogout(ctx iris.Context) {
aui := ctx.Values().GetString("auth_user_id")
id, _ := strconv.Atoi(aui)
UserAdminLogout(uint(id))
ctx.StatusCode(http.StatusOK)
_, _ = ctx.JSON(Response{true, nil, "退出"})
}
//获取程序运行环境
// 根据程序运行路径后缀判断
//如果是 test 就是测试环境
func isTestEnv() bool {
files := os.Args
for _, v := range files {
if strings.Contains(v, "test") {
return true
}
}
return false
}
// 接口跨域处理
func CrsAuth() context.Handler {
return cors.New(cors.Options{
AllowedOrigins: []string{"*"}, // allows everything, use that to change the hosts.
AllowedMethods: []string{"PUT", "PATCH", "GET", "POST", "OPTIONS", "DELETE"},
AllowedHeaders: []string{"*"},
ExposedHeaders: []string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
AllowCredentials: true,
})
}
// 获取 access_token 信息
func GetOauthTokenByToken(token string) (ot *OauthToken) {
ot = new(OauthToken)
Db.Where("token = ?", token).First(&ot)
return
}
/**
* 验证 jwt * @method JwtHandler */
func JwtHandler() *jwt.Middleware {
var mySecret = []byte("HS2JDFKhu7Y1av7b")
return jwt.New(jwt.Config{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return mySecret, nil
},
SigningMethod: jwt.SigningMethodHS256,
})
}
func AuthToken(ctx context.Context) {
value := ctx.Values().Get("jwt").(*jwt.Token)
token := GetOauthTokenByToken(value.Raw) //获取 access_token 信息
if token.Revoked || token.ExpressIn < time.Now().Unix() {
//_, _ = ctx.Writef("token 失效,请重新登录") // 输出到前端
ctx.StatusCode(http.StatusUnauthorized)
ctx.StopExecution()
return
} else {
ctx.Values().Set("auth_user_id", token.UserId)
}
ctx.Next()
}
func NewApp() *iris.Application {
dirverName = "mysql"
if isTestEnv() { //如果是测试使用测试数据库
conn = "root:wemT5ZNuo074i4FNsTwl4KhfVSvOlBcF@(127.0.0.1:3306)/tiris?charset=utf8&parseTime=True&loc=Local"
} else {
conn = "root:wemT5ZNuo074i4FNsTwl4KhfVSvOlBcF@(127.0.0.1:3306)/iris?charset=utf8&parseTime=True&loc=Local"
}
//初始化数据库
Db, err = gorm.Open(dirverName, conn)
if err != nil {
color.Red(fmt.Sprintf("gorm open 错误: %v", err))
}
app := iris.New()
app.Logger().SetLevel("debug")
app.Use(recover.New())
app.Use(logger.New())
// 路由集使用跨域中间件 CrsAuth()
// 允许 Options 方法 AllowMethods(iris.MethodOptions)
main := app.Party("/", CrsAuth()).AllowMethods(iris.MethodOptions)
{
v1 := main.Party("/v1")
{
v1.Post("/admin/login", UserLogin)
v1.PartyFunc("/admin", func(admin iris.Party) {
admin.Use(JwtHandler().Serve, AuthToken) //登录验证
admin.Get("/logout", UserLogout).Name = "退出"
})
}
}
return app
}
func main() {
app := NewApp()
app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}
|