package auth import ( "errors" "strings" "testing" "git.aiterp.net/gisle/wrouter/generate" ) var ErrExists = errors.New("auth: user exists") var ErrLogin = errors.New("auth: login failed") type testAuther struct { FullName string users []*User passwords map[string]string } func (ta *testAuther) ID() string { return strings.ToLower(ta.FullName) } func (ta *testAuther) Name() string { return ta.FullName } func (ta *testAuther) Exists(username string) bool { for _, user := range ta.users { if user.Name == username { return true } } return false } func (ta *testAuther) Find(userid string) *User { for _, user := range ta.users { if user.ID == userid { return user } } return nil } func (ta *testAuther) Login(username, password string) (*User, error) { for _, user := range ta.users { if user.Name == username && password == ta.passwords[user.ID] { return user, nil } } return nil, ErrLogin } func (ta *testAuther) Register(username, password string, data map[string]string) (*User, error) { if ta.Exists(username) { return nil, ErrExists } if ta.passwords == nil { ta.passwords = make(map[string]string) } id := generate.ID() ta.passwords[id] = password user := NewUser(ta, id, username, "member", data) ta.users = append(ta.users, user) return user, nil } func TestList(t *testing.T) { ta1 := testAuther{FullName: "Auth1"} ta2 := testAuther{FullName: "Auth2"} Register(&ta1) Register(&ta2) if ta1.ID() != "auth1" { t.Errorf("ta1.ID() = %s", ta1.ID()) t.Fail() } if ta2.ID() != "auth2" { t.Errorf("ta2.ID() = %s", ta2.ID()) t.Fail() } t.Run("Find", func(t *testing.T) { fa1 := FindAuthenticator("auth1") fa2 := FindAuthenticator("auth2") if &ta1 != fa1 { t.Errorf("%s != %s", ta1.ID(), fa1.ID()) t.Fail() } if &ta2 != fa2 { t.Errorf("%s != %s", ta2.ID(), fa2.ID()) t.Fail() } }) t.Run("Register", func(t *testing.T) { user, err := ta1.Register("Test", "CakesAndStuff", nil) if err != nil || user.Name != "Test" { t.Logf("err = %v; name = \"%s\"", err, user.Name) t.Fail() } if !ta1.Exists("Test") { t.Log("Registered user does not exist") t.Fail() } user2, err := ta1.Register("Test", "CakesAndStuff", nil) if err == nil || user2 != nil { t.Logf("err = %s; name = \"%s\"", err, user2.Name) t.Fail() } }) t.Run("Login", func(t *testing.T) { user, err := ta1.Login("Test", "CakesAndStuff") if err != nil || user.Name != "Test" { t.Logf("err = %v; name = \"%s\"", err, user.Name) t.Fail() } user2, err := ta1.Login("Test", "WrongPassword") if err == nil || user2 != nil { t.Logf("err = %v; name = \"%s\"", err, user.Name) t.Fail() } }) }