/
session.go
159 lines (144 loc) · 3.91 KB
/
session.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
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
package session
import (
"encoding/json"
"fmt"
"net/http"
"regexp"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/ybkuroki/go-webapp-project-template/config"
"github.com/ybkuroki/go-webapp-project-template/model"
"gopkg.in/boj/redistore.v1"
)
const (
// sessionStr represents a string of session key.
sessionStr = "GSESSION"
// Account is the key of account data in the session.
Account = "Account"
)
// Init initalize session authentication.
func Init(e *echo.Echo, conf *config.Config) {
if conf.Extension.SecurityEnabled {
if conf.Redis.Enabled {
e.Logger.Info("Try redis connection")
address := fmt.Sprintf("%s:%s", conf.Redis.Host, conf.Redis.Port)
store, err := redistore.NewRediStore(conf.Redis.ConnectionPoolSize, "tcp", address, "", []byte("secret"))
if err != nil {
e.Logger.Error("Failure redis connection")
}
e.Use(session.Middleware(store))
e.Logger.Info(fmt.Sprintf("Success redis connection, %s", address))
} else {
e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret"))))
}
e.Use(AuthenticationMiddleware(conf))
}
}
// AuthenticationMiddleware is the middleware of session authentication for echo.
func AuthenticationMiddleware(conf *config.Config) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !hasAuthorization(c, conf) {
return c.JSON(http.StatusUnauthorized, false)
}
if err := next(c); err != nil {
c.Error(err)
}
return nil
}
}
}
// hasAuthorization judges whether the user has the right to access the path.
func hasAuthorization(c echo.Context, conf *config.Config) bool {
currentPath := c.Path()
if equalPath(currentPath, conf.Security.ExculdePath) {
return true
}
account := GetAccount(c)
if account == nil {
return false
}
if account.Authority.Name == "Admin" && equalPath(currentPath, conf.Security.AdminPath) {
_ = Save(c)
return true
}
if account.Authority.Name == "User" && equalPath(currentPath, conf.Security.UserPath) {
_ = Save(c)
return true
}
return false
}
// equalPath judges whether a given path contains in the path list.
func equalPath(cpath string, paths []string) bool {
for i := range paths {
if regexp.MustCompile(paths[i]).Match([]byte(cpath)) {
return true
}
}
return false
}
// Get returns a session for the current request.
func Get(c echo.Context) *sessions.Session {
sess, _ := session.Get(sessionStr, c)
return sess
}
// Save saves the current session.
func Save(c echo.Context) error {
sess := Get(c)
sess.Options = &sessions.Options{
Path: "/",
HttpOnly: true,
}
return saveSession(c, sess)
}
// Delete the current session.
func Delete(c echo.Context) error {
sess := Get(c)
sess.Options = &sessions.Options{
Path: "/",
HttpOnly: true,
MaxAge: -1,
}
return saveSession(c, sess)
}
func saveSession(c echo.Context, sess *sessions.Session) error {
if err := sess.Save(c.Request(), c.Response()); err != nil {
return c.NoContent(http.StatusInternalServerError)
}
return nil
}
// SetValue sets a key and a value.
func SetValue(c echo.Context, key string, value interface{}) error {
sess := Get(c)
bytes, err := json.Marshal(value)
if err != nil {
return c.NoContent(http.StatusInternalServerError)
}
sess.Values[key] = string(bytes)
return nil
}
// GetValue returns value of session.
func GetValue(c echo.Context, key string) string {
sess := Get(c)
v := sess.Values[key]
data, result := v.(string)
if result && data != "null" {
return data
}
return ""
}
// SetAccount sets account data in session.
func SetAccount(c echo.Context, account *model.Account) error {
return SetValue(c, Account, account)
}
// GetAccount returns account object of session.
func GetAccount(c echo.Context) *model.Account {
v := GetValue(c, Account)
if v != "" {
a := &model.Account{}
_ = json.Unmarshal([]byte(v), a)
return a
}
return nil
}