forked from Cepave/open-falcon-backend
/
auth_controller.go
425 lines (382 loc) · 11.3 KB
/
auth_controller.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package uic
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/Cepave/open-falcon-backend/modules/fe/g"
"github.com/Cepave/open-falcon-backend/modules/fe/http/base"
. "github.com/Cepave/open-falcon-backend/modules/fe/model/uic"
"github.com/Cepave/open-falcon-backend/modules/fe/utils"
log "github.com/sirupsen/logrus"
"github.com/toolkits/str"
)
type AuthController struct {
base.BaseController
}
func (this *AuthController) Logout() {
u := this.Ctx.Input.GetData("CurrentUser").(*User)
token := this.Ctx.GetCookie("token")
if len(token) > 0 {
url := g.Config().Api.Logout + "/" + token
log.Println("logout url =", url)
result := sendHttpGetRequest(url)
log.Println("logout result =", result)
this.Ctx.SetCookie("token", "", 0, "/")
this.Ctx.SetCookie("token", "", 0, "/", g.Config().Http.Cookie)
}
RemoveSessionByUid(u.Id)
this.Ctx.SetCookie("sig", "", 0, "/")
this.Ctx.SetCookie("sig", "", 0, "/", g.Config().Http.Cookie)
this.Ctx.SetCookie("name", "", 0, "/")
this.Ctx.SetCookie("name", "", 0, "/", g.Config().Http.Cookie)
this.Redirect("/auth/login", 302)
}
func (this *AuthController) LoginGet() {
appSig := this.GetString("sig", "")
callback := this.GetString("callback", "")
cookieSig := this.Ctx.GetCookie("sig")
switch cookieSig {
case "":
this.renderLoginPage(appSig, callback)
return
case "disabled":
this.renderLoginPage(cookieSig, callback)
}
sessionObj := ReadSessionBySig(cookieSig)
if sessionObj == nil {
this.renderLoginPage(appSig, callback)
return
}
if int64(sessionObj.Expired) < time.Now().Unix() {
RemoveSessionByUid(sessionObj.Uid)
this.renderLoginPage(appSig, callback)
return
}
if appSig != "" && callback != "" {
this.Redirect(callback, 302)
} else {
this.Redirect("/me/info", 302)
}
}
func (this *AuthController) LoginPost() {
name := this.GetString("name", "")
password := this.GetString("password", "")
if name == "" || password == "" {
this.ServeErrJson("name or password is blank")
return
}
var u *User
ldapEnabled := this.MustGetBool("ldap", false)
if ldapEnabled {
success, err := utils.LdapBind(g.Config().Ldap.Addr,
g.Config().Ldap.BaseDN,
g.Config().Ldap.BindDN,
g.Config().Ldap.BindPasswd,
g.Config().Ldap.UserField,
name,
password)
if err != nil {
this.ServeErrJson(err.Error())
return
}
if !success {
this.ServeErrJson("name or password error")
return
}
user_attributes, err := utils.Ldapsearch(g.Config().Ldap.Addr,
g.Config().Ldap.BaseDN,
g.Config().Ldap.BindDN,
g.Config().Ldap.BindPasswd,
g.Config().Ldap.UserField,
name,
g.Config().Ldap.Attributes)
userSn := ""
userMail := ""
userTel := ""
if err == nil {
userSn = user_attributes["sn"]
userMail = user_attributes["mail"]
userTel = user_attributes["telephoneNumber"]
}
arr := strings.Split(name, "@")
var userName, userEmail string
if len(arr) == 2 {
userName = arr[0]
userEmail = name
} else {
userName = name
userEmail = userMail
}
u = ReadUserByName(userName)
if u == nil {
// 说明用户不存在
u = &User{
Name: userName,
Passwd: "",
Cnname: userSn,
Phone: userTel,
Email: userEmail,
}
_, err = u.Save()
if err != nil {
this.ServeErrJson("insert user fail " + err.Error())
return
}
}
} else {
u = ReadUserByName(name)
if u == nil {
this.ServeErrJson("no such user")
return
}
if u.Passwd != str.Md5Encode(g.Config().Salt+password) {
this.ServeErrJson("password error")
return
}
if u.Role == -1 {
this.ServeErrJson("this account has been disabled")
return
}
}
appSig := this.GetString("sig", "")
callback := this.GetString("callback", "")
if appSig != "" && callback != "" {
SaveSessionAttrs(u.Id, appSig, int(time.Now().Unix())+3600*24*30)
} else {
this.CreateSession(u.Id, 3600*24*30)
}
this.ServeDataJson(callback)
}
func (this *AuthController) renderLoginPage(sig, callback string) {
this.Data["CanRegister"] = g.Config().CanRegister
this.Data["LdapEnabled"] = g.Config().Ldap.Enabled
this.Data["Sig"] = sig
this.Data["Callback"] = callback
this.Data["Shortcut"] = g.Config().Shortcut
if sig == "disabled" {
if this.Ctx.GetCookie("name") != "" {
this.Data["Message"] = fmt.Sprintf("%s has been disabled", this.Ctx.GetCookie("name"))
} else {
this.Data["Message"] = "this account has been disabled"
}
}
log.Printf("this.Data: %v", this.Data)
this.TplName = "auth/login.html"
}
func (this *AuthController) RegisterGet() {
this.Data["CanRegister"] = g.Config().CanRegister
this.Data["Shortcut"] = g.Config().Shortcut
this.TplName = "auth/register.html"
}
func (this *AuthController) RegisterPost() {
if !g.Config().CanRegister {
this.ServeErrJson("registration system is not open")
return
}
name := strings.TrimSpace(this.GetString("name", ""))
password := strings.TrimSpace(this.GetString("password", ""))
repeatPassword := strings.TrimSpace(this.GetString("repeat_password", ""))
email := strings.TrimSpace(this.GetString("email", ""))
if password != repeatPassword {
this.ServeErrJson("password not equal the repeart one")
return
}
if !utils.IsUsernameValid(name) {
this.ServeErrJson("name pattern is invalid")
return
}
if ReadUserIdByName(name) > 0 {
this.ServeErrJson("name is already existent")
return
}
lastId, err := InsertRegisterUser(name, str.Md5Encode(g.Config().Salt+password), email)
if err != nil {
this.ServeErrJson("insert user fail " + err.Error())
return
}
this.CreateSession(lastId, 3600*24*30)
this.ServeOKJson()
}
func (this *AuthController) CreateSession(uid int64, maxAge int) int {
sig := utils.GenerateUUID()
user := SelectUserById(uid)
expired := int(time.Now().Unix()) + maxAge
SaveSessionAttrs(uid, sig, expired)
this.Ctx.SetCookie("sig", sig, maxAge, "/")
this.Ctx.SetCookie("sig", sig, maxAge, "/", g.Config().Http.Cookie)
this.Ctx.SetCookie("name", user.Name, maxAge, "/")
this.Ctx.SetCookie("name", user.Name, maxAge, "/", g.Config().Http.Cookie)
return expired
}
/**
* @function name: func (this *AuthController) LoginThirdParty()
* @description: This function returns third party login URL.
* @related issues: OWL-206
* @param: void
* @return: void
* @author: Don Hsieh
* @since: 12/17/2015
* @last modified: 12/17/2015
* @called by: beego.Router("/auth/third-party", &AuthController{}, "post:LoginThirdParty")
* in fe/http/uic/uic_routes.go
*/
func (this *AuthController) LoginThirdParty() {
s := g.Config().Api.Redirect
s = base64.StdEncoding.EncodeToString([]byte(s))
strEncoded := url.QueryEscape(s)
loginUrl := g.Config().Api.Login + "/" + strEncoded
this.ServeDataJson(loginUrl)
}
/**
* @function name: func sendHttpGetRequest(url string) map[string]interface{}
* @description: This function sends GET request to given URL.
* @related issues: OWL-206, OWL-159
* @param: url string
* @return: map[string]interface{}
* @author: Don Hsieh
* @since: 12/17/2015
* @last modified: 12/17/2015
* @called by: func (this *AuthController) LoginWithToken()
* in fe/http/uic/auth_controller.go
*/
func sendHttpGetRequest(url string) map[string]interface{} {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println("Error =", err.Error())
}
client := &http.Client{}
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
log.Println("Error =", err.Error())
return nil
} else {
body, _ := ioutil.ReadAll(resp.Body)
var nodes = make(map[string]interface{})
if err := json.Unmarshal(body, &nodes); err != nil {
log.Println("Error =", err.Error())
return nil
}
return nodes
}
}
func setUserInfo(nodes map[string]interface{}, userInfo map[string]string) {
if status, ok := nodes["status"]; ok {
if int(status.(float64)) == 1 {
data := nodes["data"].(map[string]interface{})
access_key := data["access_key"].(string)
username := data["username"].(string)
email := data["email"].(string)
log.Println("access_key =", access_key)
userInfo["username"] = username
userInfo["email"] = email
userInfo["access_key"] = access_key
}
}
}
func getUserRole(access_key string) int {
urlRole := g.Config().Api.Role + "/" + access_key
nodes := sendHttpGetRequest(urlRole)
role := -1
if int(nodes["status"].(float64)) == 1 {
permission := nodes["data"]
log.Println("permission =", permission)
if permission == "admin" {
role = 0
} else if permission == "operator" {
role = 1
} else if permission == "observer" {
role = 2
} else if permission == "deny" {
role = 3
}
}
// TODO: The role should be able to be changed on BOSS in the future.
role = 1
return role
}
/**
* @function name: func (this *AuthController) LoginWithToken()
* @description: This function logins user with third party token.
* @related issues: OWL-247, OWL-206
* @param: void
* @return: void
* @author: Don Hsieh
* @since: 12/16/2015
* @last modified: 01/08/2016
* @called by: beego.Router("/auth/login/:token", &AuthController{}, "get:LoginWithToken")
* in fe/http/uic/uic_routes.go
*/
func (this *AuthController) LoginWithToken() {
log.Println("func (this *AuthController) LoginWithToken()")
token := this.Ctx.Input.Param(":token")
log.Println("token =", token)
key := g.Config().Api.Key
authUrl := g.Config().Api.Access + "/" + token + "/" + key
nodes := sendHttpGetRequest(authUrl)
if nodes == nil {
nodes = sendHttpGetRequest(authUrl)
}
log.Println("nodes =", nodes)
var userInfo = make(map[string]string)
userInfo["username"] = ""
userInfo["email"] = ""
userInfo["access_key"] = ""
if nodes != nil {
setUserInfo(nodes, userInfo)
}
log.Println("userInfo =", userInfo)
username := userInfo["username"]
if len(username) > 0 {
access_key := userInfo["access_key"]
user := ReadUserByName(username)
if user == nil { // create third party user
InsertRegisterUser(username, "", "")
user = ReadUserByName(username)
}
if len(user.Passwd) == 0 {
role := getUserRole(access_key)
if role < 1 {
role = getUserRole(access_key)
}
email := userInfo["email"]
user.Email = email
user.Role = role
user.Update()
}
maxAge := 3600 * 24 * 30
this.Ctx.SetCookie("token", access_key, maxAge, "/")
this.Ctx.SetCookie("token", access_key, maxAge, "/", g.Config().Http.Cookie)
if user.Role != -1 {
appSig := this.GetString("sig", "")
callback := this.GetString("callback", "")
if appSig != "" && callback != "" {
SaveSessionAttrs(user.Id, appSig, int(time.Now().Unix())+3600*24*30)
} else {
this.CreateSession(user.Id, 3600*24*30)
}
if callback != "" {
this.Redirect(callback, 302)
} else {
this.Redirect("/me/info", 302)
}
} else {
//role == -1 means this account has been disabled
this.Ctx.SetCookie("sig", "disabled", maxAge, "/", g.Config().Http.Cookie)
this.Ctx.SetCookie("name", username, maxAge, "/", g.Config().Http.Cookie)
appSig := "disabled"
callback := this.GetString("callback", "")
this.renderLoginPage(appSig, callback)
}
} else {
// not logged in. redirect to login page.
appSig := this.GetString("sig", "")
callback := this.GetString("callback", "")
this.renderLoginPage(appSig, callback)
}
}