-
Notifications
You must be signed in to change notification settings - Fork 13
/
routing.go
executable file
·213 lines (187 loc) · 5.73 KB
/
routing.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
jwt "github.com/dgrijalva/jwt-go"
httpext "github.com/go-playground/pkg/net/http"
"github.com/go-playground/pure"
)
type data map[string]interface{}
//Log writes in log if debug flag is set
func Log(v ...interface{}) {
if cfg.Debug {
log.Println(v...)
}
}
type sfError struct {
Message string `json:"message"`
Code int `json:"code"`
}
func showError(w http.ResponseWriter, err error, code int) {
log.Println(err)
pure.JSON(w, code, data{"error": sfError{err.Error(), code}})
}
func authenticateUser(r *http.Request) (User, error) {
var user = NewUser()
authHeaderParts := strings.Split(r.Header.Get("Authorization"), " ")
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
return user, fmt.Errorf("Missing authorization header")
}
token, err := jwt.ParseWithClaims(authHeaderParts[1], &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return SigningKey, nil
})
if err != nil {
return user, err
}
if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
Log("Token is valid, claims: ", claims)
if ok := user.LoadByUUID(claims.UUID); !ok {
return user, fmt.Errorf("Unknown user")
}
if user.Validate(claims.PwHash) {
return user, nil
}
}
return user, fmt.Errorf("Invalid token")
}
//Dashboard - is the root handler
func Dashboard(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Dashboard. Server version: " + Version))
}
//ChangePassword - is the change password handler
func ChangePassword(w http.ResponseWriter, r *http.Request) {
user, err := authenticateUser(r)
if err != nil {
showError(w, err, http.StatusUnauthorized)
return
}
np := NewPassword{}
if err := pure.Decode(r, httpext.QueryParams, 104857600, &np); err != nil {
showError(w, err, http.StatusUnprocessableEntity)
return
}
if len(np.CurrentPassword) == 0 {
showError(w, fmt.Errorf("Your current password is required to change your password. Please update your application if you do not see this option."), http.StatusUnauthorized)
return
}
if _, err := user.Login(np.Email, np.CurrentPassword); err != nil {
showError(w, fmt.Errorf("The current password you entered is incorrect. Please try again."), http.StatusUnauthorized)
return
}
if err := user.UpdatePassword(np); err != nil {
showError(w, err, http.StatusInternalServerError)
return
}
// c.Code(http.StatusNoContent).Body("") //in spec, but SN requires token in return
token, err := user.Login(user.Email, user.Password)
if err != nil {
showError(w, err, http.StatusUnauthorized)
return
}
pure.JSON(w, http.StatusAccepted, data{"token": token, "user": user.ToJSON()})
}
//UpdateUser - updates user params
func UpdateUser(w http.ResponseWriter, r *http.Request) {
user, err := authenticateUser(r)
if err != nil {
showError(w, err, http.StatusUnauthorized)
return
}
p := Params{}
if err := pure.Decode(r, httpext.QueryParams, 104857600, &p); err != nil {
showError(w, err, http.StatusUnprocessableEntity)
return
}
Log("Request:", p)
if err := user.UpdateParams(p); err != nil {
showError(w, err, http.StatusInternalServerError)
return
}
pure.JSON(w, http.StatusAccepted, data{})
}
//Registration - is the registration handler
func Registration(w http.ResponseWriter, r *http.Request) {
var user = NewUser()
if err := pure.Decode(r, httpext.QueryParams, 104857600, &user); err != nil {
showError(w, err, http.StatusUnprocessableEntity)
return
}
Log("Request:", user)
token, err := user.Register()
if err != nil {
showError(w, err, http.StatusUnprocessableEntity)
return
}
pure.JSON(w, http.StatusCreated, data{"token": token, "user": user.ToJSON()})
}
//Login - is the login handler
func Login(w http.ResponseWriter, r *http.Request) {
var user = NewUser()
if err := pure.Decode(r, httpext.QueryParams, 104857600, &user); err != nil {
showError(w, err, http.StatusUnprocessableEntity)
return
}
Log("Request:", user)
token, err := user.Login(user.Email, user.Password)
if err != nil {
showError(w, err, http.StatusUnauthorized)
return
}
pure.JSON(w, http.StatusAccepted, data{"token": token, "user": user.ToJSON()})
}
//GetParams - is the get auth parameters handler
func GetParams(w http.ResponseWriter, r *http.Request) {
user := NewUser()
email := r.FormValue("email")
Log("Request:", string(email))
if email == "" {
showError(w, fmt.Errorf("Empty email"), http.StatusUnauthorized)
return
}
params := user.GetParams(email)
if _, ok := params["version"]; !ok {
showError(w, fmt.Errorf("Invalid email or password"), http.StatusNotFound)
return
}
content, _ := json.MarshalIndent(params, "", " ")
Log("Response:", string(content))
pure.JSON(w, http.StatusOK, params)
}
//SyncItems - is the items sync handler
func SyncItems(w http.ResponseWriter, r *http.Request) {
user, err := authenticateUser(r)
if err != nil {
showError(w, err, http.StatusUnauthorized)
return
}
var request SyncRequest
if err := pure.Decode(r, httpext.QueryParams, 104857600, &request); err != nil {
showError(w, err, http.StatusUnprocessableEntity)
return
}
Log("Request:", request)
response, err := user.SyncItems(request)
if err != nil {
showError(w, err, http.StatusInternalServerError)
return
}
content, _ := json.MarshalIndent(response, "", " ")
Log("Response:", string(content))
pure.JSON(w, http.StatusAccepted, response)
}
//BackupItems - export items
func BackupItems(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
showError(w, err, http.StatusInternalServerError)
return
}
fmt.Printf("%+v\n", r.Form)
}