forked from alterminal/alterminal
first commit
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSetAndCheckPassword(t *testing.T) {
|
||||
u := &User{}
|
||||
if err := u.SetPassword("correct horse battery staple"); err != nil {
|
||||
t.Fatal("SetPassword: ", err)
|
||||
}
|
||||
if u.PasswordHash == "" || strings.Contains(u.PasswordHash, "correct horse") {
|
||||
t.Fatalf("密碼不應以明文儲存: %q", u.PasswordHash)
|
||||
}
|
||||
if !u.CheckPassword("correct horse battery staple") {
|
||||
t.Error("正確密碼應驗證成功")
|
||||
}
|
||||
if u.CheckPassword("Tr0ub4dor&3") {
|
||||
t.Error("錯誤密碼不應驗證成功")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetPasswordUsesRandomSalt(t *testing.T) {
|
||||
a, b := &User{}, &User{}
|
||||
if err := a.SetPassword("same password"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := b.SetPassword("same password"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.PasswordHash == b.PasswordHash {
|
||||
t.Error("相同密碼應因隨機 salt 產生不同雜湊")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckPasswordMalformedHash(t *testing.T) {
|
||||
for _, hash := range []string{"", "not-a-phc-hash", "$argon2id$v=19$incomplete"} {
|
||||
u := &User{PasswordHash: hash}
|
||||
if u.CheckPassword("whatever") {
|
||||
t.Errorf("格式無效的雜湊 %q 不應驗證成功", hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoleValid(t *testing.T) {
|
||||
for _, r := range []Role{RoleAdmin, RoleUser} {
|
||||
if !r.Valid() {
|
||||
t.Errorf("Role(%q).Valid() = false, want true", r)
|
||||
}
|
||||
}
|
||||
for _, r := range []Role{"", "Admin", "superuser", "root"} {
|
||||
if r.Valid() {
|
||||
t.Errorf("Role(%q).Valid() = true, want false", r)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user