forked from elcct/defaultproject
/
middleware.go
66 lines (59 loc) · 1.97 KB
/
middleware.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
package system
import (
"net/http"
"github.com/golang/glog"
"github.com/zenazn/goji/web"
"github.com/elcct/defaultproject/models"
"github.com/gorilla/context"
"github.com/gorilla/sessions"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
// Makes sure templates are stored in the context
func (application *Application) ApplyTemplates(c *web.C, h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
c.Env["Template"] = application.Template
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
// Makes sure controllers can have access to session
func (application *Application) ApplySessions(c *web.C, h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
session, _ := application.Store.Get(r, "session")
c.Env["Session"] = session
h.ServeHTTP(w, r)
context.Clear(r)
}
return http.HandlerFunc(fn)
}
// Makes sure controllers can have access to the database
func (application *Application) ApplyDatabase(c *web.C, h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
session := application.DBSession.Clone()
defer session.Close()
c.Env["DBSession"] = session
c.Env["DBName"] = application.Configuration.Database.Database
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func (application *Application) ApplyAuth(c *web.C, h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
session := c.Env["Session"].(*sessions.Session)
if userId, ok := session.Values["User"].(bson.ObjectId); ok {
dbSession := c.Env["DBSession"].(*mgo.Session)
database := dbSession.DB(c.Env["DBName"].(string))
user := new(models.User)
err := database.C("users").Find(bson.M{"_id": userId}).One(&user)
if err != nil {
glog.Warningf("Auth error: %v", err)
c.Env["User"] = nil
} else {
c.Env["User"] = user
}
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}