This repository has been archived by the owner on Mar 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
users.go
73 lines (63 loc) · 1.77 KB
/
users.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
package actions
import (
"database/sql"
"github.com/gobuffalo/buffalo"
"github.com/gobuffalo/pop"
"github.com/gobuffalo/toodo/internal/takeon/github.com/markbates/errx"
"github.com/gobuffalo/toodo/models"
)
func UsersNew(c buffalo.Context) error {
u := models.User{}
c.Set("user", u)
return c.Render(200, r.HTML("users/new.plush.html"))
}
// UsersCreate registers a new user with the application.
func UsersCreate(c buffalo.Context) error {
u := &models.User{}
if err := c.Bind(u); err != nil {
return err
}
tx := c.Value("tx").(*pop.Connection)
verrs, err := u.Create(tx)
if err != nil {
return err
}
if verrs.HasAny() {
c.Set("user", u)
c.Set("errors", verrs)
return c.Render(200, r.HTML("users/new.plush.html"))
}
c.Session().Set("current_user_id", u.ID)
c.Flash().Add("success", "Welcome to Toodo!")
return c.Redirect(302, "/items")
}
// SetCurrentUser attempts to find a user based on the current_user_id
// in the session. If one is found it is set on the context.
func SetCurrentUser(next buffalo.Handler) buffalo.Handler {
return func(c buffalo.Context) error {
if uid := c.Session().Get("current_user_id"); uid != nil {
u := &models.User{}
tx := c.Value("tx").(*pop.Connection)
err := tx.Find(u, uid)
if err != nil {
c.Session().Clear()
if errx.Unwrap(err) == sql.ErrNoRows {
return c.Redirect(302, "/")
}
return err
}
c.Set("current_user", u)
}
return next(c)
}
}
// Authorize require a user be logged in before accessing a route
func Authorize(next buffalo.Handler) buffalo.Handler {
return func(c buffalo.Context) error {
if uid := c.Session().Get("current_user_id"); uid == nil {
c.Flash().Add("danger", "You must be authorized to see that page")
return c.Redirect(302, "/")
}
return next(c)
}
}