#!/bin/sh

po_domain="alterator-ahttpd"
alterator_api_version=1

. alterator-sh-functions

CSRF_TOKENS_DIR=/var/lib/alterator/csrf-tokens/

_var_is_digit()
{
	local n="$1"; shift

	[ -n "${n##*[!0-9]*}" ]
}

_var_is_hex()
{
	local n="$1"; shift

	[ -n "${n##*[!0-9a-f]*}" ]
}

_is_expired()
{
	local expire_time="$1"; shift

	[ "$expire_time" -le $(date +%s) ]
}

_read_token()
{
	local session="$1"; shift
	local data= expire_time= token=

	read data <"$CSRF_TOKENS_DIR/$session"
	expire_time="${data##*/}"
	token="${data%/*}"
	if [ -z "$expire_time" -o -z "$token" ] || _is_expired "$expire_time"; then
		rm -- "$CSRF_TOKENS_DIR/$session"
		return 1
	fi

	echo "$token"
}

new()
{
	local token=

	if ! _var_is_hex "$in_session_id"; then
		write_error "`_ "Wrong session ID $in_session_id"`"
		return
	fi

	if ! _var_is_digit "$in_expire" || _is_expired "$in_expire"; then
		return
	fi

	if [ -f "$CSRF_TOKENS_DIR/$in_session_id" ]; then
		local tmp="$(_read_token "$in_session_id")"
		if [ -n "$tmp" ]; then
			return
		fi
	fi

	mkdir -p "$CSRF_TOKENS_DIR"

	# token lenght is 13 characters (why not 42? it is too long)
	token="$(mktemp -u XXXXXXXXXXXXX)"
	echo "$token/$in_expire" >"$CSRF_TOKENS_DIR/$in_session_id"
}

get()
{
	local token=

	if ! _var_is_hex "$in_session_id"; then
		write_error "`_ "Wrong session ID $in_session_id"`"
		return
	fi

	if [ ! -f "$CSRF_TOKENS_DIR/$in_session_id" ]; then
		return
	fi

	token=$(_read_token "$in_session_id")
	if [ -n "$token" ]; then
		write_string_param token "$token"
	fi
}

delete()
{
	if ! _var_is_hex "$in_session_id"; then
		write_error "`_ "Wrong session ID $in_session_id"`"
		return
	fi

	rm -f -- "$CSRF_TOKENS_DIR/$in_session_id"
}

alterator_export_proc new
alterator_export_proc get
alterator_export_proc delete

message_loop
