-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
163 lines (139 loc) · 3.52 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package main
import (
"database/sql"
"encoding/json"
"html/template"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/codegangsta/martini"
"github.com/coopernurse/gorp"
jwt "github.com/dgrijalva/jwt-go"
"github.com/jmcvetta/randutil"
_ "github.com/lib/pq"
"github.com/phaikawl/prognet/biz"
"github.com/pilu/fresh/runner/runnerutils"
)
const (
mySigningKey = "n0t9r34t6cz9r34tn0t1na9r34tw4y"
)
var (
g *Environment = environment()
)
type Environment struct {
devMode bool
dbMap *gorp.DbMap
}
func environment() *Environment {
return &Environment{
dbMap: nil,
devMode: true,
}
}
func (g *Environment) IsDevMode() bool {
return g.devMode
}
func (g *Environment) InitDb() {
// connect to db using standard Go database/sql API
// use whatever database/sql driver you wish
db, err := sql.Open("postgres", "postgres://postgres:thebest1om@localhost:5432/prognet")
errPanic(err, "sql.Open failed")
// construct a gorp DbMap
g.dbMap = &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}
g.dbMap.AddTableWithName(biz.Post{}, "posts").SetKeys(true, "Id")
g.dbMap.AddTableWithName(biz.User{}, "users").SetKeys(true, "Id")
// create the table. in a production system you'd generally
// use a migration tool, or create the tables via scripts
err = g.dbMap.CreateTablesIfNotExists()
errPanic(err, "Create tables failed")
}
func (g *Environment) Db() *gorp.DbMap {
if g.dbMap == nil {
panic("Trying to get an uninitialized dbmap")
}
return g.dbMap
}
func errPanic(err error, message string) {
if err != nil {
if message == "" {
message = err.Error()
}
log.Printf(message)
if g.IsDevMode() {
panic(err.Error())
}
}
}
func checkErr(err error) {
errPanic(err, "")
}
func makeRandomUserToken() (username string, tokenString string) {
token := jwt.New(jwt.GetSigningMethod("HS256"))
username, err := randutil.AlphaStringRange(5, 10)
errPanic(err, "Cannot random string, wtf?")
token.Claims["username"] = username
token.Claims["secret"] = time.Now().Add(time.Hour * 72).Unix()
tokenString, err = token.SignedString([]byte(mySigningKey))
errPanic(err, "Cannot sign string, wtf?")
return
}
func runnerMiddleware(w http.ResponseWriter, r *http.Request) {
if runnerutils.HasErrors() {
runnerutils.RenderError(w)
}
}
func main() {
m := martini.Classic()
if os.Getenv("MARTINI_ENV") == "production" {
g.devMode = false
}
if g.IsDevMode() {
m.Use(runnerMiddleware)
}
g.InitDb()
m.Use(martini.Static("public/app"))
m.Use(func(resp http.ResponseWriter, req *http.Request) {
if strings.HasPrefix(req.URL.Path, "/api/") {
token := req.Header.Get("AuthToken")
if token != "" {
n, err := g.Db().SelectInt(`select count(*) from users where token=$1`, token)
if err != nil && err != sql.ErrNoRows {
log.Fatalf(err.Error())
}
if n > 0 {
return
}
}
resp.WriteHeader(http.StatusUnauthorized)
resp.Write([]byte("You're not allowed to do this, sorry."))
}
})
m.Get("/", func(r http.ResponseWriter) {
t, err := template.ParseFiles("public/app/index.html")
if err != nil {
panic(err.Error())
}
t.Execute(r, nil)
})
m.Get("/auth", func(r http.ResponseWriter) {
username, token := makeRandomUserToken()
user := &biz.User{
Username: username,
Token: token,
Role: biz.RoleUser,
}
checkErr(g.Db().Insert(user))
resp, err := json.Marshal(map[string]interface{}{
"username": user.Username,
"token": user.Token,
})
checkErr(err)
r.Write(resp)
})
m.Get("/api/test", func(r http.ResponseWriter) {
r.Write([]byte("CLGT"))
})
m.Run()
}