softplayer-backend/internal/controllers/accounts.go

290 lines
7.1 KiB
Go

package controllers
import (
"context"
"errors"
"fmt"
"time"
"git.badhouseplants.net/softplayer/softplayer-backend/internal/consts"
"git.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/email"
"git.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/hash"
"git.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/kube"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
)
type Account struct {
Controller ctrl.Manager
Params AccountParams
Data *AccountData
Token string
DevMode bool
}
type AccountParams struct {
HashCost int16
}
type AccountData struct {
Username string
Password string
Email string
UUID string
}
func (acc *Account) Create(ctx context.Context) error {
client := acc.Controller.GetClient()
acc.Data.UUID = uuid.New().String()
passwordHash, err := hash.HashPassword(acc.Data.Password, int(acc.Params.HashCost))
if err != nil {
return nil
}
namespace := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: acc.Data.UUID,
Labels: map[string]string{
"username": acc.Data.Username,
"email-verified": "false",
"managed-by": "softplayer",
},
},
}
if err := kube.Create(ctx, client, namespace, true); err != nil {
return err
}
if err := client.Get(ctx, types.NamespacedName{
Name: acc.Data.UUID,
}, namespace); err != nil {
if err := client.Delete(ctx, namespace); err != nil {
return err
}
return err
}
// Create a secret with the account data
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: acc.Data.Username,
Namespace: "softplayer-accounts",
},
StringData: map[string]string{
"uuid": acc.Data.UUID,
"email": acc.Data.Email,
"password": passwordHash,
},
}
if err := client.Create(ctx, kube.SetOwnerRef(ctx, client, secret, namespace)); err != nil {
if err := client.Delete(ctx, namespace); err != nil {
return err
}
return err
}
// Prepare RBAC resources for the account
role := &rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{Name: acc.Data.Username, Namespace: acc.Data.UUID},
Rules: []rbacv1.PolicyRule{{Verbs: []string{"get", "watch", "list", "create", "patch", "delete", "update"}, APIGroups: []string{""}, Resources: []string{"configmaps", "secrets"}}},
}
if err := client.Create(ctx, role); err != nil {
if err := client.Delete(ctx, namespace); err != nil {
return err
}
return err
}
sa := &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: acc.Data.UUID,
Namespace: acc.Data.UUID,
},
}
if err := client.Create(ctx, sa); err != nil {
if err := client.Delete(ctx, namespace); err != nil {
return err
}
return err
}
rb := &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: acc.Data.UUID,
Namespace: acc.Data.UUID,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: acc.Data.UUID,
Namespace: acc.Data.UUID,
},
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "Role",
Name: acc.Data.Username,
},
}
if err := client.Create(ctx, rb); err != nil {
if err := client.Delete(ctx, namespace); err != nil {
return err
}
return err
}
tokenName := fmt.Sprintf("sa-%s", acc.Data.UUID)
saSec := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: tokenName,
Namespace: acc.Data.UUID,
Annotations: map[string]string{
"kubernetes.io/service-account.name": acc.Data.UUID,
},
},
Type: "kubernetes.io/service-account-token",
}
if err := client.Create(ctx, saSec); err != nil {
if err := client.Delete(ctx, namespace); err != nil {
return err
}
return err
}
if err := kube.WaitUntilCreated(ctx, client, saSec, 10, time.Millisecond*50); err != nil {
return err
}
acc.Token, err = acc.getToken(ctx, saSec)
if err != nil {
if err := client.Delete(ctx, namespace); err != nil {
return err
}
return err
}
return nil
}
func (acc *Account) Login(ctx context.Context) error {
client := acc.Controller.GetClient()
sec := &corev1.Secret{}
if err := client.Get(ctx, types.NamespacedName{
Namespace: "softplayer-accounts",
Name: acc.Data.Username,
}, sec); err != nil {
return err
}
if err := hash.CheckPasswordHash(acc.Data.Password, string(sec.Data["password"])); err != nil {
return err
}
acc.Data.UUID = string(sec.Data["uuid"])
tokenName := fmt.Sprintf("sa-%s", acc.Data.UUID)
saSec := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: tokenName,
Namespace: acc.Data.UUID,
Annotations: map[string]string{
"kubernetes.io/service-account.name": acc.Data.UUID,
},
},
Type: "kubernetes.io/service-account-token",
}
var err error
acc.Token, err = acc.getToken(ctx, saSec)
if err != nil {
return err
}
return nil
}
func (acc *Account) ResetPassword(ctx context.Context, emailConfig email.EmailConf) (string, error) {
clientset, err := kubernetes.NewForConfig(acc.Controller.GetConfig())
if err != nil {
return "", err
}
userdata, err := clientset.CoreV1().Secrets("softplayer-accounts").Get(ctx, acc.Data.Username, metav1.GetOptions{})
if err != nil {
return "", err
}
if string(userdata.Data["email"]) != acc.Data.Email {
return "", errors.New("user or email not found")
}
acc.Data.UUID = string(userdata.Data["uuid"])
conf := &rest.Config{
Host: "https://kubernetes.default.svc.cluster.local:443",
BearerToken: acc.Token,
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
}
clientset, err = kubernetes.NewForConfig(conf)
if err != nil {
logrus.Error(err, "Couldn't create a new clientset")
return "", consts.ErrSystemError
}
secretName := "password-reset-code"
number := encodeToString(6)
secret := corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
},
StringData: map[string]string{
"code": number,
},
}
sec, err := clientset.CoreV1().Secrets(acc.Data.UUID).Create(ctx, &secret, metav1.CreateOptions{})
if !k8serrors.IsAlreadyExists(err) {
return "", err
} else if k8serrors.IsAlreadyExists(err) {
timestamp := sec.CreationTimestamp.Time
now := time.Now()
if timestamp.Add(time.Minute).Before(now) {
return "", errors.New("You can send an email once per minute, please wait")
}
}
if !acc.DevMode {
emailContent := "Subject: Softplayer verification code\r\n" + "\r\n" + fmt.Sprintf("Your verification code is %s", number)
email := string(userdata.Data["email"])
if err := emailConfig.SendEmail(email, emailContent); err != nil {
return "", err
}
}
return number, nil
}
func (acc *Account) getToken(ctx context.Context, saSec *corev1.Secret) (string, error) {
client := acc.Controller.GetClient()
if err := client.Get(ctx, types.NamespacedName{
Namespace: acc.Data.UUID,
Name: saSec.ObjectMeta.Name,
}, saSec); err != nil {
return "", err
}
return string(saSec.Data["token"]), nil
}