-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
103 lines (86 loc) · 2.37 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
package main
import (
"log"
"net/http"
userkey "restpos/pkg/userKey"
"strconv"
"strings"
"time"
Context "github.com/gorilla/context"
)
// Middleware .
type Middleware func(f http.HandlerFunc) http.HandlerFunc
// Log .
func Log(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
var id string
if user, ok := Context.GetOk(r, userkey.Key); ok {
uid := user.(User).ID
id = strconv.Itoa(int(uid))
} else {
id = "-"
}
defer func() { log.Printf("%s [%s] %s %s", time.Since(start), id, r.Method, r.URL.Path) }()
next.ServeHTTP(w, r)
})
}
// Skip urls that don't need authentication
var skipUrls = []string{
"/",
"/auth",
}
// Auth .
func Auth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
isImagePath := len(r.URL.Path) > 7 && r.URL.Path[:7] == "/static"
for _, v := range skipUrls {
if r.URL.Path == v || isImagePath {
next.ServeHTTP(w, r)
return
}
}
authKey := r.Header["Authorization"]
if authKey == nil {
http.Error(w, "No Bearer Token.", http.StatusForbidden)
return
}
var key []string
if key = strings.Split(authKey[0], " "); len(key) < 2 {
http.Error(w, "Wrong Bearer token format.", http.StatusBadRequest)
return
}
var user User
Db.First(&user, "auth_key = ?", key[1])
if user.ID == 0 {
http.Error(w, "Wrong authentication token.", http.StatusForbidden)
return
}
Context.Set(r, userkey.Key, user)
next.ServeHTTP(w, r)
})
}
// Cors .
func Cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Expose-Headers", "X-Total-Count")
if r.Method == "OPTIONS" {
w.Header().Add("Access-Control-Allow-Methods", "POST, DELETE, PUT, PATCH")
w.Header().Add("Access-Control-Allow-Headers", "Content-Type, Authorization")
return
}
next.ServeHTTP(w, r)
})
}
// JSONContentType All responses will be json Content-Type
func JSONContentType(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
isImagePath := len(r.URL.Path) > 7 && r.URL.Path[:7] == "/static"
defer next.ServeHTTP(w, r)
if isImagePath {
return
}
w.Header().Add("Content-Type", "application/json")
})
}