/
auth.go
190 lines (175 loc) · 5.65 KB
/
auth.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
package handlers
import (
"encoding/json"
"fmt"
"net/http"
"serverside-final-project/servers/gateway/models/users"
"serverside-final-project/servers/gateway/sessions"
"strconv"
"strings"
"time"
)
// UsersHandler creates new user accounts
func (hc *Context) UsersHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
contentType := r.Header.Get("Content-type")
if strings.HasPrefix(contentType, "application/json") {
newUser := &users.NewUser{}
dec := json.NewDecoder(r.Body)
if err := dec.Decode(newUser); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err := newUser.Validate()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
user, _ := newUser.ToUser()
insertedUser, err := hc.UserStore.Insert(user)
if err != nil {
fmt.Printf("Error inserting user into database: %v\n", err)
}
sessionState := NewSessionState(time.Now(), insertedUser)
_, sessionErr := sessions.BeginSession(hc.SessionIDKey, hc.SessionStore, sessionState, w)
if sessionErr != nil {
fmt.Printf("Error creating session: %v\n", err)
return
}
w.WriteHeader(http.StatusCreated)
w.Header().Set("Content-Type", "application/json")
userJSON, _ := json.Marshal(insertedUser)
w.Write(userJSON)
} else {
w.WriteHeader(http.StatusUnsupportedMediaType)
w.Write([]byte("Request body must be in JSON"))
}
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
// SpecificUserHandler handle requests for specific user
func (hc *Context) SpecificUserHandler(w http.ResponseWriter, r *http.Request) {
_, err := sessions.GetSessionID(r, hc.SessionIDKey)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
if r.Method == http.MethodGet {
URL := r.URL.RequestURI()
i := strings.LastIndex(URL, "/")
var idValue int64
var UserID string = URL[i+1 : len(URL)]
if UserID == "me" {
sessionState := &SessionState{}
sessions.GetState(r, hc.SessionIDKey, hc.SessionStore, sessionState)
user := sessionState.User
idValue = user.ID
} else {
idValue, _ = strconv.ParseInt(UserID, 10, 64)
}
user, err := hc.UserStore.GetByID(idValue)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
userJSON, _ := json.Marshal(user)
w.Write(userJSON)
} else if r.Method == http.MethodPatch {
URL := r.URL.RequestURI()
i := strings.LastIndex(URL, "/")
UserID := URL[i+1 : len(URL)]
sessionState := &SessionState{}
sessions.GetState(r, hc.SessionIDKey, hc.SessionStore, sessionState)
if UserID != "me" {
userID, _ := strconv.ParseInt(UserID, 10, 64)
if userID != sessionState.User.ID {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("Invalid UserID"))
return
}
}
contentType := r.Header.Get("Content-type")
if !strings.HasPrefix(contentType, "application/json") {
w.WriteHeader(http.StatusUnsupportedMediaType)
w.Write([]byte("Request body must be in JSON"))
return
}
updates := &users.Updates{}
dec := json.NewDecoder(r.Body)
if err := dec.Decode(updates); err != nil {
fmt.Printf("error decoding JSON: %v\n", err)
return
}
sessionState.User.ApplyUpdates(updates)
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
userJSON, _ := json.Marshal(sessionState.User)
w.Write(userJSON)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
// SessionsHandler handles requests for the "sessions" resource, and
// allows clients to begin a new session using an existing user's credentials.
func (hc *Context) SessionsHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
credentials := &users.Credentials{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(credentials); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
user, err := hc.UserStore.GetByEmail(credentials.Email)
if err != nil {
time.Sleep(time.Second)
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("invalid credentials"))
return
}
if user.Authenticate(credentials.Password) != nil {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("invalid credentials"))
return
}
sessionState := NewSessionState(time.Now(), user)
sessions.BeginSession(hc.SessionIDKey, hc.SessionStore, sessionState, w)
clientIP := r.Header.Get("X-Forwarded-For")
if len(clientIP) != 0 {
ipList := strings.Split(clientIP, ", ")
clientIP = ipList[0]
} else {
clientIP = r.RemoteAddr
}
hc.UserStore.LogUser(user.ID, sessionState.Time, clientIP)
w.WriteHeader(http.StatusCreated)
w.Header().Set("Content-Type", "application/json")
userJSON, _ := json.Marshal(user)
w.Write(userJSON)
} else {
w.WriteHeader(http.StatusUnsupportedMediaType)
w.Write([]byte("Request body must be in JSON"))
}
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
// SpecificSessionHandler handles requests related to a specific
// authenticated session
func (hc *Context) SpecificSessionHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete {
pathElements := strings.Split(r.URL.RequestURI(), "/")
if pathElements[len(pathElements)-1] != "mine" {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("Last element of URL must be mine, got " + pathElements[len(pathElements)-1]))
return
}
sessions.EndSession(r, hc.SessionIDKey, hc.SessionStore)
w.Write([]byte("Signed out"))
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}