-
Notifications
You must be signed in to change notification settings - Fork 32
/
session.go
112 lines (88 loc) · 2.15 KB
/
session.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
108
109
110
111
112
// Package session provides in-memory storage of secure session details.
package session
import (
"errors"
"fmt"
"sync"
"github.com/arigatomachine/cli/identity"
)
type memorySession struct {
id *identity.ID
// sensitive values
token string
passphrase string
mutex *sync.Mutex
}
// Session is the interface for access to secure session details.
type Session interface {
Set(*identity.ID, string, string) error
ID() *identity.ID
Token() string
Passphrase() string
HasToken() bool
HasPassphrase() bool
Logout()
String() string
}
// NewSession returns the default implementation of the Session interface.
func NewSession() Session {
return &memorySession{mutex: &sync.Mutex{}}
}
// Set atomically sets all relevant session details.
//
// It returns an error if any values are empty.
func (s *memorySession) Set(id *identity.ID, passphrase, token string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
if len(id) == 0 {
return errors.New("ID must not be empty")
}
if len(passphrase) == 0 {
return errors.New("Passphrase must not be empty")
}
if len(token) == 0 {
return errors.New("Token must not be empty")
}
s.id = id
s.passphrase = passphrase
s.token = token
return nil
}
func (s *memorySession) ID() *identity.ID {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.id
}
// Token returns the auth token stored in this session.
func (s *memorySession) Token() string {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.token
}
// Passphrase returns the user's passphrase.
func (s *memorySession) Passphrase() string {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.passphrase
}
func (s *memorySession) HasToken() bool {
return (len(s.token) > 0)
}
func (s *memorySession) HasPassphrase() bool {
return (len(s.passphrase) > 0)
}
// Logout clears all details from the session.
func (s *memorySession) Logout() {
s.mutex.Lock()
defer s.mutex.Unlock()
s.id = nil
s.token = ""
s.passphrase = ""
}
// String implements the fmt.Stringer interface.
func (s *memorySession) String() string {
s.mutex.Lock()
defer s.mutex.Unlock()
return fmt.Sprintf(
"memorySession{token:%t,passphrase:%t}", s.HasToken(), s.HasPassphrase())
}