Core functionality for new aiterp.net servers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
2.4 KiB

package auth
import (
"errors"
"strings"
"testing"
)
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) Find(userid string) *User {
for _, user := range ta.users {
if user.ID == userid {
return user
}
}
return nil
}
func (ta *testAuther) Login(userid, password string) (*User, error) {
for _, user := range ta.users {
if user.ID == userid && password == ta.passwords[user.ID] {
return user, nil
}
}
return nil, ErrLogin
}
func (ta *testAuther) Register(userid, password string, data map[string]string) (*User, error) {
if ta.Find(userid) != nil {
return nil, ErrExists
}
if ta.passwords == nil {
ta.passwords = make(map[string]string)
}
user := NewUser(ta, userid, "member", data)
ta.users = append(ta.users, user)
ta.passwords[userid] = password
return user, nil
}
func TestAuthenticator(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.ID != "Test" {
t.Logf("err = %v; name = \"%s\"", err, user.ID)
t.Fail()
}
if ta1.Find("Test") == nil {
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.ID)
t.Fail()
}
})
t.Run("Login", func(t *testing.T) {
user, err := ta1.Login("Test", "CakesAndStuff")
if err != nil || user.ID != "Test" {
t.Logf("err = %v; user = %+v", err, user)
t.Fail()
}
user2, err := ta1.Login("Test", "WrongPassword")
if err == nil || user2 != nil {
t.Logf("err = %v; user = %+v", err, user2)
t.Fail()
}
})
}