/
auth.go
63 lines (54 loc) · 1.26 KB
/
auth.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
package controllers
import (
"github.com/astaxie/beego"
"github.com/wangbin/imwb/forms"
"github.com/wangbin/imwb/models"
)
const (
SessionKey = "_auth_user_id"
)
type LoginController struct {
beego.Controller
userCache *models.User
}
func (this *LoginController) Prepare() {
userId := this.GetSession(SessionKey)
if userId == nil {
this.userCache = models.AnonymousUser()
} else {
this.userCache = models.GetUser(userId.(string))
}
}
func (this *LoginController) Get() {
this.TplNames = "login.tpl"
form := forms.NewLoginForm(this.userCache)
this.Data["Form"] = form
this.Data["User"] = this.userCache
}
func (this *LoginController) Post() {
form := forms.NewLoginForm(this.userCache)
err := this.ParseForm(form)
if err != nil {
form.SetNonFieldError(err)
}
if !form.IsValid() {
this.TplNames = "login.tpl"
this.Data["User"] = this.userCache
this.Data["Form"] = form
} else {
this.login(form.User())
this.Ctx.Redirect(302, "/login/")
}
}
func (this *LoginController) login(user *models.User) {
this.userCache = user
this.DelSession(SessionKey)
this.SetSession(SessionKey, user.Id)
}
type LogoutController struct {
beego.Controller
}
func (this *LogoutController) Get() {
this.DelSession(SessionKey)
this.Ctx.Redirect(302, "/login/")
}