Skip to content

Commit

Permalink
feat: delete user from kinde (#564)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dun-sin authored Oct 31, 2023
1 parent 5dd5755 commit f2fefa8
Showing 1 changed file with 50 additions and 10 deletions.
60 changes: 50 additions & 10 deletions server/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ const getAccessToken = async () => {
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
audience: `${domain}/api`,
}),
});

Expand All @@ -62,23 +63,46 @@ const getAccessToken = async () => {
}
};

const checkIfUserExistsInKinde = async (email) => {
const headers = {
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
};

const getKindeUser = async (email) => {
const response = await fetch(`${domain}/api/v1/users?email=${email}`, {
method: 'GET',
headers: headers,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
});
const data = await response.json();
return data.users ? true : false;
let data;
if (!response.ok) {
const errorText = await response.json(); // Capture the error response text
if (errorText.errors[1].code === 'TOKEN_INVALID') {
const newAccessToken = await getAccessToken();
accessToken = newAccessToken;

const response = await fetch(`${domain}/api/v1/users?email=${email}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${newAccessToken}`,
},
});

data = await response.json();
} else {
console.log(errorText);
throw new Error(`Couldn't get user from kinde`);
}
} else {
data = await response.json();
}
return data;
};

const createUserWithId = async (email, id) => {
// Logic to create a new user with a provided ID
const doesUserExist = await checkIfUserExistsInKinde(email);
const getUser = await getKindeUser(email);
const doesUserExist = getUser.users ? true : false;

if (doesUserExist) {
return User.create({ _id: id, email });
Expand Down Expand Up @@ -222,6 +246,22 @@ const deleteUser = async (req, res) => {
return res.status(NOT_FOUND).json({ error: 'User not found' });
}

const kindeUser = await getKindeUser(email);
const kindeUserId = kindeUser.users[0].id;

// delte user from kinde
const response = await fetch(`${domain}/api/v1/user?id=${kindeUserId}`, {
method: 'DELETE',

headers: {
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
});

if (!response.ok) {
throw new Error(response.text());
}
// Delete the user
await user.deleteOne();

Expand Down

1 comment on commit f2fefa8

@vercel
Copy link

@vercel vercel bot commented on f2fefa8 Oct 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.