-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsave.go
100 lines (92 loc) · 2.54 KB
/
save.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
package main
import (
"crypto/md5"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/albrow/forms"
)
// DataAndChecksumKeys are keys must be included in uploaded backup date
var DataAndChecksumKeys []string
func init() {
DataAndChecksumKeys = []string{
"scores", "clearlamps", "clearedsongs", "unlocklist",
"installid", "devicemodelname", "story", "version",
}
}
func returnBackup(w http.ResponseWriter, r *http.Request) {
var (
userID int
err error
)
if NeedAuth {
userID, err = verifyBearerAuth(r.Header.Get("Authorization"))
if err != nil {
c := Container{false, nil, 203}
http.Error(w, c.toJSON(), http.StatusUnauthorized)
return
}
} else {
userID = staticUserID
}
var data string
err = db.QueryRow(sqlStmtReadBackupData, userID).Scan(&data)
if err != nil {
log.Printf("%s: Error occured while querying table DATA_BACKUP for downloading data: %s\n", r.URL.Path, err)
} else if data == "" {
http.Error(w, `{"success":false,"error_code":402}`, http.StatusNotFound)
} else {
fmt.Fprintf(w, `{"success":true,"value":{"user_id":%d,%s}}`, userID, data)
}
}
func receiveBackup(w http.ResponseWriter, r *http.Request) {
var (
userID int
err error
)
if NeedAuth {
userID, err = verifyBearerAuth(r.Header.Get("Authorization"))
if err != nil {
c := Container{false, nil, 203}
http.Error(w, c.toJSON(), http.StatusUnauthorized)
return
}
} else {
userID = staticUserID
}
data, err := forms.Parse(r)
if err != nil {
log.Printf("%s: Error occured while parsing form: %s\n", r.URL.Path, err)
}
val := data.Validator()
for _, key := range DataAndChecksumKeys {
val.Require(key + "_data")
val.Require(key + "_checksum")
}
if val.HasErrors() {
log.Printf("%s: Data uploaded lacks of necessary key.\n", r.URL.Path)
for k, v := range val.ErrorMap() {
log.Printf("%s: %s", k, v)
}
}
results := []string{}
for _, key := range DataAndChecksumKeys {
content := data.Get(key + "_data")
checksum := data.Get(key + "_checksum")
sum := fmt.Sprintf("%x", md5.Sum([]byte(content)))
if string(sum) != checksum {
log.Printf("%s: Checksum check failed for key `%s`", r.URL.Path, key)
return
}
results = append(results, fmt.Sprintf(`"%s":%s`, key, content))
}
result := strings.Join(results, ",")
result = fmt.Sprintf(`%s,"createdAt":%d`, result, time.Now().Unix())
_, err = db.Exec(sqlStmtWriteBackupDate, result, userID)
if err != nil {
log.Printf("%s: Error occured while writing backup data: %s\n", r.URL.Path, err)
}
fmt.Fprintf(w, `{"success":true,"value":{"user_id":%d}}`, userID)
}