/
user.go
50 lines (41 loc) · 1.02 KB
/
user.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
package middleware
import (
"net/http"
"github.com/gorilla/mux"
"github.com/root-gg/plik/server/context"
)
// User middleware for all the /user/{userID} routes.
func User(ctx *context.Context, next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if ctx.GetUser() == nil {
ctx.Unauthorized("You must be authenticated, please login first")
return
}
// Get the user id from the url params
vars := mux.Vars(req)
userID := vars["userID"]
if userID == "" {
ctx.MissingParameter("user id")
return
}
if userID != ctx.GetUser().ID {
if !ctx.IsAdmin() {
ctx.Forbidden("you need administrator privileges")
return
}
// Get user from session
user, err := ctx.GetMetadataBackend().GetUser(userID)
if err != nil {
ctx.InternalServerError("unable to get user", err)
return
}
if user == nil {
ctx.NotFound("user not found")
return
}
ctx.SaveOriginalUser()
ctx.SetUser(user)
}
next.ServeHTTP(resp, req)
})
}