- Track learner sessions and revoke them immediately on every request - Add a device replacement challenge for logins over the limit - Add learner and admin endpoints to list and remove devices - Trim excess sessions when enforcement is enabled - Stop logging refresh tokens and authorization headers Enforcement is off by default through DEVICE_LIMIT_ENFORCED.
608 lines
20 KiB
Go
608 lines
20 KiB
Go
package authentication
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"sort"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"Rezina-Backend/internal/domain"
|
|
"Rezina-Backend/internal/ports"
|
|
|
|
"github.com/google/uuid"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
type sessionTestUserStore struct {
|
|
ports.UserStore
|
|
users map[int64]domain.User
|
|
googleIDs map[string]int64
|
|
appleIDs map[string]int64
|
|
}
|
|
|
|
func (s sessionTestUserStore) GetUserByID(_ context.Context, id int64) (domain.User, error) {
|
|
return s.users[id], nil
|
|
}
|
|
func (s sessionTestUserStore) GetUserByGoogleID(_ context.Context, googleID string) (domain.User, error) {
|
|
id, ok := s.googleIDs[googleID]
|
|
if !ok {
|
|
return domain.User{}, domain.ErrUserNotFound
|
|
}
|
|
return s.users[id], nil
|
|
}
|
|
func (s sessionTestUserStore) GetUserByAppleID(_ context.Context, appleID string) (domain.User, error) {
|
|
id, ok := s.appleIDs[appleID]
|
|
if !ok {
|
|
return domain.User{}, domain.ErrUserNotFound
|
|
}
|
|
return s.users[id], nil
|
|
}
|
|
func (s sessionTestUserStore) GetUserByEmailPhone(_ context.Context, email, phone string) (domain.User, error) {
|
|
for _, u := range s.users {
|
|
if u.Email == email || u.PhoneNumber == phone {
|
|
return u, nil
|
|
}
|
|
}
|
|
return domain.User{}, ErrUserNotFound
|
|
}
|
|
|
|
type fakeChallenge struct {
|
|
userID int64
|
|
device domain.DeviceInfo
|
|
expires time.Time
|
|
used bool
|
|
}
|
|
type fakeSession struct {
|
|
item domain.UserSession
|
|
key string
|
|
active bool
|
|
reason string
|
|
}
|
|
|
|
func (s *memorySessionStore) activeSortedLocked(userID int64, except uuid.UUID) []*fakeSession {
|
|
items := make([]*fakeSession, 0)
|
|
for _, item := range s.sessions {
|
|
if item.active && item.item.UserID == userID && item.item.ID != except {
|
|
items = append(items, item)
|
|
}
|
|
}
|
|
sort.Slice(items, func(i, j int) bool {
|
|
if !items[i].item.LastSeenAt.Equal(items[j].item.LastSeenAt) {
|
|
return items[i].item.LastSeenAt.After(items[j].item.LastSeenAt)
|
|
}
|
|
if !items[i].item.CreatedAt.Equal(items[j].item.CreatedAt) {
|
|
return items[i].item.CreatedAt.After(items[j].item.CreatedAt)
|
|
}
|
|
return items[i].item.ID.String() < items[j].item.ID.String()
|
|
})
|
|
return items
|
|
}
|
|
func (s *memorySessionStore) revokeSessionTokensLocked(sessionID uuid.UUID) {
|
|
for token, value := range s.tokens {
|
|
if value.SessionID.Valid && value.SessionID.UUID == sessionID {
|
|
value.Revoked = true
|
|
s.tokens[token] = value
|
|
}
|
|
}
|
|
}
|
|
|
|
type memorySessionStore struct {
|
|
mu sync.Mutex
|
|
sessions map[uuid.UUID]*fakeSession
|
|
challenges map[string]*fakeChallenge
|
|
tokens map[string]domain.RefreshToken
|
|
}
|
|
|
|
func newMemorySessionStore() *memorySessionStore {
|
|
return &memorySessionStore{sessions: map[uuid.UUID]*fakeSession{}, challenges: map[string]*fakeChallenge{}, tokens: map[string]domain.RefreshToken{}}
|
|
}
|
|
func (s *memorySessionStore) CreateRefreshToken(_ context.Context, rt domain.RefreshToken) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.tokens[rt.Token] = rt
|
|
return nil
|
|
}
|
|
func (s *memorySessionStore) GetRefreshToken(_ context.Context, token string) (domain.RefreshToken, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
rt, ok := s.tokens[token]
|
|
if !ok {
|
|
return domain.RefreshToken{}, ErrRefreshTokenNotFound
|
|
}
|
|
return rt, nil
|
|
}
|
|
func (s *memorySessionStore) GetRefreshTokenByUserID(_ context.Context, id int64) (domain.RefreshToken, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for _, v := range s.tokens {
|
|
if v.UserID == id {
|
|
return v, nil
|
|
}
|
|
}
|
|
return domain.RefreshToken{}, ErrRefreshTokenNotFound
|
|
}
|
|
func (s *memorySessionStore) RevokeRefreshToken(_ context.Context, token string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
rt := s.tokens[token]
|
|
rt.Revoked = true
|
|
s.tokens[token] = rt
|
|
return nil
|
|
}
|
|
|
|
func (s *memorySessionStore) IssueUserSession(_ context.Context, p domain.SessionIssueParams) (domain.SessionIssueResult, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for _, v := range s.sessions {
|
|
if v.active && p.Device.Key != "" && v.key == p.Device.Key && v.item.UserID == p.UserID {
|
|
v.active = false
|
|
}
|
|
}
|
|
count := 0
|
|
for _, v := range s.sessions {
|
|
if v.active && v.item.UserID == p.UserID {
|
|
count++
|
|
}
|
|
}
|
|
if p.EnforceLimit && count >= p.MaxDevices {
|
|
s.challenges[string(p.ChallengeHash)] = &fakeChallenge{userID: p.UserID, device: p.Device, expires: p.ChallengeExpiry}
|
|
return domain.SessionIssueResult{LimitReached: true, ChallengeExpires: p.ChallengeExpiry, Devices: s.listLocked(p.UserID)}, nil
|
|
}
|
|
id := uuid.New()
|
|
item := domain.UserSession{ID: id, UserID: p.UserID, Label: p.Device.Label, Platform: p.Device.Platform, CreatedAt: time.Now(), LastSeenAt: time.Now(), ExpiresAt: p.RefreshExpires}
|
|
s.sessions[id] = &fakeSession{item: item, key: p.Device.Key, active: true}
|
|
s.tokens[p.RefreshToken] = domain.RefreshToken{UserID: p.UserID, Token: p.RefreshToken, ExpiresAt: p.RefreshExpires, SessionID: uuid.NullUUID{UUID: id, Valid: true}}
|
|
return domain.SessionIssueResult{Session: item}, nil
|
|
}
|
|
func (s *memorySessionStore) listLocked(userID int64) []domain.UserSession {
|
|
out := []domain.UserSession{}
|
|
for _, v := range s.sessions {
|
|
if v.active && v.item.UserID == userID {
|
|
out = append(out, v.item)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
func (s *memorySessionStore) ReplaceUserSession(_ context.Context, p domain.SessionReplaceParams) (domain.UserSession, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
ch := s.challenges[string(p.ChallengeHash)]
|
|
if ch == nil || ch.used || !ch.expires.After(time.Now()) {
|
|
return domain.UserSession{}, ErrInvalidDeviceChallenge
|
|
}
|
|
old := s.sessions[p.SessionID]
|
|
if old == nil || !old.active || old.item.UserID != ch.userID {
|
|
return domain.UserSession{}, ErrInvalidDeviceChallenge
|
|
}
|
|
ch.used = true
|
|
old.active = false
|
|
id := uuid.New()
|
|
item := domain.UserSession{ID: id, UserID: ch.userID, Label: ch.device.Label, Platform: ch.device.Platform, LastSeenAt: time.Now(), ExpiresAt: p.RefreshExpires}
|
|
item.CreatedAt = item.LastSeenAt
|
|
s.sessions[id] = &fakeSession{item: item, key: ch.device.Key, active: true}
|
|
s.tokens[p.RefreshToken] = domain.RefreshToken{UserID: ch.userID, Token: p.RefreshToken, ExpiresAt: p.RefreshExpires, SessionID: uuid.NullUUID{UUID: id, Valid: true}}
|
|
if p.EnforceLimit {
|
|
others := s.activeSortedLocked(ch.userID, id)
|
|
keepOthers := p.MaxDevices - 1
|
|
if keepOthers < 0 {
|
|
keepOthers = 0
|
|
}
|
|
if keepOthers > len(others) {
|
|
keepOthers = len(others)
|
|
}
|
|
for _, excess := range others[keepOthers:] {
|
|
excess.active = false
|
|
excess.reason = "over_device_limit"
|
|
s.revokeSessionTokensLocked(excess.item.ID)
|
|
}
|
|
}
|
|
return item, nil
|
|
}
|
|
func (s *memorySessionStore) RotateSessionRefreshToken(_ context.Context, p domain.SessionRefreshParams) (domain.RefreshToken, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
old, ok := s.tokens[p.OldToken]
|
|
if !ok || old.Revoked {
|
|
return domain.RefreshToken{}, ErrRefreshTokenNotFound
|
|
}
|
|
sid := old.SessionID
|
|
if sid.Valid {
|
|
ss := s.sessions[sid.UUID]
|
|
if ss == nil || !ss.active {
|
|
return domain.RefreshToken{}, ErrSessionRevoked
|
|
}
|
|
if p.IsLearner && p.EnforceLimit {
|
|
ranked := s.activeSortedLocked(old.UserID, uuid.Nil)
|
|
withinLimit := false
|
|
for i, item := range ranked {
|
|
if i >= p.MaxDevices {
|
|
break
|
|
}
|
|
if item.item.ID == sid.UUID {
|
|
withinLimit = true
|
|
break
|
|
}
|
|
}
|
|
if !withinLimit {
|
|
ss.active = false
|
|
ss.reason = "over_device_limit"
|
|
s.revokeSessionTokensLocked(sid.UUID)
|
|
return domain.RefreshToken{}, ErrSessionRevoked
|
|
}
|
|
}
|
|
ss.item.LastSeenAt = time.Now()
|
|
ss.item.ExpiresAt = p.RefreshExpires
|
|
} else if p.IsLearner {
|
|
count := 0
|
|
for _, v := range s.sessions {
|
|
if v.active && v.item.UserID == old.UserID {
|
|
count++
|
|
}
|
|
}
|
|
if p.EnforceLimit && count >= p.MaxDevices {
|
|
return domain.RefreshToken{}, ErrDeviceLimitReached
|
|
}
|
|
id := uuid.New()
|
|
sid = uuid.NullUUID{UUID: id, Valid: true}
|
|
s.sessions[id] = &fakeSession{item: domain.UserSession{ID: id, UserID: old.UserID, Label: p.Device.Label, Platform: p.Device.Platform, ExpiresAt: p.RefreshExpires}, key: p.Device.Key, active: true}
|
|
}
|
|
old.Revoked = true
|
|
s.tokens[p.OldToken] = old
|
|
next := domain.RefreshToken{UserID: old.UserID, Token: p.NewToken, ExpiresAt: p.RefreshExpires, SessionID: sid}
|
|
s.tokens[p.NewToken] = next
|
|
return next, nil
|
|
}
|
|
func (s *memorySessionStore) LogoutSession(_ context.Context, token string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
rt, ok := s.tokens[token]
|
|
if !ok || rt.Revoked {
|
|
return ErrRefreshTokenNotFound
|
|
}
|
|
rt.Revoked = true
|
|
s.tokens[token] = rt
|
|
if rt.SessionID.Valid {
|
|
s.sessions[rt.SessionID.UUID].active = false
|
|
}
|
|
return nil
|
|
}
|
|
func (s *memorySessionStore) IsUserSessionActive(_ context.Context, id uuid.UUID, userID int64) (bool, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
v := s.sessions[id]
|
|
return v != nil && v.active && v.item.UserID == userID, nil
|
|
}
|
|
func (s *memorySessionStore) ListUserSessions(_ context.Context, userID int64) ([]domain.UserSession, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.listLocked(userID), nil
|
|
}
|
|
func (s *memorySessionStore) RevokeOwnUserSession(_ context.Context, userID int64, id uuid.UUID, _ string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
v := s.sessions[id]
|
|
if v == nil || !v.active || v.item.UserID != userID {
|
|
return ErrSessionNotFound
|
|
}
|
|
v.active = false
|
|
return nil
|
|
}
|
|
func (s *memorySessionStore) RevokeUserSession(ctx context.Context, userID int64, id uuid.UUID, reason string) error {
|
|
return s.RevokeOwnUserSession(ctx, userID, id, reason)
|
|
}
|
|
func (s *memorySessionStore) RevokeAllUserSessionsAndTokens(_ context.Context, userID int64, _ string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for _, v := range s.sessions {
|
|
if v.item.UserID == userID {
|
|
v.active = false
|
|
}
|
|
}
|
|
for k, v := range s.tokens {
|
|
if v.UserID == userID {
|
|
v.Revoked = true
|
|
s.tokens[k] = v
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
func (s *memorySessionStore) RevokeSessionsForRoleExcludingUser(context.Context, string, int64) error {
|
|
return nil
|
|
}
|
|
|
|
func newSessionTestService(store *memorySessionStore) *Service {
|
|
return NewService(nil, sessionTestUserStore{users: map[int64]domain.User{7: {ID: 7, Role: domain.RoleStudent}, 8: {ID: 8, Role: domain.RoleStudent}}}, nil, store, 3600)
|
|
}
|
|
func issue(t *testing.T, svc *Service, key string) (domain.SessionIssueResult, error) {
|
|
t.Helper()
|
|
return svc.IssueLearnerSession(context.Background(), 7, domain.RoleStudent, domain.DeviceInfo{Key: key, Label: "Chrome on Android", Platform: "android"})
|
|
}
|
|
|
|
func TestLearnerDeviceLimitAndSameDevice(t *testing.T) {
|
|
store := newMemorySessionStore()
|
|
svc := newSessionTestService(store)
|
|
svc.ConfigureDeviceSessions(2, true)
|
|
first, err := issue(t, svc, "one")
|
|
if err != nil || first.LimitReached {
|
|
t.Fatal(err)
|
|
}
|
|
second, err := issue(t, svc, "two")
|
|
if err != nil || second.LimitReached {
|
|
t.Fatal(err)
|
|
}
|
|
third, err := issue(t, svc, "three")
|
|
if err != nil || !third.LimitReached || third.ChallengeToken == "" || len(third.Devices) != 2 {
|
|
t.Fatalf("unexpected third login: %#v %v", third, err)
|
|
}
|
|
again, err := issue(t, svc, "one")
|
|
if err != nil || again.LimitReached {
|
|
t.Fatalf("same-device relogin used another slot: %#v %v", again, err)
|
|
}
|
|
active, _ := store.ListUserSessions(context.Background(), 7)
|
|
if len(active) != 2 {
|
|
t.Fatalf("active=%d", len(active))
|
|
}
|
|
}
|
|
func TestDeviceLimitEnforcementOff(t *testing.T) {
|
|
store := newMemorySessionStore()
|
|
svc := newSessionTestService(store)
|
|
svc.ConfigureDeviceSessions(2, false)
|
|
for _, key := range []string{"one", "two", "three"} {
|
|
got, err := issue(t, svc, key)
|
|
if err != nil || got.LimitReached {
|
|
t.Fatalf("%s: %#v %v", key, got, err)
|
|
}
|
|
}
|
|
}
|
|
func TestParallelLoginGuard(t *testing.T) {
|
|
store := newMemorySessionStore()
|
|
svc := newSessionTestService(store)
|
|
svc.ConfigureDeviceSessions(2, true)
|
|
var wg sync.WaitGroup
|
|
for i := 0; i < 12; i++ {
|
|
wg.Add(1)
|
|
go func() { defer wg.Done(); _, _ = issue(t, svc, uuid.NewString()) }()
|
|
}
|
|
wg.Wait()
|
|
active, _ := store.ListUserSessions(context.Background(), 7)
|
|
if len(active) != 2 {
|
|
t.Fatalf("parallel logins created %d sessions", len(active))
|
|
}
|
|
}
|
|
func TestChallengeSuccessReuseExpiryAndOwnership(t *testing.T) {
|
|
store := newMemorySessionStore()
|
|
svc := newSessionTestService(store)
|
|
svc.ConfigureDeviceSessions(2, true)
|
|
one, _ := issue(t, svc, "one")
|
|
_, _ = issue(t, svc, "two")
|
|
challenge, _ := issue(t, svc, "three")
|
|
login, err := svc.ReplaceLearnerSession(context.Background(), challenge.ChallengeToken, one.Session.ID)
|
|
if err != nil || login.SessionID == uuid.Nil || login.RfToken == "" {
|
|
t.Fatalf("replace: %#v %v", login, err)
|
|
}
|
|
if _, err = svc.ReplaceLearnerSession(context.Background(), challenge.ChallengeToken, one.Session.ID); !errors.Is(err, ErrInvalidDeviceChallenge) {
|
|
t.Fatalf("reuse err=%v", err)
|
|
}
|
|
expired, _ := issue(t, svc, "four")
|
|
hash, _ := hashDeviceChallenge(expired.ChallengeToken)
|
|
store.mu.Lock()
|
|
store.challenges[string(hash)].expires = time.Now().Add(-time.Second)
|
|
store.mu.Unlock()
|
|
if _, err = svc.ReplaceLearnerSession(context.Background(), expired.ChallengeToken, login.SessionID); !errors.Is(err, ErrInvalidDeviceChallenge) {
|
|
t.Fatalf("expiry err=%v", err)
|
|
}
|
|
wrong, _ := issue(t, svc, "five")
|
|
otherID := uuid.New()
|
|
store.mu.Lock()
|
|
store.sessions[otherID] = &fakeSession{item: domain.UserSession{ID: otherID, UserID: 8}, active: true}
|
|
store.mu.Unlock()
|
|
if _, err = svc.ReplaceLearnerSession(context.Background(), wrong.ChallengeToken, otherID); !errors.Is(err, ErrInvalidDeviceChallenge) {
|
|
t.Fatalf("ownership err=%v", err)
|
|
}
|
|
if _, err = svc.ReplaceLearnerSession(context.Background(), "not-a-token", otherID); !errors.Is(err, ErrInvalidDeviceChallenge) {
|
|
t.Fatalf("invalid err=%v", err)
|
|
}
|
|
}
|
|
func TestRefreshRevocationLegacyAdoptionAndLogout(t *testing.T) {
|
|
store := newMemorySessionStore()
|
|
svc := newSessionTestService(store)
|
|
svc.ConfigureDeviceSessions(2, true)
|
|
created, _ := issue(t, svc, "one")
|
|
store.mu.Lock()
|
|
store.sessions[created.Session.ID].active = false
|
|
store.mu.Unlock()
|
|
if _, err := svc.RefreshTokenForDevice(context.Background(), created.RefreshToken, domain.DeviceInfo{Platform: "web", Label: "Browser on Web"}); !errors.Is(err, ErrSessionRevoked) {
|
|
t.Fatalf("revoked refresh err=%v", err)
|
|
}
|
|
legacy := "legacy"
|
|
store.tokens[legacy] = domain.RefreshToken{UserID: 7, Token: legacy, ExpiresAt: time.Now().Add(time.Hour)}
|
|
rotated, err := svc.RefreshTokenForDevice(context.Background(), legacy, domain.DeviceInfo{Key: "legacy-device", Platform: "web", Label: "Chrome on Web"})
|
|
if err != nil || !rotated.SessionID.Valid {
|
|
t.Fatalf("legacy adoption: %#v %v", rotated, err)
|
|
}
|
|
if err := svc.Logout(context.Background(), rotated.Token); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
active, _ := store.IsUserSessionActive(context.Background(), rotated.SessionID.UUID, 7)
|
|
if active {
|
|
t.Fatal("logout left session active")
|
|
}
|
|
}
|
|
|
|
func TestEnforcementTrimsExistingSessionsOnRefreshAndPersistsRevocation(t *testing.T) {
|
|
store := newMemorySessionStore()
|
|
svc := newSessionTestService(store)
|
|
svc.ConfigureDeviceSessions(2, false)
|
|
issued := make([]domain.SessionIssueResult, 0, 3)
|
|
for _, key := range []string{"oldest", "middle", "newest"} {
|
|
result, err := issue(t, svc, key)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
issued = append(issued, result)
|
|
}
|
|
store.mu.Lock()
|
|
base := time.Now().Add(-time.Hour)
|
|
for i, result := range issued {
|
|
store.sessions[result.Session.ID].item.LastSeenAt = base.Add(time.Duration(i) * time.Minute)
|
|
store.sessions[result.Session.ID].item.CreatedAt = base.Add(time.Duration(i) * time.Minute)
|
|
}
|
|
store.mu.Unlock()
|
|
|
|
svc.ConfigureDeviceSessions(2, true)
|
|
_, err := svc.RefreshTokenForDevice(context.Background(), issued[0].RefreshToken, domain.DeviceInfo{Platform: "web"})
|
|
if !errors.Is(err, ErrSessionRevoked) {
|
|
t.Fatalf("refresh error = %v", err)
|
|
}
|
|
store.mu.Lock()
|
|
defer store.mu.Unlock()
|
|
if store.sessions[issued[0].Session.ID].active || store.sessions[issued[0].Session.ID].reason != "over_device_limit" {
|
|
t.Fatalf("session revocation did not persist: %#v", store.sessions[issued[0].Session.ID])
|
|
}
|
|
if !store.tokens[issued[0].RefreshToken].Revoked {
|
|
t.Fatal("refresh token revocation did not persist")
|
|
}
|
|
}
|
|
|
|
func TestReplacementTrimsExistingSessionsAndKeepsNewSession(t *testing.T) {
|
|
store := newMemorySessionStore()
|
|
svc := newSessionTestService(store)
|
|
svc.ConfigureDeviceSessions(2, false)
|
|
issued := make([]domain.SessionIssueResult, 0, 3)
|
|
for _, key := range []string{"one", "two", "three"} {
|
|
result, err := issue(t, svc, key)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
issued = append(issued, result)
|
|
}
|
|
svc.ConfigureDeviceSessions(2, true)
|
|
challenge, err := issue(t, svc, "replacement")
|
|
if err != nil || !challenge.LimitReached {
|
|
t.Fatalf("challenge: %#v, %v", challenge, err)
|
|
}
|
|
login, err := svc.ReplaceLearnerSession(context.Background(), challenge.ChallengeToken, issued[0].Session.ID)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
active, _ := store.ListUserSessions(context.Background(), 7)
|
|
if len(active) != 2 {
|
|
t.Fatalf("active sessions = %d, want 2", len(active))
|
|
}
|
|
newActive, _ := store.IsUserSessionActive(context.Background(), login.SessionID, 7)
|
|
if !newActive {
|
|
t.Fatal("replacement trimming revoked the new session")
|
|
}
|
|
}
|
|
|
|
func TestRefreshDoesNotTrimWhenEnforcementIsOff(t *testing.T) {
|
|
store := newMemorySessionStore()
|
|
svc := newSessionTestService(store)
|
|
svc.ConfigureDeviceSessions(2, false)
|
|
issued := make([]domain.SessionIssueResult, 0, 3)
|
|
for _, key := range []string{"one", "two", "three"} {
|
|
result, err := issue(t, svc, key)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
issued = append(issued, result)
|
|
}
|
|
if _, err := svc.RefreshTokenForDevice(context.Background(), issued[0].RefreshToken, domain.DeviceInfo{Platform: "web"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
active, _ := store.ListUserSessions(context.Background(), 7)
|
|
if len(active) != 3 {
|
|
t.Fatalf("active sessions = %d, want 3", len(active))
|
|
}
|
|
}
|
|
|
|
type sessionTestOtpStore struct {
|
|
ports.OtpStore
|
|
otp domain.Otp
|
|
used bool
|
|
}
|
|
|
|
func (s *sessionTestOtpStore) GetOtpByCode(_ context.Context, userID int64, code string) (domain.Otp, error) {
|
|
if s.otp.UserID != userID || s.otp.Otp != code {
|
|
return domain.Otp{}, domain.ErrOtpNotFound
|
|
}
|
|
return s.otp, nil
|
|
}
|
|
|
|
func (s *sessionTestOtpStore) MarkOtpAsUsed(_ context.Context, otp domain.Otp) error {
|
|
s.otp = otp
|
|
s.used = true
|
|
return nil
|
|
}
|
|
|
|
func TestNonLearnerOTPGoogleAndAppleKeepLegacyRefreshTokens(t *testing.T) {
|
|
admin := domain.User{ID: 9, Email: "admin@example.com", PhoneNumber: "+251900000009", Role: domain.RoleAdmin, Status: domain.UserStatusActive}
|
|
userStore := sessionTestUserStore{
|
|
users: map[int64]domain.User{9: admin}, googleIDs: map[string]int64{"google-admin": 9}, appleIDs: map[string]int64{"apple-admin": 9},
|
|
}
|
|
|
|
t.Run("OTP", func(t *testing.T) {
|
|
tokens := newMemorySessionStore()
|
|
otpStore := &sessionTestOtpStore{otp: domain.Otp{UserID: 9, Otp: "123456", ExpiresAt: time.Now().Add(time.Minute)}}
|
|
svc := NewService(otpStore, userStore, nil, tokens, 3600)
|
|
login, err := svc.VerifyOtp(context.Background(), admin.Email, "", "123456")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !otpStore.used || login.RfToken == "" || login.SessionID != uuid.Nil {
|
|
t.Fatalf("login = %#v, otp used = %v", login, otpStore.used)
|
|
}
|
|
})
|
|
|
|
for _, test := range []struct {
|
|
name string
|
|
login func(*Service) (domain.LoginSuccess, error)
|
|
}{
|
|
{name: "Google", login: func(svc *Service) (domain.LoginSuccess, error) {
|
|
return svc.LoginWithGoogle(context.Background(), domain.GoogleUser{ID: "google-admin", Email: admin.Email})
|
|
}},
|
|
{name: "Apple", login: func(svc *Service) (domain.LoginSuccess, error) {
|
|
return svc.LoginWithApple(context.Background(), domain.AppleUser{ID: "apple-admin", Email: admin.Email})
|
|
}},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
tokens := newMemorySessionStore()
|
|
svc := NewService(nil, userStore, nil, tokens, 3600)
|
|
login, err := test.login(svc)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if login.RfToken == "" || login.SessionID != uuid.Nil {
|
|
t.Fatalf("login = %#v", login)
|
|
}
|
|
active, _ := tokens.ListUserSessions(context.Background(), admin.ID)
|
|
if len(active) != 0 {
|
|
t.Fatalf("non-learner received %d sessions", len(active))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestAdminLoginFlowRemainsNonSessionBased(t *testing.T) {
|
|
store := newMemorySessionStore()
|
|
hash, err := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.MinCost)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
users := sessionTestUserStore{users: map[int64]domain.User{9: {ID: 9, Email: "admin@example.com", Password: hash, Role: domain.RoleAdmin, Status: domain.UserStatusActive}}}
|
|
svc := NewService(nil, users, nil, store, 3600)
|
|
login, err := svc.Login(context.Background(), domain.LoginRequest{Email: "admin@example.com", Password: "secret"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if login.RfToken == "" || login.SessionID != uuid.Nil {
|
|
t.Fatalf("admin login changed: %#v", login)
|
|
}
|
|
active, _ := store.ListUserSessions(context.Background(), 9)
|
|
if len(active) != 0 {
|
|
t.Fatalf("admin received %d learner sessions", len(active))
|
|
}
|
|
}
|