-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.go
107 lines (91 loc) · 2.69 KB
/
main.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
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
package main
import (
"fmt"
"log"
"net/http"
"go-casbin-http-authrozation/User"
)
func main() {
// 定义路径
mux := http.NewServeMux()
mux.HandleFunc("/login", loginHandler(User.Authorized))
mux.HandleFunc("/logout", logoutHandler())
mux.HandleFunc("/member/current", currentMemberHandler())
mux.HandleFunc("/member/role", memberRoleHandler())
mux.HandleFunc("/admin/stuff", adminHandler())
log.Print("监听端口 :8081")
log.Fatal(http.ListenAndServe(
":8081",
User.SessionManager.Use(User.Authorizer(
User.AuthEnforcer, // casbin 鉴权
User.Authorized, // 授权用户
)(mux)),
))
}
///
func loginHandler(users User.Items) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := r.PostFormValue("name")
session := User.SessionManager.Load(r)
user, err := users.FindByName(name)
if err != nil {
writeError(http.StatusBadRequest, "WRONG_CREDENTIALS", w, err)
return
}
// 创建 token 值
if err := session.RenewToken(w); err != nil {
writeError(http.StatusInternalServerError, "内部错误", w, err)
return
}
_ = session.PutInt(w, "id", user.ID)
_ = session.PutString(w, "role", user.Role)
writeSuccess("SUCCESS", w)
})
}
func logoutHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := User.SessionManager.Load(r)
if err := session.Destroy(w); err != nil {
writeError(http.StatusInternalServerError, "内部错误", w, err)
return
}
writeSuccess("SUCCESS", w)
})
}
func currentMemberHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := User.SessionManager.Load(r)
uid, err := session.GetInt("id")
if err != nil {
writeError(http.StatusInternalServerError, "内部错误", w, err)
return
}
writeSuccess(fmt.Sprintf("当前用户ID: %d", uid), w)
})
}
func memberRoleHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := User.SessionManager.Load(r)
role, err := session.GetString("role")
if err != nil {
writeError(http.StatusInternalServerError, "内部错误", w, err)
return
}
writeSuccess(fmt.Sprintf("当前用户角色: %s", role), w)
})
}
func adminHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writeSuccess("你是管理员!", w)
})
}
///
func writeError(status int, message string, w http.ResponseWriter, err error) {
log.Print("错误: ", err.Error())
w.WriteHeader(status)
_, _ = w.Write([]byte(message))
}
func writeSuccess(message string, w http.ResponseWriter) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(message))
}