This repository has been archived by the owner on Dec 2, 2018. It is now read-only.
/
adtest.go
99 lines (82 loc) · 2.05 KB
/
adtest.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 main
import (
"github.com/zeebo/admin"
"launchpad.net/gobson/bson"
"launchpad.net/mgo"
"log"
"net/http"
"os"
"time"
)
var (
session *mgo.Session
)
func init() {
var err error
session, err = mgo.Mongo(Env("MONGO_URL", "localhost"))
if err != nil {
log.Fatal(err)
}
}
func Env(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
type Time int64
func (t Time) String() string {
return time.Unix(0, int64(t)).String()
}
func Auth(req *http.Request) (resp admin.AuthResponse) {
req.ParseForm()
username, password := req.Form.Get("Username"), req.Form.Get("Password")
var valid User
if err := session.DB("blog").C("User").Find(bson.M{"username": username}).One(&valid); err != nil {
resp.Error = "Invalid username and/or password. Please try again."
return
}
if !valid.ID.Valid() {
resp.Error = "Invalid username and/or password. Please try again."
return
}
if valid.Compare(password) {
resp.Passed = true
resp.Username = valid.Username
resp.Key = valid.ID
} else {
resp.Error = "Invalid username and/or password. Please try again."
}
return
}
type LoggingWrapper struct {
Handler http.Handler
}
func (l *LoggingWrapper) ServeHTTP(w http.ResponseWriter, req *http.Request) {
now, path := time.Now(), req.URL.RawPath
l.Handler.ServeHTTP(w, req)
later := time.Now()
log.Printf("[%s:%s] %s", req.Method, path, later.Sub(now))
}
func main() {
a := &admin.Admin{
Session: session,
Prefix: "/admin",
Auth: admin.AuthFunc(Auth),
}
a.Register(&Post{}, "blog.Post", &admin.Options{
Columns: []string{"Title", "Body", "Posted", "Updated"},
})
a.Register(&User{}, "blog.User", &admin.Options{
Columns: []string{"Username", "Password"},
})
a.Init()
static := http.FileServer(http.Dir(Env("STATIC_DIR", "static")))
//setup handlers
http.Handle("/admin/", &LoggingWrapper{a})
http.Handle("/static/", http.StripPrefix("/static/", static))
//http.Handle("/", http.HandleFunc(blog))
if err := http.ListenAndServe(Env("BIND_ADDR", ":11223"), nil); err != nil {
log.Fatal(err)
}
}