package main import ( "testing" "time" "github.com/tinode/chat/server/store" "github.com/tinode/chat/server/store/types" ) func TestResolveRegistrationAccount(t *testing.T) { tests := []struct { name string username string phone string wantAccount string wantPhone string wantPhoneFlow bool wantErr bool }{ {name: "username", username: "alice1", wantAccount: "alice1"}, {name: "numeric username", username: "12345", wantAccount: "12345"}, {name: "phone wins", username: "INVALID", phone: "13800138000", wantAccount: "+8613800138000", wantPhone: "+8613800138000", wantPhoneFlow: true}, {name: "uppercase rejected", username: "Alice", wantErr: true}, {name: "long username rejected", username: "abcdefghijk", wantErr: true}, {name: "malformed phone does not fall back", username: "alice", phone: "1380013800", wantErr: true}, {name: "phone whitespace rejected", username: "alice", phone: " 13800138000", wantErr: true}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { account, phone, phoneFlow, err := resolveRegistrationAccount(tc.username, tc.phone) if (err != nil) != tc.wantErr || account != tc.wantAccount || phone != tc.wantPhone || phoneFlow != tc.wantPhoneFlow { t.Fatalf("got account=%q phone=%q phoneFlow=%v err=%v", account, phone, phoneFlow, err) } }) } } func TestRegistrationSecretMatchesSelectedAccount(t *testing.T) { if !registrationSecretMatches([]byte("alice:password:with-colon"), "alice") { t.Fatal("matching account was rejected") } if registrationSecretMatches([]byte("bob:password"), "alice") || registrationSecretMatches([]byte("password"), "alice") { t.Fatal("mismatched or malformed secret was accepted") } } func TestValidateRegistrationInviteStates(t *testing.T) { oldInvites := store.RegistrationInvites defer func() { store.RegistrationInvites = oldInvites }() now := time.Now().UTC() tests := []struct { status types.RegistrationInviteStatus expires time.Time want error }{ {types.RegistrationInviteActive, now.Add(time.Minute), nil}, {types.RegistrationInviteActive, now, types.ErrInviteExpired}, {types.RegistrationInviteRevoked, now.Add(time.Minute), types.ErrInviteRevoked}, {types.RegistrationInviteExpired, now.Add(time.Minute), types.ErrInviteExpired}, } for _, tc := range tests { store.RegistrationInvites = &testRegistrationInviteStore{invite: &types.RegistrationInviteCode{Status: tc.status, ExpiresAt: tc.expires}} if got := validateRegistrationInvite(7, "AbCdE", now); got != tc.want { t.Fatalf("status=%q: got %v want %v", tc.status, got, tc.want) } } }