forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
authenticator.go
107 lines (94 loc) · 2.45 KB
/
authenticator.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
package session
import (
"errors"
"fmt"
"net/http"
"time"
"strconv"
"k8s.io/apiserver/pkg/authentication/user"
)
const UserNameKey = "user.name"
const UserUIDKey = "user.uid"
const ExpiresKey = "expires"
type Authenticator struct {
store Store
name string
maxAge int
}
func NewAuthenticator(store Store, name string, maxAge int) *Authenticator {
return &Authenticator{
store: store,
name: name,
maxAge: maxAge,
}
}
func (a *Authenticator) AuthenticateRequest(req *http.Request) (user.Info, bool, error) {
session, err := a.store.Get(req, a.name)
if err != nil {
return nil, false, err
}
expiresObj, ok := session.Values()[ExpiresKey]
if !ok {
return nil, false, nil
}
expiresString, ok := expiresObj.(string)
if !ok {
return nil, false, errors.New("expires on session is not a string")
}
if expiresString == "" {
return nil, false, nil
}
expires, err := strconv.ParseInt(expiresString, 10, 64)
if err != nil {
return nil, false, fmt.Errorf("error parsing expires timestamp: %v", err)
}
if expires < time.Now().Unix() {
return nil, false, nil
}
nameObj, ok := session.Values()[UserNameKey]
if !ok {
return nil, false, nil
}
name, ok := nameObj.(string)
if !ok {
return nil, false, errors.New("user.name on session is not a string")
}
if name == "" {
return nil, false, nil
}
uidObj, ok := session.Values()[UserUIDKey]
if !ok {
return nil, false, nil
}
uid, ok := uidObj.(string)
if !ok {
return nil, false, errors.New("user.uid on session is not a string")
}
// Tolerate empty string UIDs in the session
return &user.DefaultInfo{
Name: name,
UID: uid,
}, true, nil
}
func (a *Authenticator) AuthenticationSucceeded(user user.Info, state string, w http.ResponseWriter, req *http.Request) (bool, error) {
session, err := a.store.Get(req, a.name)
if err != nil {
return false, err
}
values := session.Values()
values[UserNameKey] = user.GetName()
values[UserUIDKey] = user.GetUID()
values[ExpiresKey] = strconv.FormatInt(time.Now().Add(time.Duration(a.maxAge)*time.Second).Unix(), 10)
// TODO: should we save groups, scope, and extra in the session as well?
return false, a.store.Save(w, req)
}
func (a *Authenticator) InvalidateAuthentication(w http.ResponseWriter, req *http.Request) error {
session, err := a.store.Get(req, a.name)
if err != nil {
return err
}
session.Values()[UserNameKey] = ""
session.Values()[UserUIDKey] = ""
session.Values()[ExpiresKey] = ""
return a.store.Save(w, req)
}