package pkiws

import (
	"crypto/sha512"
	"encoding/hex"
	"fmt"

	"git.paulbsd.com/paulbsd/pki/src/config"
	"git.paulbsd.com/paulbsd/pki/src/pki"
	"github.com/labstack/echo/v4"
)

// Auth make authentication to webservice
func Auth(cfg *config.Config, username string, password string, c echo.Context) (res bool, user *pki.User, err error) {
	user = &pki.User{Username: username}

	_, err = cfg.Db.Get(user)
	if err != nil {
		res = false
		return
	}

	hashedPassword := sha512.Sum512([]byte(password))
	base64Password := hex.EncodeToString(hashedPassword[:])

	if base64Password == user.PasswordSHA512 {
		res = true
	} else {
		err = fmt.Errorf("Password doesn't match")
	}
	return
}

// ConfigAccess make ip authorization to configuration
func ConfigAccess(cfg config.Config, ip string) (ret bool) {
	switch ip {
	case "127.0.0.1":
		return true
	case "::1":
		return true
	default:
		return
	}
}
