package main

import (
	"errors"
	"strings"

	"github.com/jcmturner/gokrb5/v8/client"
	"github.com/jcmturner/gokrb5/v8/config"
	"github.com/jcmturner/gokrb5/v8/iana/etypeID"
	"github.com/jcmturner/gokrb5/v8/krberror"
)

type Krb5Auth struct {
	Realm string
}

func parseETypes(s []string, w bool) []int32 {
	var eti []int32
	for _, et := range s {
		if !w {
			var weak bool
			for _, wet := range strings.Fields(config.WeakETypeList) {
				if et == wet {
					weak = true
					break
				}
			}
			if weak {
				continue
			}
		}
		i := etypeID.EtypeSupported(et)
		if i != 0 {
			eti = append(eti, i)
		}
	}
	return eti
}

func (f *Krb5Auth) checkAuth(username, password string) (res bool, err error) {
	cnf := config.New()
	cnf.LibDefaults.DNSLookupKDC = true
	cnf.LibDefaults.DNSLookupRealm = true
	cnf.LibDefaults.DefaultTGSEnctypeIDs = parseETypes(cnf.LibDefaults.DefaultTGSEnctypes, cnf.LibDefaults.AllowWeakCrypto)
	cnf.LibDefaults.DefaultTktEnctypeIDs = parseETypes(cnf.LibDefaults.DefaultTktEnctypes, cnf.LibDefaults.AllowWeakCrypto)
	cnf.LibDefaults.PermittedEnctypeIDs = parseETypes(cnf.LibDefaults.PermittedEnctypes, cnf.LibDefaults.AllowWeakCrypto)

	c := client.NewWithPassword(username, f.Realm, password, cnf)
	if err := c.Login(); err != nil {
		if errk, ok := err.(krberror.Krberror); ok {
			if errk.RootCause == krberror.NetworkingError {
				return false, errors.New(`{"status": "Authentication system unavailable, please retry."}`)
			} else if errk.RootCause == krberror.KDCError {
				return false, errors.New(`{"status": "Invalid username or password"}`)
			}
		}
		return false, err
	} else {
		return true, nil
	}
}
