-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
238 lines (185 loc) · 5.18 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"github.com/go-martini/martini"
"github.com/martini-contrib/binding"
"github.com/odeke-em/extractor"
uuid "github.com/odeke-em/go-uuid"
"github.com/odeke-em/meddler"
"github.com/odeke-em/qr-server/models"
"github.com/odeke-em/rsc/qr"
)
const (
ENV_DRIVE_SERVER_PUB_KEY = "DRIVE_SERVER_PUB_KEY"
ENV_DRIVE_SERVER_PRIV_KEY = "DRIVE_SERVER_PRIV_KEY"
ENV_DRIVE_SERVER_PORT = "DRIVE_SERVER_PORT"
ENV_DRIVE_SERVER_HOST = "DRIVE_SERVER_HOST"
ENV_DBNAME = "DBNAME"
ENV_RESTRICT_DOMAINS = "RESTRICT_DOMAINS"
DefaultMongoURI = "mongodb://localhost:27017"
DefaultPort = "4040"
)
var envKeyAlias = &extractor.EnvKey{
PubKeyAlias: ENV_DRIVE_SERVER_PUB_KEY,
PrivKeyAlias: ENV_DRIVE_SERVER_PRIV_KEY,
}
type addressInfo struct {
port, host string
}
func envGet(varname string, placeholders ...string) string {
v := os.Getenv(varname)
if v == "" {
for _, placeholder := range placeholders {
if placeholder != "" {
v = placeholder
break
}
}
}
return v
}
func mongoURI() string {
uri := os.Getenv("MONGOHQ_URI")
if uri == "" {
uri = DefaultMongoURI
}
return uri
}
func addressInfoFromEnv() *addressInfo {
return &addressInfo{
port: envGet(ENV_DRIVE_SERVER_PORT, "3000"),
host: envGet(ENV_DRIVE_SERVER_HOST, "localhost"),
}
}
var envKeySet = extractor.KeySetFromEnv(envKeyAlias)
var envAddrInfo = addressInfoFromEnv()
var envDbName = envGet(ENV_DBNAME, models.DbName)
func (ai *addressInfo) ConnectionString() string {
// TODO: ensure fields meet rubric
return fmt.Sprintf("%s:%s", ai.host, ai.port)
}
func main() {
m := martini.Classic()
if envGet(ENV_RESTRICT_DOMAINS) == "" {
m.Get("/qr", binding.Bind(meddler.Payload{}), presentQRCode)
m.Post("/qr", binding.Bind(meddler.Payload{}), presentQRCode)
}
m.Get("/drive/qr", binding.Bind(meddler.Payload{}), googleDriveDomainRestrictedQRCode)
m.Post("/drive/qr", binding.Bind(meddler.Payload{}), googleDriveDomainRestrictedQRCode)
// m.Post("/gen", GenerateKeySet)
m.Run() // m.RunOnAddr(envAddrInfo.ConnectionString())
}
func sessionHandler(fn func(*mgo.Session) (interface{}, error)) (interface{}, error) {
uri := mongoURI()
session, sErr := mgo.Dial(uri)
if sErr == nil {
defer session.Close()
session.SetSafe(&mgo.Safe{})
}
result, err := fn(session)
return result, err
}
func lookUpKeySet(publicKey string) (*extractor.KeySet, error) {
result, err := sessionHandler(func(session *mgo.Session) (interface{}, error) {
collection := session.DB(envDbName).C(models.KeySetModelName)
result := models.KeySet{}
if qErr := collection.Find(bson.M{"publickey": publicKey}).One(&result); qErr != nil {
return nil, qErr
}
ks := &extractor.KeySet{
PublicKey: result.PublicKey,
PrivateKey: result.PrivateKey,
}
return ks, nil
})
ks, _ := result.(*extractor.KeySet)
return ks, err
}
func GenerateKeySet(res http.ResponseWriter, req *http.Request) {
ks, err := _generateKeySet()
if err != nil {
fmt.Fprintf(os.Stderr, "%v error: %v\n", time.Now().UTC(), err)
fmt.Fprintf(res, "error encountered please try again!")
return
}
marshalled, err := json.Marshal(ks)
var result interface{} = string(marshalled)
if err != nil {
result = err
}
fmt.Fprintf(res, "%v\n", result)
}
func newUUID4Joined() string {
return strings.Replace(uuid.NewRandom().String(), "-", "", -1)
}
func newKeySet() *models.KeySet {
ks := &models.KeySet{
PublicKey: newUUID4Joined(),
PrivateKey: newUUID4Joined(),
}
ks.Init()
return ks
}
func _generateKeySet() (*models.KeySet, error) {
result, err := sessionHandler(func(session *mgo.Session) (interface{}, error) {
ks := newKeySet()
collection := session.DB(envDbName).C(models.KeySetModelName)
index := mgo.Index{
Key: []string{"privatekey", "publickey"},
Unique: true,
Background: false, // TODO: check if blocking will affect speed
}
indexErr := collection.EnsureIndex(index)
if indexErr != nil {
return nil, indexErr
}
ks.PreSave()
err := collection.Insert(ks)
if err != nil {
return nil, err
}
return ks, nil
})
mks, _ := result.(*models.KeySet)
return mks, err
}
func presentQRCode(pl meddler.Payload, res http.ResponseWriter, req *http.Request) {
foundKeySet, err := lookUpKeySet(pl.PublicKey)
if err != nil {
http.Error(res, fmt.Sprintf("encountered error: %v", err), 400)
return
}
if foundKeySet == nil {
panic("null keySet returned from publicKeyLookup")
}
rawTextForSigning := pl.RawTextForSigning()
if !foundKeySet.Match([]byte(rawTextForSigning), []byte(pl.Signature)) {
http.Error(res, "invalid signature", 403)
return
}
curTimeUnix := time.Now().Unix()
if pl.ExpiryTime < curTimeUnix {
http.Error(res, fmt.Sprintf("request expired at %q, current time %q", pl.ExpiryTime, curTimeUnix), 403)
return
}
uri := pl.URI
code, err := qr.Encode(uri, qr.Q)
if err != nil {
fmt.Fprintf(res, "%s %v\n", uri, err)
return
}
pngImage := code.PNG()
fmt.Fprintf(res, "%s", pngImage)
}
func errorPrint(fmt_ string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "\033[31m")
fmt.Fprintf(os.Stderr, fmt_, args...)
fmt.Fprintf(os.Stderr, "\033[00m")
}