forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
99 lines (85 loc) · 2.32 KB
/
app.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
package controllers
import (
"code.google.com/p/go.crypto/bcrypt"
"github.com/robfig/revel"
"github.com/robfig/revel/samples/booking/app/models"
"github.com/robfig/revel/samples/booking/app/routes"
)
type Application struct {
GorpController
}
func (c Application) AddUser() revel.Result {
if user := c.connected(); user != nil {
c.RenderArgs["user"] = user
}
return nil
}
func (c Application) connected() *models.User {
if c.RenderArgs["user"] != nil {
return c.RenderArgs["user"].(*models.User)
}
if username, ok := c.Session["user"]; ok {
return c.getUser(username)
}
return nil
}
func (c Application) getUser(username string) *models.User {
users, err := c.Txn.Select(models.User{}, `select * from User where Username = ?`, username)
if err != nil {
panic(err)
}
if len(users) == 0 {
return nil
}
return users[0].(*models.User)
}
func (c Application) Index() revel.Result {
if c.connected() != nil {
return c.Redirect(routes.Hotels.Index())
}
c.Flash.Error("Please log in first")
return c.Render()
}
func (c Application) Register() revel.Result {
return c.Render()
}
func (c Application) SaveUser(user models.User, verifyPassword string) revel.Result {
c.Validation.Required(verifyPassword)
c.Validation.Required(verifyPassword == user.Password).
Message("Password does not match")
user.Validate(c.Validation)
if c.Validation.HasErrors() {
c.Validation.Keep()
c.FlashParams()
return c.Redirect(routes.Application.Register())
}
user.HashedPassword, _ = bcrypt.GenerateFromPassword(
[]byte(user.Password), bcrypt.DefaultCost)
err := c.Txn.Insert(&user)
if err != nil {
panic(err)
}
c.Session["user"] = user.Username
c.Flash.Success("Welcome, " + user.Name)
return c.Redirect(routes.Hotels.Index())
}
func (c Application) Login(username, password string) revel.Result {
user := c.getUser(username)
if user != nil {
err := bcrypt.CompareHashAndPassword(user.HashedPassword, []byte(password))
if err == nil {
c.Session["user"] = username
c.Flash.Success("Welcome, " + username)
return c.Redirect(routes.Hotels.Index())
}
}
c.Flash.Out["username"] = username
c.Flash.Error("Login failed")
return c.Redirect(routes.Application.Index())
}
func (c Application) Logout() revel.Result {
for k := range c.Session {
delete(c.Session, k)
}
return c.Redirect(routes.Application.Index())
}