-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
319 lines (286 loc) · 8.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package main
import (
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"os/exec"
"strconv"
"time"
"github.com/boltdb/bolt"
"github.com/julienschmidt/httprouter"
)
// TODO add bcrypt
func init() {
// Handles db/bucket creation
db, err := bolt.Open("goblog.db", 0600, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("UsersBucket")) // email -> password
if err != nil {
return fmt.Errorf("Error with UsersBucket: %s", err)
}
return nil
})
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("CookieBucket")) // random string -> email
if err != nil {
return fmt.Errorf("Error with CookieBucket: %s", err)
}
return nil
})
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("BlogMappingBucket")) // random string -> email
if err != nil {
return fmt.Errorf("Error with BlogMappingBucket: %s", err)
}
return nil
})
}
func LoginPage(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
baseT := template.Must(template.New("base").Parse(base))
baseT = template.Must(baseT.Parse(login))
baseT.ExecuteTemplate(w, "base", map[string]string{
"PageName": "login",
"User": getUser(w, req),
})
}
func LoginHandler(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
email := req.FormValue("email")
password := req.FormValue("password")
if verifyUser(w, req, email, password) {
http.Redirect(w, req, "/admin/", http.StatusFound)
} else {
fmt.Fprintf(w, "Invalid email/password")
}
}
func LogoutHandler(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
cookie, err := req.Cookie("goblog")
if err != nil {
fmt.Println(err)
}
delete := http.Cookie{Name: "goblog", Value: "delete", Expires: time.Now(), HttpOnly: true, Path: "/"}
http.SetCookie(w, &delete)
db, err := bolt.Open("goblog.db", 0600, nil)
if err != nil {
fmt.Println(err)
}
defer db.Close()
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("CookieBucket"))
err := b.Delete([]byte(cookie.Value))
return err
})
http.Redirect(w, req, "/", http.StatusFound)
}
func MainPage(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
baseT := template.Must(template.New("base").Parse(base))
baseT = template.Must(baseT.Parse(mainPage))
baseT.ExecuteTemplate(w, "base", map[string]string{
"PageName": "main",
"User": getUser(w, r),
})
}
func SignupPage(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
baseT := template.Must(template.New("base").Parse(base))
baseT = template.Must(baseT.Parse(signup))
baseT.ExecuteTemplate(w, "base", map[string]string{
"PageName": "signup",
"User": getUser(w, r),
})
}
func SignupHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
email := r.FormValue("email")
password := r.FormValue("password")
if addUser(email, password) {
cookie := http.Cookie{Name: "goblog", Value: RandomString(), Expires: time.Now().Add(time.Hour * 24 * 7 * 52), HttpOnly: true, MaxAge: 50000, Path: "/"}
http.SetCookie(w, &cookie)
db, err := bolt.Open("goblog.db", 0600, nil)
if err != nil {
fmt.Println(err)
}
defer db.Close()
if err != nil {
fmt.Println(err)
}
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("CookieBucket"))
err = b.Put([]byte(cookie.Value), []byte(email))
return err
})
if err != nil {
fmt.Println(err)
}
http.Redirect(w, r, "/admin/", http.StatusFound)
} else {
fmt.Println("Failure!")
http.Redirect(w, r, "/signup/", http.StatusFound)
}
}
func AdminPage(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if getUser(w, r) != "" {
baseT := template.Must(template.New("base").Parse(base))
baseT = template.Must(baseT.Parse(admin))
baseT.ExecuteTemplate(w, "base", map[string]string{
"PageName": "admin",
"User": getUser(w, r),
})
} else {
fmt.Fprintf(w, "You must be authenticated!") // TODO make this look better
}
}
func AdminHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
blogname := r.FormValue("blogname") // <- subdomain
website := blogname + ".goblog.pw" // Change this
port := rand.Intn(63000) + 2000
blogcheck := []byte("")
if getUser(w, r) != "" {
db, err := bolt.Open("goblog.db", 0600, nil)
if err != nil {
fmt.Println(err)
}
defer db.Close()
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("BlogMappingBucket"))
blogcheck = b.Get([]byte(blogname))
return nil
})
if blogcheck == nil {
create, err := exec.Command("./create.sh", blogname, strconv.Itoa(port)).Output()
if err != nil {
fmt.Println(err)
} else {
fmt.Println("80 -> " + strconv.Itoa(port))
fmt.Fprintf(w, "%s", create)
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("UsersBucket"))
err := b.Put([]byte(blogname), []byte(website)) // <- TODO change this
return err
})
}
} else {
fmt.Fprintf(w, "Failure creating blog! Please choose a different name!")
}
} else {
fmt.Fprintf(w, "You must be authenticated!") // TODO make this look better
}
}
func verifyUser(w http.ResponseWriter, r *http.Request, email string, password string) bool {
correctpass := []byte("")
db, err := bolt.Open("goblog.db", 0600, nil)
if err != nil {
fmt.Println(err)
}
defer db.Close()
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("UsersBucket"))
correctpass = b.Get([]byte(email))
return nil
})
if password == string(correctpass) {
cookie := http.Cookie{Name: "goblog", Value: RandomString(), Expires: time.Now().Add(time.Hour * 24 * 7 * 52), HttpOnly: true, MaxAge: 50000, Path: "/"}
http.SetCookie(w, &cookie)
if err != nil {
fmt.Println(err)
}
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("CookieBucket"))
err = b.Put([]byte(cookie.Value), []byte(email))
return err
})
if err != nil {
fmt.Println(err)
}
return true
}
return false
}
func addUser(email string, password string) bool {
check := []byte("")
db, err := bolt.Open("goblog.db", 0600, nil)
if err != nil {
fmt.Println(err)
}
defer db.Close()
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("UsersBucket"))
check = b.Get([]byte(email))
return nil
})
if check == nil {
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("UsersBucket"))
err := b.Put([]byte(email), []byte(password))
return err
})
return true
} else {
return false
}
}
// http://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
var src = rand.NewSource(time.Now().UnixNano())
func RandomString() string {
b := make([]byte, 20)
for i, cache, remain := 20-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
func getUser(w http.ResponseWriter, r *http.Request) string {
cookie, err := r.Cookie("goblog")
if err != nil {
fmt.Println(err) // No cookie
}
if cookie != nil {
return getUserFromCookie(cookie.Value)
}
return ""
}
func getUserFromCookie(value string) string {
servervalue := []byte("")
db, err := bolt.Open("goblog.db", 0600, nil)
if err != nil {
fmt.Println(err)
}
defer db.Close()
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("CookieBucket"))
servervalue = b.Get([]byte(value))
return nil
})
if servervalue != nil {
return string(servervalue)
}
return ""
}
func main() {
fmt.Println("Started server on port 1337")
router := httprouter.New()
router.GET("/", MainPage)
router.POST("/login/", LoginHandler)
router.GET("/signup/", SignupPage)
router.POST("/signup/", SignupHandler)
router.GET("/admin/", AdminPage)
router.POST("/admin/", AdminHandler)
router.GET("/logout/", LogoutHandler)
log.Fatal(http.ListenAndServe(":1337", router))
}