-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.go
More file actions
144 lines (125 loc) · 3.64 KB
/
Copy pathServer.go
File metadata and controls
144 lines (125 loc) · 3.64 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
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
package main
import (
"HighArch-dialogs/api"
"HighArch-dialogs/service"
"HighArch-dialogs/storage"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/gocql/gocql"
"github.com/google/uuid"
"log"
"net/http"
"strings"
"github.com/gorilla/mux"
)
type Server struct {
dialogService *service.DialogService
authService *service.AuthService
}
func NewServer(goCqlSession *gocql.Session) *Server {
dialogStore := storage.NewDialogStore(goCqlSession)
return &Server{
dialogService: service.NewDialogService(dialogStore),
}
}
func (s *Server) GetDialogListHandler(w http.ResponseWriter, req *http.Request) {
currentUserId, err := getUserIdFromContext(req.Context())
if err != nil {
http.Error(w, "", http.StatusUnauthorized)
return
}
peerId := mux.Vars(req)["user_id"]
res, err := s.dialogService.GetDialog(currentUserId, peerId)
if err != nil {
respondError(w, err)
} else {
renderJSON(w, res)
}
}
func (s *Server) GetSendMessageHandler(w http.ResponseWriter, req *http.Request) {
currentUserId, err := getUserIdFromContext(req.Context())
if err != nil {
http.Error(w, "", http.StatusUnauthorized)
return
}
var sendMessageModel api.DialogMessageSendApiModel
err = parseJSON(req, &sendMessageModel)
if err != nil { // validation error
println(err.Error())
w.WriteHeader(http.StatusBadRequest)
} else {
peerId := mux.Vars(req)["user_id"]
err := s.dialogService.AddDialogMessage(currentUserId, peerId, sendMessageModel.Text)
if err != nil {
respondError(w, err)
} else {
w.WriteHeader(http.StatusOK)
}
}
}
// Auth middleware methods
const userIdKey string = "user_id"
func (s *Server) GetAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("Authorization")
if tokenString == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
xRequestId := r.Header.Get(xRequestIdName)
tokenString = strings.Replace(tokenString, "Bearer ", "", 1)
userId, err := s.authService.Authenticate(tokenString, xRequestId)
if err != nil || userId == nil || *userId == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
println("Checked auth for user: " + *userId)
ctx := context.WithValue(r.Context(), userIdKey, *userId)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func getUserIdFromContext(ctx context.Context) (string, error) {
userId, ok := ctx.Value(userIdKey).(string)
if !ok {
return "", fmt.Errorf("user id not found in context")
}
return userId, nil
}
// X-Request-Id middleware methods
const xRequestIdName string = "X-Request-Id"
func (s *Server) GetXRequestIdMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
xRequestId := r.Header.Get(xRequestIdName)
if xRequestId == "" {
r.Header.Set(xRequestIdName, uuid.NewString())
}
next.ServeHTTP(w, r)
})
}
// Utils methods
func renderJSON(w http.ResponseWriter, v interface{}) {
js, err := json.Marshal(v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js) // TODO: should handle error???
}
func parseJSON(r *http.Request, v interface{}) error {
return json.NewDecoder(r.Body).Decode(v)
}
func respondError(w http.ResponseWriter, err error) {
log.Println(err)
if errors.Is(err, service.ErrorNotFound) {
w.WriteHeader(http.StatusNotFound)
} else if errors.Is(err, service.ErrorValidation) {
w.WriteHeader(http.StatusBadRequest)
} else if errors.Is(err, service.ErrorStoreError) {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
}