This repository has been archived by the owner on Apr 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshizuku.go
313 lines (277 loc) · 9.25 KB
/
shizuku.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
package main
import (
"github.com/gin-gonic/gin";
"github.com/gin-gonic/gin/binding";
"html/template"
"log"
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"os"
"io"
"net/http"
"strings"
"time"
"encoding/json"
)
type Nanika struct {
Name string
FileName string
HitCount int
Slug string
Password string //while we have the option to password files... security is not a focus.
Active bool
}
// Binding from form values
type NaniForm struct {
Name string `form:"name" binding:"optional"`
FileName string `form:"filename" binding:"optional"`
Slug string `form:"slug" binding:"optional"`
Password string `form:"password" binding:"optional"`
Active bool `form:"active" binding:"optional"`
}
var (
templateDelims = []string{"{{%", "%}}"}
IsDrop = false
//templates *template.Template
)
var Contains = func(list []string, elem string) bool {
for _, t := range list { if t == elem { return true } }
return false
}
func main() {
r := gin.Default()
html := template.Must(template.New("").Delims(templateDelims[0], templateDelims[1]).ParseFiles("./templates/index.tmpl","./templates/admin.tmpl", "./templates/passwordedFile.tmpl"))
r.SetHTMLTemplate(html)
r.Static("/assets","./public")
//setting up mongodb
session, err := mgo.Dial("localhost")
if (err != nil){
fmt.Println("Oh gosh!")
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
db := session.DB("shizuku").C("nanika")
index := mgo.Index{
Key: []string{"name", "slug"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err = db.EnsureIndex(index)
if err != nil {
panic(err)
}
// Drop Database if true
if IsDrop {
err = session.DB("shizuku").DropDatabase()
if err != nil {
panic(err)
}
//err = db.Insert(&Nanika{Name: "SomeName", FileName: "some/file/name",HitCount: 0, Slug: "Slugtest", Password: "password", Active: true},
//&Nanika{Name: "SomeOtherName", FileName: "some/other/file/name",HitCount: 200, Slug: "Slugtest2", Password: "password2", Active: false},
//&Nanika{Name: "SomeOther3Name", FileName: "some/other2/file/name",HitCount: 200, Slug: "Slugtest3", Password: "", Active: true})
//if err != nil {
// panic(err)
//}
}
r.GET("/", func(c *gin.Context) {
obj := gin.H{"title": "Apa!"}
c.HTML(200, "index.tmpl", obj)
})
r.GET("/f/:slug", func(c *gin.Context) {
ret := Nanika{}
fmt.Println("slug is: "+ c.Params.ByName("slug"))
err := db.Find(bson.M{"slug": c.Params.ByName("slug"), "active": true}).One(&ret)
if(err != nil){
fmt.Println("err finding slug")
c.Redirect(301, "/")
//return
}
if(ret.Password != ""){
obj := gin.H{"title": ret.Name}
c.HTML(200, "passwordedFile.tmpl", obj)
}else{
colQuerier := bson.M{"slug": c.Params.ByName("slug")}
change := bson.M{"$set": bson.M{"hitcount": ret.HitCount+1}}
err = db.Update(colQuerier, change)
if err != nil {
panic(err)
}
http.ServeFile(c.Writer, c.Request, "./uploaded/"+ret.FileName)
}
//c.HTML(200, "index.tmpl", obj)
})
r.POST("/f/:slug", func(c *gin.Context) {
ret := Nanika{}
fmt.Println("slug is: "+ c.Params.ByName("slug"))
err := db.Find(bson.M{"slug": c.Params.ByName("slug"), "active": true}).One(&ret)
if(err != nil){
fmt.Println("err finding slug")
c.Redirect(301, "/")
return
}
var form NaniForm
c.BindWith(&form, binding.Form)
fmt.Println(form.Password)
if(ret.Password != form.Password){
obj := gin.H{"title": "bad password for file " +ret.Name}
c.HTML(200,"passwordedFile.tmpl", obj)
return
}
colQuerier := bson.M{"slug": c.Params.ByName("slug")}
change := bson.M{"$set": bson.M{"hitcount": ret.HitCount+1}}
err = db.Update(colQuerier, change)
if err != nil {
panic(err)
}
http.ServeFile(c.Writer, c.Request, "./uploaded/"+ret.FileName)
//c.HTML(200, "index.tmpl", obj)
})
// Group using gin.BasicAuth() middleware
// gin.Accounts is a shortcut for map[string]string
if(os.Getenv("SHIZUKU_PASSWORD") == ""){
fmt.Println("Unable to find env var for SHIZUKU_PASSWORD")
return
}
authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
"apa": os.Getenv("SHIZUKU_PASSWORD"), //TODO make this run from env var
}))
//Page we upload from
authorized.GET("/", func(c *gin.Context){
//user := c.MustGet(gin.AuthUserKey).(string)
obj := gin.H{"title": "Shizuku Administration", "content": "testing content. This is what content will look like I guess?"}
c.HTML(200, "admin.tmpl", obj)
})
authorized.GET("/files", func(c *gin.Context){
results := []Nanika{}
err := db.Find(nil).All(&results)
if( err != nil){
fmt.Println("We had an issue with getting all the files")
log.Fatal(err)
}
c.JSON(200, results)
})
authorized.PUT("/file", func(c *gin.Context){
defer c.Request.Body.Close()
var v NaniForm
if err := json.NewDecoder(c.Request.Body).Decode(&v); err != nil {
panic(err)
}
fmt.Println(v)
colQuerier := bson.M{"filename": v.FileName}
change := bson.M{"$set": bson.M{"slug": v.Slug, "name": v.Name, "active": v.Active, "password": v.Password}}
err = db.Update(colQuerier, change)
if err != nil {
panic(err)
}
c.JSON(200, gin.H{"ok": "Updated"})
})
authorized.DELETE("/file", func(c *gin.Context){
//TODO find file
defer c.Request.Body.Close()
var v NaniForm
if err := json.NewDecoder(c.Request.Body).Decode(&v); err != nil {
panic(err)
}
fmt.Println(v)
//remove record from db
colQuerier := bson.M{"filename": v.FileName}
//change := bson.M{"$set": bson.M{"slug": v.Slug, "name": v.Name, "active": v.Active, "password": v.Password}}
err = db.Remove(colQuerier)
if err != nil {
panic(err)
c.JSON(500, gin.H{"ok": "trouble deleting file from db"})
return
}
//delete file
err = os.Remove(v.FileName)
if err != nil {
panic(err)
c.JSON(500, gin.H{"ok": "trouble deleting file from system"})
return
}
c.JSON(200, gin.H{"ok": "Deleted"})
})
//where the file goes~
authorized.POST("/upload", func(c *gin.Context){
file, header, err := c.Request.FormFile("file")
if( err != nil){
panic(err)
}
defer file.Close()
buff := make([]byte, 512) // see http://golang.org/pkg/net/http/#DetectContentType
_, err = file.Read(buff)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
file.Seek(0,0) //because Read offsets our copy
filetype := http.DetectContentType(buff)
acceptableTypes := []string{"image/jpeg",
"image/jpg",
"image/gif",
"image/png",
"image/bmp",
"image/gif",
"audio/x-wav",
"audio/mpeg",
"audio/mid",
"application/pdf",
"application/zip",
"application/x-javascript",
"text/plain"}
if(!Contains(acceptableTypes, filetype)){
c.JSON(200, gin.H{"ok":"Bad filetype"})
return
}
sfn := strings.Split(header.Filename,".")
t := time.Now()
internFileName := sfn[0] + "-" + fmt.Sprintf("%d",t.Year()) + "-" + fmt.Sprintf("%d",t.Month()) +"-"+ fmt.Sprintf("%d",t.Day()) + "." + sfn[len(sfn)-1]
sfn = strings.Split(internFileName,".") //because I want to reuse for slugname
//ensure file doesn't exist
if _, err := os.Stat("./uploaded/"+internFileName); err == nil {
fmt.Printf("file exists; processing...")
c.JSON(500, gin.H{"ok":"file already exists"})
return
}
//create a temp file
outFile, err := os.Create("./uploaded/"+internFileName)
if( err != nil){
fmt.Println("Unable to create a file, check privilages")
c.JSON(500, gin.H{"ok":"nope, couldn't make it"})
return
}
defer outFile.Close()
//copy the data into temp file
_, err = io.Copy(outFile, file)
if( err != nil){
fmt.Println(err)
c.JSON(500, gin.H{"ok":"couldn't copy"})
return
}
//other form vals
var form NaniForm
c.BindWith(&form, binding.Form)
//create database entry
nani := Nanika{
Name: form.Name,
FileName: internFileName,
HitCount: 0,
Slug: sfn[0], //should just be filename without ext
Password: form.Password,
Active: form.Active,
}
err = db.Insert(&nani)
if err != nil {
fmt.Println(err)
c.JSON(500, gin.H{"ok":"error saving to db"})
return
}
c.JSON(200, gin.H{"ok":"seemed to make it through " + nani.FileName})
})
// Listen and server on 0.0.0.0:8080
r.Run(":8080")
}