-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
token.go
298 lines (241 loc) · 7.94 KB
/
token.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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package user
import (
"net/http"
"github.com/azukaar/cosmos-server/src/utils"
"github.com/golang-jwt/jwt"
"errors"
"strconv"
"strings"
"time"
"encoding/json"
)
func quickLoggout(w http.ResponseWriter, req *http.Request, err error) (utils.User, error) {
utils.Error("UserToken: Token likely falsified", err)
logOutUser(w, req)
redirectToReLogin(w, req)
return utils.User{}, errors.New("Token likely falsified")
}
func RefreshUserToken(w http.ResponseWriter, req *http.Request) (utils.User, error) {
config := utils.GetMainConfig()
// if new install
if config.NewInstall {
// check route
if req.URL.Path != "/cosmos/api/status" && req.URL.Path != "/cosmos/api/newInstall" && req.URL.Path != "/cosmos/api/dns" {
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "NEW_INSTALL",
})
return utils.User{}, errors.New("New install")
} else {
return utils.User{}, nil
}
}
cookie, err := req.Cookie("jwttoken")
if err != nil {
return utils.User{}, nil
}
tokenString := cookie.Value
if tokenString == "" {
return utils.User{}, nil
}
ed25519Key, errK := jwt.ParseEdPublicKeyFromPEM([]byte(utils.GetPublicAuthKey()))
if errK != nil {
utils.Error("UserToken: Cannot read auth public key", errK)
utils.HTTPError(w, "Authorization Error", http.StatusInternalServerError, "A001")
return utils.User{}, errors.New("Cannot read auth public key")
}
parts := strings.Split(tokenString, ".")
errT := jwt.SigningMethodEdDSA.Verify(strings.Join(parts[0:2], "."), parts[2], ed25519Key)
if errT != nil {
if _, e := quickLoggout(w, req, errT); e != nil {
return utils.User{}, errT
}
}
type claimsType struct {
nickname string
}
claims := jwt.MapClaims{}
_, errP := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return ed25519Key, nil
})
if errP != nil {
utils.Error("UserToken: token is not valid", nil)
logOutUser(w, req)
redirectToReLogin(w, req)
return utils.User{}, errors.New("Token not valid")
}
var (
nickname string
passwordCycle int
mfaDone bool
ok bool
forDomain string
)
if nickname, ok = claims["nickname"].(string); !ok {
if _, e := quickLoggout(w, req, nil); e != nil {
return utils.User{}, e
}
}
if passwordCycleFloat, ok := claims["passwordCycle"].(float64); ok {
passwordCycle = int(passwordCycleFloat)
} else {
if _, e := quickLoggout(w, req, nil); e != nil {
return utils.User{}, e
}
}
if mfaDone, ok = claims["mfaDone"].(bool); !ok {
if _, e := quickLoggout(w, req, nil); e != nil {
return utils.User{}, e
}
}
if forDomain, ok = claims["forDomain"].(string); !ok {
if _, e := quickLoggout(w, req, nil); e != nil {
return utils.User{}, e
}
}
reqHostname := req.Host
reqHostNoPort := strings.Split(reqHostname, ":")[0]
if !strings.HasSuffix(reqHostNoPort, forDomain) {
utils.Error("UserToken: token is not valid for this domain", nil)
logOutUser(w, req)
redirectToReLogin(w, req)
return utils.User{}, errors.New("JWT Token not valid for this domain")
}
userInBase := utils.User{}
c, closeDb, errCo := utils.GetEmbeddedCollection(utils.GetRootAppId(), "users")
defer closeDb()
if errCo != nil {
utils.Error("Database Connect", errCo)
utils.HTTPError(w, "Database", http.StatusInternalServerError, "DB001")
return utils.User{}, errCo
}
errDB := c.FindOne(nil, map[string]interface{}{
"Nickname": nickname,
}).Decode(&userInBase)
if errDB != nil {
utils.Error("UserToken: User not found", errDB)
logOutUser(w, req)
redirectToReLogin(w, req)
return utils.User{}, errors.New("User not found")
}
if userInBase.PasswordCycle != passwordCycle {
utils.Error("UserToken: Password cycle changed, token is too old", nil)
logOutUser(w, req)
redirectToReLogin(w, req)
return utils.User{}, errors.New("Password cycle changed, token is too old")
}
requestURL := req.URL.Path
isSettingMFA := strings.HasPrefix(requestURL, "/cosmos-ui/loginmfa") || strings.HasPrefix(requestURL, "/cosmos-ui/newmfa") || strings.HasPrefix(requestURL, "/api/mfa")
userInBase.MFAState = 0
if !isSettingMFA && (userInBase.MFAKey != "" && userInBase.Was2FAVerified && !mfaDone) {
utils.Warn("UserToken: MFA required")
userInBase.MFAState = 1
} else if !isSettingMFA && (config.RequireMFA && !mfaDone) {
utils.Warn("UserToken: MFA not set")
userInBase.MFAState = 2
}
if time.Now().Unix() - int64(claims["iat"].(float64)) > 3600 {
SendUserToken(w, req, userInBase, mfaDone)
}
return userInBase, nil
}
func GetUserR(req *http.Request) (string, string) {
return req.Header.Get("x-cosmos-user"), req.Header.Get("x-cosmos-role")
}
func logOutUser(w http.ResponseWriter, req *http.Request) {
reqHostname := req.Host
reqHostNoPort := strings.Split(reqHostname, ":")[0]
cookie := http.Cookie{
Name: "jwttoken",
Value: "",
Expires: time.Now().Add(-time.Hour * 24 * 365),
Path: "/",
Secure: utils.IsHTTPS,
HttpOnly: true,
}
clientCookie := http.Cookie{
Name: "client-infos",
Value: "{}",
Expires: time.Now().Add(-time.Hour * 24 * 365),
Path: "/",
Secure: utils.IsHTTPS,
HttpOnly: false,
}
if reqHostNoPort == "localhost" || reqHostNoPort == "0.0.0.0" {
cookie.Domain = ""
clientCookie.Domain = ""
} else {
cookie.Domain = "." + reqHostNoPort
clientCookie.Domain = "." + reqHostNoPort
}
http.SetCookie(w, &cookie)
http.SetCookie(w, &clientCookie)
// TODO: logout every other device if asked by increasing passwordcycle
}
func redirectToReLogin(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, "/cosmos-ui/login?invalid=1&redirect=" + req.URL.Path + "&" + req.URL.RawQuery, http.StatusTemporaryRedirect)
}
func redirectToLoginMFA(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, "/cosmos-ui/loginmfa?invalid=1&redirect=" + req.URL.Path + "&" + req.URL.RawQuery, http.StatusTemporaryRedirect)
}
func redirectToNewMFA(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, "/cosmos-ui/newmfa?invalid=1&redirect=" + req.URL.Path + "&" + req.URL.RawQuery, http.StatusTemporaryRedirect)
}
func SendUserToken(w http.ResponseWriter, req *http.Request, user utils.User, mfaDone bool) {
reqHostname := req.Host
reqHostNoPort := strings.Split(reqHostname, ":")[0]
expiration := time.Now().Add(3 * 24 * time.Hour)
token := jwt.New(jwt.SigningMethodEdDSA)
claims := token.Claims.(jwt.MapClaims)
claims["exp"] = expiration.Unix()
claims["role"] = user.Role
claims["nickname"] = user.Nickname
claims["passwordCycle"] = user.PasswordCycle
claims["iat"] = time.Now().Unix()
claims["nbf"] = time.Now().Unix()
claims["mfaDone"] = mfaDone
claims["forDomain"] = reqHostNoPort
key, err5 := jwt.ParseEdPrivateKeyFromPEM([]byte(utils.GetPrivateAuthKey()))
if err5 != nil {
utils.Error("UserLogin: Error while retrieving signing key", err5)
utils.HTTPError(w, "User Logging Error", http.StatusInternalServerError, "UL001")
return
}
tokenString, err4 := token.SignedString(key)
if err4 != nil {
utils.Error("UserLogin: Error while signing token", err4)
utils.HTTPError(w, "User Logging Error", http.StatusInternalServerError, "UL001")
return
}
cookie := http.Cookie{
Name: "jwttoken",
Value: tokenString,
Expires: expiration,
Path: "/",
Secure: utils.IsHTTPS,
HttpOnly: true,
}
clientCookie := http.Cookie{
Name: "client-infos",
Value: user.Nickname + "," + strconv.Itoa(int(user.Role)),
Expires: expiration,
Path: "/",
Secure: utils.IsHTTPS,
HttpOnly: false,
}
utils.Log("UserLogin: Setting cookie for " + reqHostNoPort)
if reqHostNoPort == "localhost" || reqHostNoPort == "0.0.0.0" {
cookie.Domain = ""
clientCookie.Domain = ""
} else {
if utils.IsValidHostname(reqHostNoPort) {
cookie.Domain = "." + reqHostNoPort
clientCookie.Domain = "." + reqHostNoPort
} else {
utils.Error("UserLogin: Invalid hostname", nil)
utils.HTTPError(w, "User Logging Error", http.StatusInternalServerError, "UL001")
return
}
}
http.SetCookie(w, &cookie)
http.SetCookie(w, &clientCookie)
}