diff --git a/auth/admin.go b/auth/admin.go new file mode 100644 index 0000000..a1bea38 --- /dev/null +++ b/auth/admin.go @@ -0,0 +1,68 @@ +package auth + +import ( + "errors" + "github.com/fanux/fist/tools" +) + +// vars +var AdminUsername string +var AdminPassword string + +// consts +const ( + DefaultNamespace = "sealyun" + DefaultSecretName = "fist-admin" +) + +type Admin struct { + Name string + Passwd string +} + +type Adminer interface { + LoadSecret() error + IsAdmin() (bool, error) +} + +func NewAdmin(name string, passwd string) Adminer { + var admire Adminer + admire = &Admin{Name: name, Passwd: passwd} + return admire +} + +func (*Admin) LoadSecret() error { + clients, err := tools.GetK8sClient() + if err != nil { + return err + } + if AdminUsername == "" { + secrets, err := tools.GetSecrets(DefaultNamespace, DefaultSecretName, clients) + if err != nil { + return err + } + AdminUsername = string(secrets.Data["username"]) + } + if AdminPassword == "" { + secrets, err := tools.GetSecrets(DefaultNamespace, DefaultSecretName, clients) + if err != nil { + return err + } + AdminPassword = string(secrets.Data["password"]) + } + return nil +} + +func (admin *Admin) IsAdmin() (bool, error) { + if admin.Name == "" { + return false, errors.New("the username is empty") + } + if admin.Passwd == "" { + return false, errors.New("the password is empty") + } + if admin.Name == AdminUsername && admin.Passwd == AdminPassword { + return true, nil + } else { + return false, errors.New("the username and password is mismatching") + } +} diff --git a/auth/admin_test.go b/auth/admin_test.go new file mode 100644 index 0000000..57ca475 --- /dev/null +++ b/auth/admin_test.go @@ -0,0 +1,45 @@ +package auth + +import ( + "strconv" + "testing" +) + +func TestAdmin_IsAdminFalse(t *testing.T) { + adminer := NewAdmin("admin", "admin") + err := adminer.LoadSecret() + if err != nil { + panic(err) + return + } + isAdmin, err := adminer.IsAdmin() + println("isAdmin:" + strconv.FormatBool(isAdmin)) + if err != nil { + panic(err) + return + } +} + +func TestAdmin_IsAdminTrue(t *testing.T) { + adminer := NewAdmin("admin", "1f2d1e2e67df") + err := adminer.LoadSecret() + if err != nil { + panic(err) + return + } + isAdmin, err := adminer.IsAdmin() + println("isAdmin:" + strconv.FormatBool(isAdmin)) + if err != nil { + panic(err) + return + } +} + +func TestAdmin_LoadSecret(t *testing.T) { + adminer := NewAdmin("admin", "admin") + err := adminer.LoadSecret() + if err != nil { + panic(err) + return + } +} diff --git a/auth/deploy/secret.yaml b/auth/deploy/secret.yaml new file mode 100644 index 0000000..0e2fd7b --- /dev/null +++ b/auth/deploy/secret.yaml @@ -0,0 +1,9 @@ +apiVersion: v1 +kind: Secret +metadata: + name: fist-admin + namespace: sealyun +type: Opaque +data: + username: YWRtaW4= + password: MWYyZDFlMmU2N2Rm