package main

import (
	"crypto/sha256"
	"time"

	"github.com/dgrijalva/jwt-go"
)

func generateTokenPair(user userInfo, cockieStr string) (map[string]string, error) {
	// Create token
	token := jwt.New(jwt.SigningMethodHS256)

	// Set claims
	// This is the information which frontend can use
	// The backend can also decode the token and get admin etc.
	claims := token.Claims.(jwt.MapClaims)
	claims["admin"] = false
	for _, v := range user.Result.Result.MemberofGroup {
		if v == "usermodifier" || v == "admins" {
			claims["admin"] = true
		}
	}
	claims["sub"] = 1
	claims["name"] = user.Result.Result.UID[0]
	claims["IPAUid"] = user.Result.Result.Uidnumber[0]
	sha256 := sha256.Sum256([]byte(user.Result.Result.UID[0]))
	var hashChannel = make(chan []byte, 1)
	hashChannel <- sha256[:]
	claims["IPAToken"] = encrypt(<-hashChannel, cockieStr)
	claims["memberof"] = user.Result.Result.MemberofGroup
	claims["mail"] = user.Result.Result.Mail
	claims["exp"] = time.Now().Add(time.Minute * 15).Unix()

	// Generate encoded token and send it as response.
	// The signing string should be secret (a generated UUID works too)
	t, err := token.SignedString([]byte("secret"))
	if err != nil {
		return nil, err
	}

	refreshToken := jwt.New(jwt.SigningMethodHS256)
	rtClaims := refreshToken.Claims.(jwt.MapClaims)
	rtClaims["sub"] = 1
	rtClaims["IPAToken"] = claims["IPAToken"]
	rtClaims["name"] = claims["name"]
	rtClaims["exp"] = time.Now().Add(time.Hour * 24).Unix()

	rt, err := refreshToken.SignedString([]byte("secret"))
	if err != nil {
		return nil, err
	}

	return map[string]string{
		"access_token":  t,
		"refresh_token": rt,
	}, nil
}
