This repository has been archived by the owner on Oct 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
76 lines (64 loc) · 2.09 KB
/
cache.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
// Package cache implements middleware caching Authorization header to authenticate user.
package cache
import (
"net/http"
"time"
gcache "github.com/pmylund/go-cache"
)
// Type Cache stores cache for basic auth, and record.
type Cache struct {
gcache.Cache
}
const (
DefaultAuthExpireTime = 10 * time.Minute
DefaultAuthPurseTime = 60 * time.Second
AuthenticatedHeader = "go-auth-cache-Authenticated"
)
// NewDefault returns a Cache with default value for AuthCache, RecordCache
func NewDefault() *Cache {
return &Cache{
// Cache for basic authentication:
// Default expiration time: 10 minutes.
// Purges expired items time: every 60 seconds.
*gcache.New(DefaultAuthExpireTime, DefaultAuthPurseTime),
}
}
// New returns a Cache with given expire time, and purse time.
func New(authExpireTime, authPurseTime time.Duration) *Cache {
return &Cache{
// Cache for basic authentication:
// Default expiration time: 10 minutes.
// Purges expired items time: every 60 seconds.
*gcache.New(authExpireTime, authPurseTime),
}
}
// ServeHTTP inform next middleware this request already authenticated by looking into the cache.
func (c *Cache) ServeHTTP(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
found := false
if (req.Method != "GET") && (req.Method != "POST") {
next(w, req)
return
}
// Get credential from request header.
credential := req.Header.Get("Authorization")
// Get authentication status by credential.
authenticated, found := c.Get(credential)
// Cache hit
if found && (authenticated == "true") {
// Inform next middleware this request is authenticated.
w.Header().Set(AuthenticatedHeader, "true")
next(w, req)
} else {
// Cache miss. Unauthenticated.
w.Header().Set(AuthenticatedHeader, "false")
// Call next middleware
next(w, req)
order := w.Header().Get(AuthenticatedHeader)
// Cache this credential if ordered by other middleware.
if order == "cache" {
c.Set(credential, "true", gcache.DefaultExpiration)
}
// Remove AuthenticatedHeader out of response header.
w.Header().Del(AuthenticatedHeader)
}
}