-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
206 lines (183 loc) · 5.76 KB
/
handler.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"regexp"
"time"
jwt "github.com/form3tech-oss/jwt-go"
"github.com/gorilla/mux"
"github.com/pborman/uuid"
)
var (
mediaTypes = map[string]string{
".jpeg": "image",
".jpg": "image",
".gif": "image",
".png": "image",
".mov": "video",
".mp4": "video",
".avi": "video",
".flv": "video",
".wmv": "video",
}
)
var mySigningKey = []byte("secret")
// handle upload request
func uploadHandler(w http.ResponseWriter, r *http.Request) {
// parse from body of request to get a json object
fmt.Println("Received one post request")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
if r.Method == "OPTIONS" {
return
}
user := r.Context().Value("user")
claims := user.(*jwt.Token).Claims
username := claims.(jwt.MapClaims)["username"]
p := Post{
Id: uuid.New(),
User: username.(string),
Message: r.FormValue("message"),
}
file, header, err := r.FormFile("media_file")
if err != nil {
http.Error(w, "Media file is not available", http.StatusBadRequest)
fmt.Printf("Media file is not available %v\n", err)
return
}
suffix := filepath.Ext(header.Filename)
if t, ok := mediaTypes[suffix]; ok {
p.Type = t
} else {
p.Type = "unknown"
}
err = savePost(&p, file)
if err != nil {
http.Error(w, "Failed to save post to GCS or Elasticsearch", http.StatusInternalServerError)
fmt.Printf("Failed to save post to GCS or Elasticsearch %v\n", err)
return
}
fmt.Println("Post is saved successfully.")
}
func searchHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one request for search")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
w.Header().Set("Content-Type", "application/json")
if r.Method == "OPTIONS" {
return
}
user := r.URL.Query().Get("user")
keywords := r.URL.Query().Get("keywords")
var posts []Post
var err error
if user != "" {
posts, err = searchPostsByUser(user)
} else {
posts, err = searchPostsByKeywords(keywords)
}
if err != nil {
http.Error(w, "Failed to read post from Elasticsearch", http.StatusInternalServerError)
fmt.Printf("Failed to parse posts into JSON format %v.\n", err)
return
}
js, err := json.Marshal(posts)
if err != nil {
http.Error(w, "Failed to parse posts into JSON format", http.StatusInternalServerError)
fmt.Printf("Failed to parse posts into JSON format %v.\n", err)
return
}
w.Write(js)
}
func deleteHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one delete for search")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
if r.Method == "OPTIONS" {
return
}
user := r.Context().Value("user")
claims := user.(*jwt.Token).Claims
username := claims.(jwt.MapClaims)["username"].(string)
id := mux.Vars(r)["id"]
if err := deletePost(id, username); err != nil {
http.Error(w, "Failed to delete post from Elasticsearch", http.StatusInternalServerError)
fmt.Printf("Failed to delete post from Elasticsearch %v\n", err)
return
}
fmt.Println("Post is deleted successfully")
}
func signinHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one signin request")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == "OPTIONS" {
return
}
// Get User information from client
decoder := json.NewDecoder(r.Body)
var user User
if err := decoder.Decode(&user); err != nil {
http.Error(w, "Cannot decode user data from client", http.StatusBadRequest)
fmt.Printf("Cannot decode user data from client %v\n", err)
return
}
exists, err := checkUser(user.Username, user.Password)
if err != nil {
http.Error(w, "Failed to read user from Elasticsearch", http.StatusInternalServerError)
fmt.Printf("Failed to read user from Elasticsearch %v\n", err)
return
}
if !exists {
http.Error(w, "User doesn't exists or wrong password", http.StatusUnauthorized)
fmt.Printf("User doesn't exists or wrong password\n")
return
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username,
"exp": time.Now().Add(time.Hour * 24).Unix(),
})
tokenString, err := token.SignedString(mySigningKey)
if err != nil {
http.Error(w, "Failed to generate token", http.StatusInternalServerError)
fmt.Printf("Failed to generate token %v\n", err)
return
}
w.Write([]byte(tokenString))
}
func signupHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one signup request")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == "OPTIONS" {
return
}
decoder := json.NewDecoder(r.Body)
var user User
if err := decoder.Decode(&user); err != nil {
http.Error(w, "Cannot decode user data from client", http.StatusBadRequest)
fmt.Printf("Cannot decode user data from client %v\n", err)
return
}
if user.Username == "" || user.Password == "" || regexp.MustCompile(`^[a-z0-9]$`).MatchString(user.Username) {
http.Error(w, "Invalid username or password", http.StatusBadRequest)
fmt.Printf("Invalid username or password\n")
return
}
success, err := addUser(&user)
if err != nil {
http.Error(w, "Failed to save user to Elasticsearch", http.StatusInternalServerError)
fmt.Printf("Failed to save user to Elasticsearch %v\n", err)
return
}
if !success {
http.Error(w, "User already exists", http.StatusBadRequest)
fmt.Println("User already exists")
return
}
fmt.Printf("User added successfully: %s.\n", user.Username)
}