auth
auth/session.go
Rename Grant to AuthorizationCode. God bless gofmt. Rename all our instances of Grant to AuthorizationCode (including related variables and types, like grantStore and ErrGrantNotFound, plus all our comments and error strings. Whew.) to better reflect that it is only a single type of grant that could be accepted by the server.
1 package auth
3 import (
4 "errors"
5 "time"
7 "code.secondbit.org/uuid"
8 )
10 var (
11 // ErrNoSessionStore is returned when a Context tries to act on a sessionStore without setting on first.
12 ErrNoSessionStore = errors.New("no sessionStore was specified for the Context")
13 // ErrSessionNotFound is returned when a Session is requested but not found in the sessionStore.
14 ErrSessionNotFound = errors.New("session not found in sessionStore")
15 // ErrInvalidSession is returned when a Session is specified but is not valid.
16 ErrInvalidSession = errors.New("session is not valid")
17 // ErrSessionAlreadyExists is returned when a sessionStore tries to store a Session with an ID that already exists in the sessionStore.
18 ErrSessionAlreadyExists = errors.New("session already exists")
19 )
21 // Session represents a user's authenticated session, associating it with a profile
22 // and some audit data.
23 type Session struct {
24 ID string
25 IP string
26 UserAgent string
27 ProfileID uuid.ID
28 Created time.Time
29 Login string
30 Active bool
31 }
33 type sessionStore interface {
34 createSession(session Session) error
35 getSession(id string) (Session, error)
36 removeSession(id string) error
37 listSessions(profile uuid.ID, before time.Time, num int64) ([]Session, error)
38 }
40 func (m *memstore) createSession(session Session) error {
41 m.sessionLock.Lock()
42 defer m.sessionLock.Unlock()
43 if _, ok := m.sessions[session.ID]; ok {
44 return ErrSessionAlreadyExists
45 }
46 m.sessions[session.ID] = session
47 return nil
48 }
50 func (m *memstore) getSession(id string) (Session, error) {
51 m.sessionLock.RLock()
52 defer m.sessionLock.RUnlock()
53 if _, ok := m.sessions[id]; !ok {
54 return Session{}, ErrSessionNotFound
55 }
56 return m.sessions[id], nil
57 }
59 func (m *memstore) removeSession(id string) error {
60 m.sessionLock.Lock()
61 defer m.sessionLock.Unlock()
62 if _, ok := m.sessions[id]; !ok {
63 return ErrSessionNotFound
64 }
65 delete(m.sessions, id)
66 return nil
67 }
69 func (m *memstore) listSessions(profile uuid.ID, before time.Time, num int64) ([]Session, error) {
70 m.sessionLock.RLock()
71 defer m.sessionLock.RUnlock()
72 res := []Session{}
73 for _, session := range m.sessions {
74 if int64(len(res)) >= num {
75 break
76 }
77 if profile != nil && !profile.Equal(session.ProfileID) {
78 continue
79 }
80 if !before.IsZero() && session.Created.After(before) {
81 continue
82 }
83 res = append(res, session)
84 }
85 // BUG(paddy): sessions should return sorted by date created
86 return res, nil
87 }