-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache_verifier.go
56 lines (47 loc) · 1.25 KB
/
cache_verifier.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
// Copyright (c) 2023 Benjamin Borbe All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pkg
import (
"time"
"github.com/golang/glog"
"github.com/wunderlist/ttlcache"
)
type CacheTTL time.Duration
func (c CacheTTL) IsEmpty() bool {
return int64(c) == 0
}
func (c CacheTTL) Duration() time.Duration {
return time.Duration(c)
}
type cacheAuth struct {
verifier Verifier
cache *ttlcache.Cache
}
func NewCacheAuth(
verifier Verifier,
ttl CacheTTL,
) Verifier {
return &cacheAuth{
verifier: verifier,
cache: ttlcache.NewCache(ttl.Duration()),
}
}
func (c *cacheAuth) Verify(username UserName, password Password) (bool, error) {
glog.V(2).Infof("verify user %s with password-length %d", username, len(password))
value, found := c.cache.Get(username.String())
if found && value == password.String() {
glog.V(2).Infof("cache hit for user %v", username)
return true, nil
}
result, err := c.verifier.Verify(username, password)
if err != nil {
glog.Warningf("verify user %v failed: %v", username, err)
return false, err
}
if result {
glog.V(2).Infof("add user %v to cache", username)
c.cache.Set(username.String(), password.String())
}
return result, nil
}