Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion netlify/functions-src/functions/admin/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ const getAdminAccessToken = async (): Promise<string> => {
const data = await response.json();
return data.access_token;
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error fetching admin access token:', error);
throw new Error('Failed to fetch access token');
}
Expand Down
1 change: 0 additions & 1 deletion netlify/functions-src/functions/email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ export const handler: Handler = async (event) => {
body: JSON.stringify({ message: 'Email sent successfully' }),
};
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error sending email:', error);
return {
statusCode: 500,
Expand Down
2 changes: 0 additions & 2 deletions netlify/functions-src/functions/email/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ export const send = async (params: EmailParams) => {
html: content,
});
} catch (error) {
// eslint-disable-next-line no-console
console.error('Send email error', params, JSON.stringify(error, null, 2));
throw new Error('Failed to send email');
}
Expand Down Expand Up @@ -47,7 +46,6 @@ const getTemplateContent = async (name: string) => {
encoding: 'utf8',
});
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error reading template file:', error);
throw new Error(`Template file not found: ${templatePath}`);
}
Expand Down
15 changes: 11 additions & 4 deletions netlify/functions-src/functions/modules/users/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,37 +7,44 @@ import { deleteUser as deleteUserFromAuth0 } from '../../admin/delete';
import { success } from '../../utils/response';

const deleteUserAccount = async ({ _id, auth0Id }: Pick<User, '_id' | 'auth0Id'>) => {
console.log('Deleting user from DB:', { userId: _id.toString(), auth0Id });
const result = await deleteUser(_id);
console.log('User deleted from DB:', { userId: _id.toString(), result });
deleteUserFromAuth0(auth0Id)
.then(result => {
// eslint-disable-next-line no-console
console.log('User deleted from Auth0:', result);
})
.catch(error => {
// eslint-disable-next-line no-console
console.error('Error deleting user from Auth0:', error);
});
return result;
};

// A user deleting their own account
export const handler: ApiHandler<unknown, User> = async (event, context) => {
console.log('Self delete requested:', { userId: context.user._id.toString() });
const result = await deleteUserAccount(context.user);
return success({ data: result }, 204);
};

// An admin deleting any user's account. Must be wrapped with `withAuth(..., { role: Role.ADMIN })`
export const adminDeleteHandler: ApiHandler<unknown, User> = async (event) => {
export const adminDeleteHandler: ApiHandler<unknown, User> = async (event, context) => {
const { userId } = event.queryStringParameters ?? {};
console.log('Admin delete requested:', { adminId: context.user?._id?.toString(), userId });

if (!userId || !ObjectId.isValid(userId)) {
console.error('Admin delete rejected: invalid user id', { userId });
throw new DataError(400, 'Invalid user id');
}

const user = await getUserBy('_id', new ObjectId(userId));
if (!user) {
console.error('Admin delete failed: user not found', { userId });
throw new DataError(404, 'User not found');
}

const result = await deleteUserAccount(user);
return success({ data: result }, 204);
console.log('Admin delete completed:', { adminId: context.user?._id?.toString(), userId });
// 200 with a body (not 204) so the client can parse the response
return success({ data: result });
};
6 changes: 5 additions & 1 deletion netlify/functions-src/functions/modules/users/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,15 @@ import { success } from '../../utils/response';
type UserSuggestion = Pick<User, '_id' | 'name' | 'email' | 'avatar'>;

// Admin only. Must be wrapped with `withAuth(..., { role: Role.ADMIN })`
export const adminSearchHandler: ApiHandler<unknown, UserSuggestion[]> = async (event) => {
export const adminSearchHandler: ApiHandler<unknown, UserSuggestion[]> = async (event, context) => {
const query = (event.queryStringParameters?.q ?? '').trim();
// query itself is not logged since it may contain an email address
console.log('Admin user search requested:', { adminId: context.user?._id?.toString(), queryLength: query.length });
if (query.length < 2) {
console.error('Admin user search rejected: query too short');
throw new DataError(400, 'Query must be at least 2 characters');
}
const users = await searchUsers(query);
console.log('Admin user search completed:', { results: users.length });
return success({ data: users });
};
12 changes: 11 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,17 @@
"message": "Do not use `sessionStorage` directly, use the storage wrapper instead"
}
]
}
},
"overrides": [
{
"files": [
"netlify/functions-src/**/*"
],
"rules": {
"no-console": "off"
}
}
]
},
"browserslist": [
">0.2%",
Expand Down
5 changes: 5 additions & 0 deletions src/Me/Routes/Admin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import Input from '../components/Input';
import { Loader } from '../../components/Loader';
import { getChannelInfo } from '../../channelProvider';
import { useApi } from '../../context/apiContext/ApiContext';
import { useRoutes } from '../../hooks/useRoutes';

const Mentee = styled.span`
display: flex;
Expand Down Expand Up @@ -139,6 +140,7 @@ const Admin = () => {
MentorshipRequest[]
>([]);
const api = useApi()
const routes = useRoutes();

const filteredMentorshipRequests = useMemo(() => {
return mentorshipRequests
Expand Down Expand Up @@ -269,6 +271,9 @@ const Admin = () => {
mentorships={filteredMentorshipRequests}
/>
)}
<Card>
<a href={routes.me.admin.deleteUser.get()}>Delete a user</a>
</Card>
<Card className='wide'>
<Filters>
<FormField>
Expand Down
15 changes: 10 additions & 5 deletions src/Me/Routes/AdminDeleteUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,16 @@ const AdminDeleteUser = () => {
return;
}
setIsDeleting(true);
const deleted = await deleteUserAccount(api, selected._id);
setIsDeleting(false);
if (deleted) {
toast.success(`${selected.name} was deleted`);
setSelected(null);
try {
const deleted = await deleteUserAccount(api, selected._id);
if (deleted) {
toast.success(`${selected.name} was deleted`);
setSelected(null);
} else {
toast.error(`Failed to delete ${selected.name}`);
}
} finally {
setIsDeleting(false);
}
};

Expand Down
Loading