/
middleware.go
211 lines (179 loc) · 6.73 KB
/
middleware.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
package middleware
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/SENG-499-Company2-B01/Backend/logger"
"github.com/SENG-499-Company2-B01/Backend/modules/helper"
"github.com/SENG-499-Company2-B01/Backend/modules/users"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
func fetch_email(path string, collection *mongo.Collection) string {
username := strings.TrimPrefix(path, "/users/")
username = strings.TrimSpace(username)
filter := bson.M{"username": username}
var user users.User
err := collection.FindOne(context.TODO(), filter).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
// If the user is not found,
// log the error and return a not found response
logger.Error(fmt.Errorf("user not found"), http.StatusNotFound)
} else {
logger.Error(fmt.Errorf("error getting user"), http.StatusInternalServerError)
}
return ""
}
return user.Email
}
func valid_permissions(r *http.Request, isAdmin bool, jwt_email string, collection *mongo.Collection) bool {
if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" || r.Method == "DELETE" {
if isAdmin {
return true
}
// If we have a non-admin token, a user can only update themselves
return jwt_email == fetch_email(r.URL.Path, collection)
}
return true
}
// Middleware function, which will be called for each request
func Users_API_Access_Control(next http.Handler, collection *mongo.Collection) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ignore if this is not a call to users or prev schedules, classrooms
if !strings.Contains(r.URL.Path, "/users") && !strings.Contains(r.URL.Path, "/courses") && !strings.Contains(r.URL.Path, "/schedules/prev") && !strings.Contains(r.URL.Path, "/schedules") && !strings.Contains(r.URL.Path, "/classrooms") {
// Middleware successful
next.ServeHTTP(w, r)
return
}
apikey := r.Header.Get("apikey")
if apikey != "" {
check := helper.VerifyAPIKey(apikey)
if check {
// Middleware successful
next.ServeHTTP(w, r)
return
}
http.Error(w, "Unauthorized", http.StatusUnauthorized)
logger.Error(fmt.Errorf("Unauthorized"), http.StatusUnauthorized)
return
}
auth := r.Header.Get("Authorization")
if auth == "" {
http.Error(w, "Unauthorized - Error no token provided", http.StatusUnauthorized)
logger.Error(fmt.Errorf("Unauthorized - Error no token provided"), http.StatusUnauthorized)
return
}
token, err := helper.CleanJWT(r.Header.Get("Authorization"))
if err != nil {
http.Error(w, "Unauthorized - Error "+err.Error(), http.StatusUnauthorized)
logger.Error(fmt.Errorf("Error while cleaning jwt "+err.Error()), http.StatusUnauthorized)
return
}
ok, jwtInfo, err := helper.VerifyJWT(token)
if err != nil || !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
if err != nil {
logger.Error(fmt.Errorf("Error while verifying jwt "+err.Error()), http.StatusUnauthorized)
}
return
}
// Role based access for courses endpoints
if strings.Contains(r.URL.Path, "/courses") {
// Get is allowed with valid jwt
if r.Method == "GET" {
next.ServeHTTP(w, r)
return
}
// CRUD for courses is only allowed for admins
if (r.Method == "POST" || r.Method == "PUT" || r.Method == "DELETE") && !jwtInfo.IsAdmin {
http.Error(w, "Forbidden", http.StatusForbidden)
logger.Error(fmt.Errorf("Forbidden - CRUD operation on courses requested by "+jwtInfo.Email), http.StatusForbidden)
return
}
}
// Role based access for users endpoints
if strings.Contains(r.URL.Path, "/classrooms") {
// get forbidden for jwt
if r.Method == "GET" {
next.ServeHTTP(w, r)
return
}
// user must be admin for CRUD operation on classrooms
if (r.Method == "POST" || r.Method == "PUT" || r.Method == "DELETE") && !jwtInfo.IsAdmin {
http.Error(w, "Forbidden", http.StatusForbidden)
logger.Error(fmt.Errorf("Forbidden - CRUD operation requested by "+jwtInfo.Email), http.StatusForbidden)
return
}
}
// Role based access for previous schedules endpoints
if r.URL.Path == "/schedules/prev" {
if r.Method == "GET" {
next.ServeHTTP(w, r)
return
}
if r.Method == "POST" && !jwtInfo.IsAdmin {
http.Error(w, "Forbidden", http.StatusForbidden)
logger.Error(fmt.Errorf("Forbidden - /schedules/prev CRUD operation requested by non admin - "+jwtInfo.Email), http.StatusForbidden)
return
}
}
// Role based access for schedules endpoints
if strings.Contains(r.URL.Path, "/schedules") && r.URL.Path != "/schedules/prev" {
// get forbidden for jwt
if r.Method == "GET" {
next.ServeHTTP(w, r)
return
}
// user must be admin for CRUD operation on schedules
if (r.Method == "POST" || r.Method == "PUT" || r.Method == "DELETE") && !jwtInfo.IsAdmin {
http.Error(w, "Forbidden", http.StatusForbidden)
logger.Error(fmt.Errorf("Forbidden - CRUD operation requested for schedules by "+jwtInfo.Email), http.StatusForbidden)
return
}
}
// Role Based access for users endpoint
if strings.Contains(r.URL.Path, "/users") {
// user must be admin for CRUD operation on users
if !valid_permissions(r, jwtInfo.IsAdmin, jwtInfo.Email, collection) {
http.Error(w, "Forbidden", http.StatusForbidden)
logger.Error(fmt.Errorf("Forbidden - CRUD operation requested by "+jwtInfo.Email), http.StatusForbidden)
return
}
// if user is not admin then they can only get their
if (r.Method == "GET") && !jwtInfo.IsAdmin {
// Extract the user username from the URL path
path := r.URL.Path
username := strings.TrimPrefix(path, "/users/")
username = strings.TrimSpace(username)
// NOTE: check for get all user from non admin
// Retrieve the user from the MongoDB collection
var user users.User
filter := bson.M{"username": username}
err := collection.FindOne(context.TODO(), filter).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
// If the user is not found,
// log the error and return a not found response
logger.Error(fmt.Errorf("User not found"), http.StatusNotFound)
http.Error(w, "Forbidden", http.StatusForbidden)
} else {
// If there is an error retrieving the user,
// log the error and return an internal server error response
logger.Error(fmt.Errorf("Error getting user"), http.StatusInternalServerError)
http.Error(w, "Error getting user from DB", http.StatusInternalServerError)
}
return
}
if user.Email != jwtInfo.Email {
logger.Error(fmt.Errorf("Forbidden, non admin user trying to access other users info"), http.StatusForbidden)
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
}
}
// Middleware successful
next.ServeHTTP(w, r)
})
}