Refactored code.

This commit is contained in:
Michael Mainguy 2023-11-06 05:32:01 -06:00
parent 1ae2dd3609
commit 80ef1b595f

View File

@ -1,10 +1,11 @@
import {Context} from "@netlify/functions"; import {Context} from "@netlify/functions";
import axios from 'axios'; import axios from 'axios';
export default async (req: Request, context: Context) => { const baseurl = 'https://syncdb-service-d3f974de56ef.herokuapp.com/';
try { const auth = 'admin:stM8Lnm@Cuf-tWZHv';
console.log(req.method); const authToken = Buffer.from(auth).toString('base64');
const origin = req.headers['origin'];
function buildOptions(req: Request) {
if (req.method == 'OPTIONS') { if (req.method == 'OPTIONS') {
return new Response( return new Response(
new Blob(), new Blob(),
@ -18,34 +19,39 @@ export default async (req: Request, context: Context) => {
}, },
status: 200 status: 200
}) })
} else {
return null;
} }
const baseurl = 'https://syncdb-service-d3f974de56ef.herokuapp.com/'; }
console.log(baseurl);
const params = JSON.parse(await req.text());
console.log(params);
const dbKey = params.username; type Params = {
const password = params.password; username: string,
password: string
}
if (!dbKey || !password) { async function checkIfDbExists(params: Params) {
console.log(params); console.log("Checking if DB exists");
if (!params.username || !params.password) {
throw new Error('No share key provided'); throw new Error('No share key provided');
} }
try { try {
const exist = await axios.head(baseurl + dbKey); console.log('Checking for DB');
const exist = await axios.head(baseurl + params.username);
if (exist) { if (exist) {
return return true;
new Response('OK');
} }
} catch (err) { } catch (err) {
console.log("DB not Found");
console.log(err); console.log(err);
} }
const auth = 'admin:stM8Lnm@Cuf-tWZHv'; return false;
const authToken = Buffer.from(auth).toString('base64'); }
async function createDB(params: Params) {
console.log("Creating DB");
const response = await axios.put( const response = await axios.put(
baseurl + dbKey, baseurl + params.username,
{}, {},
{ {
headers: { headers: {
@ -55,10 +61,19 @@ export default async (req: Request, context: Context) => {
} }
}); });
const data = await response.data; const data = await response.data;
if (response.status == 201) { console.log(JSON.stringify(response));
const response2 = await axios.put( return data;
baseurl + '_users/org.couchdb.user:' + dbKey, }
{_id: 'org.couchdb.user:' + dbKey, name: dbKey, password: password, roles: [], type: 'user'},
async function createUser(params: Params) {
console.log("Creating User");
const userResponse = await axios.put(
baseurl + '_users/org.couchdb.user:' + params.username,
{
_id: 'org.couchdb.user:' + params.username,
name: params.username,
password: params.password, roles: [], type: 'user'
},
{ {
headers: { headers: {
'Authorization': 'Basic ' + authToken, 'Authorization': 'Basic ' + authToken,
@ -66,10 +81,14 @@ export default async (req: Request, context: Context) => {
'Accept': 'application/json' 'Accept': 'application/json'
} }
}); });
data.auth = response2.data; return userResponse;
const authresponse = await axios.put( }
baseurl + dbKey + '/_security',
{admins: {names: [], roles: []}, members: {names: [dbKey], roles: []}}, async function authorizeUser(params: Params) {
console.log("Authorizing User");
return await axios.put(
baseurl + params.username + '/_security',
{admins: {names: [], roles: []}, members: {names: [params.username], roles: []}},
{ {
headers: { headers: {
'Authorization': 'Basic ' + authToken, 'Authorization': 'Basic ' + authToken,
@ -77,10 +96,38 @@ export default async (req: Request, context: Context) => {
'Accept': 'application/json' 'Accept': 'application/json'
} }
}); });
}
export default async (req: Request, context: Context) => {
console.log(req.method);
const origin = req.headers['origin'];
const options = buildOptions(req);
if (options) {
return options;
} }
return
new Response( try {
new Blob(), const params = JSON.parse(await req.text());
console.log(params);
const exists = await checkIfDbExists(params);
if (exists) {
return new Response("OK");
}
const createDbResponse = await createDB(params);
if (createDbResponse.status != 201) {
throw new Error('Could not create DB');
}
const createUserResponse = await createUser(params);
if (createUserResponse.status != 201) {
throw new Error('Could not create User');
}
const authorizeUserResponse = await authorizeUser(params);
if (authorizeUserResponse.status != 200) {
throw new Error('could not authorize user');
}
return new Response(
"OK",
{ {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -93,8 +140,7 @@ export default async (req: Request, context: Context) => {
} catch (err) { } catch (err) {
console.log(err); console.log(err);
const response = {err: err}; const response = {err: err};
return return new Response(JSON.stringify(response),
new Response(JSON.stringify(response),
{status: 500} {status: 500}
) )
} }