From c6951c0838700f8a7ac8c9166959843f4b379afc Mon Sep 17 00:00:00 2001 From: evlist Date: Fri, 3 Mar 2023 11:06:21 +0100 Subject: [PATCH] Fetching user doc --- src/lib/find-user-by-token.ts | 34 ++++++++++++++++++++++++++++ src/lib/headers-with-auth.ts | 3 +-- src/routes/api/conf/[token]/index.ts | 9 +++++--- 3 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 src/lib/find-user-by-token.ts diff --git a/src/lib/find-user-by-token.ts b/src/lib/find-user-by-token.ts new file mode 100644 index 0000000..e59b168 --- /dev/null +++ b/src/lib/find-user-by-token.ts @@ -0,0 +1,34 @@ +import { adminCredentials } from '~/components/credentials'; +import { headersWithAuth } from './headers-with-auth'; + +export const findUserByToken = async ( + token: string, + credentials = adminCredentials() +) => { + const db = 'dyomedea_users'; + if (!credentials) { + return null; + } + const { database } = credentials; + + const headers = headersWithAuth(credentials); + if (!headers) { + return null; + } + headers.set('Content-Type', 'application/json'); + + const params = { + selector: { + token, + }, + }; + + const response = await fetch(`${database}/${db}/_find`, { + method: 'POST', + mode: 'cors', + headers, + body: JSON.stringify(params), + }); + + return (await response.json()).docs[0]; +}; diff --git a/src/lib/headers-with-auth.ts b/src/lib/headers-with-auth.ts index 9078e19..04063b9 100644 --- a/src/lib/headers-with-auth.ts +++ b/src/lib/headers-with-auth.ts @@ -1,7 +1,6 @@ import { adminCredentials } from '~/components/credentials'; -export const headersWithAuth = () => { - const credentials = adminCredentials(); +export const headersWithAuth = (credentials = adminCredentials()) => { if (!credentials) { return null; } diff --git a/src/routes/api/conf/[token]/index.ts b/src/routes/api/conf/[token]/index.ts index a8817cc..eaa59f0 100644 --- a/src/routes/api/conf/[token]/index.ts +++ b/src/routes/api/conf/[token]/index.ts @@ -1,8 +1,11 @@ import { APIEvent, json } from 'solid-start/api'; +import { findUserByToken } from '~/lib/find-user-by-token'; import { readConfig } from '~/server-only-lib/read-config'; -export async function GET({ params, env }: APIEvent) { - const {credentials} = readConfig(); +export async function GET({ params }: APIEvent) { + const { credentials } = readConfig(); console.log({ caller: 'api/conf GET', params, credentials }); - return json({ params, env, response: 'OK' }); + const user = await findUserByToken(params.token, credentials); + console.log({ caller: 'api/conf GET', params, credentials, user }); + return json({ params, response: 'OK' }); }