-
Notifications
You must be signed in to change notification settings - Fork 2
/
user.go
98 lines (83 loc) · 2.63 KB
/
user.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
package routers
import (
"fmt"
"net/http"
"github.com/chadweimer/gomp/models"
"github.com/julienschmidt/httprouter"
"github.com/mholt/binding"
"github.com/urfave/negroni"
)
// LoginForm encapsulates user input for the login screen
type LoginForm struct {
Username string `form:"username"`
Password string `form:"password"`
}
// FieldMap provides the LoginForm field name maping for form binding
func (f *LoginForm) FieldMap(req *http.Request) binding.FieldMap {
return binding.FieldMap{
&f.Username: "username",
&f.Password: "password",
}
}
func (rc *RouteController) RequireAuthentication(h negroni.Handler) negroni.HandlerFunc {
return func(resp http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
sess, err := rc.sessionStore.Get(req, "UserSession")
if err != nil || sess.Values["UserID"] == nil {
if loginPath := fmt.Sprintf("%s/login", rc.cfg.RootURLPath); req.URL.Path != loginPath {
http.Redirect(resp, req, loginPath, http.StatusFound)
}
return
}
var user *models.User
userID, ok := sess.Values["UserID"].(int64)
if ok {
user, err = rc.model.Users.Read(userID)
}
if user == nil {
if logoutPath := fmt.Sprintf("%s/logout", rc.cfg.RootURLPath); req.URL.Path != logoutPath {
http.Redirect(resp, req, logoutPath, http.StatusFound)
}
return
}
h.ServeHTTP(resp, req, next)
}
}
func (rc *RouteController) Login(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
rc.HTML(resp, http.StatusOK, "user/login", make(map[string]interface{}))
}
func (rc *RouteController) LoginPost(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
form := new(LoginForm)
errs := binding.Bind(req, form)
if errs != nil && errs.Len() > 0 {
rc.HTML(resp, http.StatusOK, "user/login", make(map[string]interface{}))
return
}
user, err := rc.model.Users.Authenticate(form.Username, form.Password)
if err != nil {
rc.HTML(resp, http.StatusOK, "user/login", make(map[string]interface{}))
return
}
sess, err := rc.sessionStore.New(req, "UserSession")
if rc.HasError(resp, err) {
return
}
sess.Values["UserID"] = user.ID
err = sess.Save(req, resp)
if rc.HasError(resp, err) {
return
}
http.Redirect(resp, req, fmt.Sprintf("%s/", rc.cfg.RootURLPath), http.StatusFound)
}
func (rc *RouteController) Logout(resp http.ResponseWriter, req *http.Request, p httprouter.Params) {
sess, _ := rc.sessionStore.Get(req, "UserSession")
if sess != nil {
for k := range sess.Values {
delete(sess.Values, k)
}
err := sess.Save(req, resp)
if rc.HasError(resp, err) {
return
}
}
http.Redirect(resp, req, fmt.Sprintf("%s/login", rc.cfg.RootURLPath), http.StatusFound)
}