// Copyright (C) 2019 Marius Schellenberger

package server

import (
	"crypto/rand"
	"crypto/subtle"
	"encoding/base64"
	"git.giftfish.de/ston1th/docstore/pkg/log"
	"git.giftfish.de/ston1th/jwt/v3"
)

const keySize = jwt.KeySize / 2

func genKey(length int) (bytes []byte) {
	bytes = make([]byte, length)
	if _, err := rand.Reader.Read(bytes); err != nil {
		log.Println("genKey:", err)
	}
	return
}

func newXsrf(secret []byte) string {
	rnd := genKey(keySize)
	return base64.RawURLEncoding.EncodeToString(append(rnd, xor(rnd, secret)...))
}

func checkXsrf(xsrf string, secret []byte) bool {
	t, err := base64.RawURLEncoding.DecodeString(xsrf)
	if err != nil {
		return false
	}
	if len(t) != jwt.KeySize {
		return false
	}
	return subtle.ConstantTimeCompare(secret, xor(t[keySize:], t[:keySize])) == 1
}

func xor(a, b []byte) (c []byte) {
	n := len(a)
	if len(b) < n {
		return nil
	}
	c = make([]byte, n)
	for i := 0; i < n; i++ {
		c[i] = a[i] ^ b[i]
	}
	return
}
