-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserUpdater.go
More file actions
61 lines (47 loc) · 1.34 KB
/
Copy pathuserUpdater.go
File metadata and controls
61 lines (47 loc) · 1.34 KB
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
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"github.com/gorilla/mux"
)
type UserUpdaterService struct {
store Store
}
func NewUserUpdaterService(s *Store) *UserUpdaterService {
return &UserUpdaterService{store: *s}
}
func (s *UserUpdaterService) RegisterRouters(r *mux.Router) {
r.HandleFunc("/user/language", WithJWTAuth(s.handleLanguageSetter, s.store)).Methods("POST")
}
func (s *UserUpdaterService) handleLanguageSetter(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var payload map[string]interface{}
err = json.Unmarshal(body, &payload)
if err != nil {
http.Error(w, "Error unmarshaling JSON", http.StatusBadRequest)
return
}
if payload["native"] == nil || payload["learning"] == nil {
http.Error(w, "JSON Data is invalid", http.StatusBadRequest)
return
}
claims, err := GetTokenData(GetTokenFromRequest(r))
if err != nil {
permissionDenied(w)
return
}
isUpdated, err := s.store.UpdateUserLangs(claims["userID"].(string), payload["native"].(string), payload["learning"].(string))
if err != nil || !isUpdated {
log.Print(err)
http.Error(w, "MySQL Error", http.StatusBadRequest)
return
}
WriteJSON(w, http.StatusOK, make(map[string]interface{}))
}