'use server'
import demoUser from "./demo-user.json"
// Cache for current tokens
const _tokens = new Map<string, string>()
/**
* Gets an authentication token server-to-server for the currently authenticated user.
*
* @param refresh - Whether to request a fresh token or use an existing token
* @returns {string} The current user token
*/
export const tokenFactory = async (refresh: boolean = false) => {
// TODO: Replace the demo user with the current user from your system
const user = demoUser;
console.log("Requesting token")
// Try using a cached token if refresh isn't requested
if (!refresh) {
const token = _tokens.get(user.uid)
if (token) {
console.log("Using cached token", user.uid)
return token
}
}
// fetch access_token from server
const response = await fetch(new URL(`/api/users/${user.uid}/tokens`, process.env.NEXT_PUBLIC_WEAVY_URL), {
method: "POST",
headers: {
"content-type": "application/json",
Authorization: `Bearer ${process.env.WEAVY_APIKEY}`,
},
body: JSON.stringify({ expires_in: 3600 }),
})
if (response.ok) {
const data = await response.json()
const token = data.access_token as string
// Cache the token
_tokens.set(user.uid, token)
console.log("Requesting token", token)
// return token to UIKit
return token
} else {
throw new Error("Could not fetch token")
}
}