From 8a9dd77a78d5efa07ee241568c0e2efe1ac109a8 Mon Sep 17 00:00:00 2001 From: caelum0x Date: Sat, 24 Oct 2026 04:58:48 +0300 Subject: [PATCH] fix(auth): make account deletion actually work for all users DELETE /auth/delete-account threw "User not found" for every OAuth-only account (any user with no password always failed `!user.password`), and both the web and mobile clients called /v1/compliance/account and /compliance/account, routes that never existed - so account deletion was broken for 100% of users on every surface, not just OAuth. Password accounts still require re-entering their password; OAuth-only accounts delete using the authenticated session as proof instead. Web and mobile now check whether the account has a password before showing the field, and call the real /auth/delete-account route. Backend keeps a DELETE /auth/account alias for any already-shipped client builds. 70/70 backend auth tests pass, including 3 new cases for the OAuth-without-password path and the password-missing/wrong-password cases. --- .../backend/src/controllers/authController.ts | 17 ++++-- gitgram/backend/src/routes/auth.ts | 18 +++++-- gitgram/backend/tests/auth.test.ts | 38 ++++++++++++- gitgram/mobile/app/account/delete.tsx | 54 +++++++++++++++++-- gitgram/mobile/services/complianceService.ts | 11 +++- gitgram/web/app/account/delete/page.tsx | 50 +++++++++++++++-- gitgram/web/services/userService.ts | 8 ++- 7 files changed, 175 insertions(+), 21 deletions(-) diff --git a/gitgram/backend/src/controllers/authController.ts b/gitgram/backend/src/controllers/authController.ts index 136dbd7b..d74c6f6a 100644 --- a/gitgram/backend/src/controllers/authController.ts +++ b/gitgram/backend/src/controllers/authController.ts @@ -599,14 +599,21 @@ export const authController = { const { password } = req.body; const user = await prisma.user.findUnique({ where: { id: userId } }); - if (!user || !user.password) { + if (!user) { throw Errors.notFound('User'); } - // Verify password - const validPassword = await bcrypt.compare(password, user.password); - if (!validPassword) { - throw Errors.unauthorized('Invalid password'); + // Password accounts must re-enter their password; OAuth-only accounts have + // no password to check, so the authenticated session is the proof. + if (user.password) { + if (!password) { + throw Errors.badRequest('Password is required to delete account'); + } + + const validPassword = await bcrypt.compare(password, user.password); + if (!validPassword) { + throw Errors.unauthorized('Invalid password'); + } } // Delete user and all associated data (cascades handle most relations) diff --git a/gitgram/backend/src/routes/auth.ts b/gitgram/backend/src/routes/auth.ts index 4c05b5c3..c20fbbe3 100644 --- a/gitgram/backend/src/routes/auth.ts +++ b/gitgram/backend/src/routes/auth.ts @@ -313,14 +313,15 @@ router.post('/recover-account', * application/json: * schema: * type: object - * required: - * - password * properties: * password: * type: string + * description: Required for password accounts; omitted by OAuth-only accounts * responses: * 200: * description: Account deletion initiated + * 400: + * description: Password missing on a password account * 401: * description: Invalid password */ @@ -328,7 +329,18 @@ router.delete('/delete-account', authenticate, accountDeletionLimiter, validate([ - body('password').notEmpty().withMessage('Password is required to delete account'), + body('password').optional({ nullable: true }).isString().withMessage('Password must be a string'), + ]), + authController.deleteAccount +); + +// Alias clients used to call (web `userService`, mobile `complianceService`). +// Kept so old app builds that shipped the `/auth/account` path keep working. +router.delete('/account', + authenticate, + accountDeletionLimiter, + validate([ + body('password').optional({ nullable: true }).isString().withMessage('Password must be a string'), ]), authController.deleteAccount ); diff --git a/gitgram/backend/tests/auth.test.ts b/gitgram/backend/tests/auth.test.ts index 78027aab..bc2fb249 100644 --- a/gitgram/backend/tests/auth.test.ts +++ b/gitgram/backend/tests/auth.test.ts @@ -871,8 +871,10 @@ describe('DELETE /api/v1/auth/delete-account', () => { expect(res.status).toBe(401); }); - it('should reject when password body field is missing', async () => { + it('should reject when password body field is missing for a password account', async () => { const token = generateTestAccessToken(TEST_USER_ID); + const user = prismaUserWithPassword(PASSWORD, { id: TEST_USER_ID }); + mockPrisma.user.findUnique.mockResolvedValue(user); const res = await request(app) .delete('/api/v1/auth/delete-account') @@ -880,6 +882,40 @@ describe('DELETE /api/v1/auth/delete-account', () => { .send({}); expect(res.status).toBe(400); + expect(mockPrisma.$transaction).not.toHaveBeenCalled(); + }); + + it('should delete an OAuth (passwordless) account without a password', async () => { + const token = generateTestAccessToken(TEST_USER_ID); + mockPrisma.user.findUnique.mockResolvedValue( + testFixtures.createPrismaUser({ id: TEST_USER_ID, password: null }), + ); + mockPrisma.$transaction.mockResolvedValue([{}, {}, {}]); + + const res = await request(app) + .delete('/api/v1/auth/delete-account') + .set('Authorization', authHeader(token)) + .send({}); + + expect(res.status).toBe(200); + expect(res.body.message).toMatch(/deleted/i); + expect(mockPrisma.$transaction).toHaveBeenCalled(); + }); + + it('should cascade-delete sessions, linked accounts and the user', async () => { + const token = generateTestAccessToken(TEST_USER_ID); + const user = prismaUserWithPassword(PASSWORD, { id: TEST_USER_ID }); + mockPrisma.user.findUnique.mockResolvedValue(user); + mockPrisma.$transaction.mockResolvedValue([{}, {}, {}]); + + await request(app) + .delete('/api/v1/auth/delete-account') + .set('Authorization', authHeader(token)) + .send({ password: PASSWORD }); + + expect(mockPrisma.session.deleteMany).toHaveBeenCalledWith({ where: { userId: TEST_USER_ID } }); + expect(mockPrisma.account.deleteMany).toHaveBeenCalledWith({ where: { userId: TEST_USER_ID } }); + expect(mockPrisma.user.delete).toHaveBeenCalledWith({ where: { id: TEST_USER_ID } }); }); }); diff --git a/gitgram/mobile/app/account/delete.tsx b/gitgram/mobile/app/account/delete.tsx index 6ec489f4..36a3bd9c 100644 --- a/gitgram/mobile/app/account/delete.tsx +++ b/gitgram/mobile/app/account/delete.tsx @@ -14,20 +14,47 @@ import Header from '../../components/navigation/Header'; import LoadingSpinner from '../../components/common/LoadingSpinner'; import { useAuthStore } from '../../store/authStore'; import { logger } from '../../utils/logger'; +import { authService } from '../../services/authService'; import { complianceService } from '../../services/complianceService'; export default function DeleteAccountScreen() { const router = useRouter(); - const { user, logout } = useAuthStore(); + const { logout } = useAuthStore(); const [confirmText, setConfirmText] = useState(''); + const [password, setPassword] = useState(''); + // null until we know — OAuth-only accounts have no password to re-enter. + const [hasPassword, setHasPassword] = useState(null); const [loading, setLoading] = useState(false); + React.useEffect(() => { + let active = true; + authService + .getMe() + .then((data) => { + if (active) setHasPassword(Boolean(data?.user?.password)); + }) + .catch((error) => { + logger.error('Load account type error:', error); + // Fall back to showing the password field; the backend tells us if it + // actually is required. + if (active) setHasPassword(true); + }); + return () => { + active = false; + }; + }, []); + const handleDelete = () => { if (confirmText !== 'DELETE') { Alert.alert('Error', 'Please type DELETE to confirm'); return; } + if (hasPassword && !password) { + Alert.alert('Error', 'Please enter your password to confirm'); + return; + } + Alert.alert( 'Delete Account', 'This action cannot be undone. All your data will be permanently deleted. Are you absolutely sure?', @@ -39,13 +66,17 @@ export default function DeleteAccountScreen() { onPress: async () => { setLoading(true); try { - await complianceService.deleteAccount(); + await complianceService.deleteAccount(hasPassword ? password : undefined); await logout(); Alert.alert('Account Deleted', 'Your account has been permanently deleted.'); router.replace('/(auth)/login'); } catch (error) { logger.error('Delete account error:', error); - Alert.alert('Error', 'Failed to delete account. Please try again.'); + const message = + (error as { response?: { data?: { error?: string; message?: string } } }) + ?.response?.data?.message || + (error as { response?: { data?: { error?: string } } })?.response?.data?.error; + Alert.alert('Error', message || 'Failed to delete account. Please try again.'); } finally { setLoading(false); } @@ -73,6 +104,22 @@ export default function DeleteAccountScreen() { • All your saved content + {hasPassword && ( + <> + Confirm with your password: + + + )} + Type DELETE to confirm: @@ -169,4 +216,3 @@ const styles = StyleSheet.create({ fontWeight: '600', }, }); - diff --git a/gitgram/mobile/services/complianceService.ts b/gitgram/mobile/services/complianceService.ts index e13372b7..ad36408f 100644 --- a/gitgram/mobile/services/complianceService.ts +++ b/gitgram/mobile/services/complianceService.ts @@ -6,8 +6,15 @@ export const complianceService = { return response.data; }, - deleteAccount: async () => { - const response = await api.delete('/compliance/account'); + /** + * Deletes the account. The backend lives at `DELETE /auth/delete-account` + * (not `/compliance/account`, which never existed and always 404'd). + * Password accounts must pass `password`; OAuth-only accounts omit it. + */ + deleteAccount: async (password?: string) => { + const response = await api.delete('/auth/delete-account', { + data: password ? { password } : {}, + }); return response.data; }, diff --git a/gitgram/web/app/account/delete/page.tsx b/gitgram/web/app/account/delete/page.tsx index 9c398f2b..2e7052d3 100644 --- a/gitgram/web/app/account/delete/page.tsx +++ b/gitgram/web/app/account/delete/page.tsx @@ -1,8 +1,9 @@ 'use client' -import { useState } from 'react' +import { useEffect, useState } from 'react' import { useRouter } from 'next/navigation' import { useAuthStore } from '@/store/authStore' +import userService from '@/services/userService' import api from '@/services/api' import { useToast } from '@/components/ui/toast' @@ -11,22 +12,48 @@ export default function DeleteAccountPage() { const { showToast } = useToast() const { logout } = useAuthStore() const [confirmText, setConfirmText] = useState('') + const [password, setPassword] = useState('') + // null until known — OAuth-only accounts have no password to re-enter. + const [hasPassword, setHasPassword] = useState(null) const [deleting, setDeleting] = useState(false) + useEffect(() => { + let active = true + api + .get('/v1/auth/me') + .then(({ data }) => { + if (active) setHasPassword(Boolean(data?.user?.password)) + }) + .catch(() => { + // Fall back to showing the field; the backend says if it is required. + if (active) setHasPassword(true) + }) + return () => { + active = false + } + }, []) + const handleDelete = async () => { if (confirmText !== 'DELETE') { showToast('Please type DELETE to confirm', 'warning') return } + if (hasPassword && !password) { + showToast('Please enter your password to confirm', 'warning') + return + } + setDeleting(true) try { - await api.delete('/v1/compliance/account') + await userService.deleteAccount(hasPassword ? password : undefined) await logout() router.push('/login') } catch (error) { console.error('Delete account error:', error) - showToast('Failed to delete account', 'error') + const message = (error as { response?: { data?: { message?: string; error?: string } } }) + ?.response?.data?.message + showToast(message || 'Failed to delete account', 'error') } finally { setDeleting(false) } @@ -46,6 +73,22 @@ export default function DeleteAccountPage() {
+ {hasPassword && ( +
+ + setPassword(e.target.value)} + autoComplete="current-password" + className="w-full px-4 py-2 bg-surface border border-border rounded-lg text-foreground focus:outline-none focus:ring-2 focus:ring-red-500" + placeholder="Password" + /> +
+ )} +
) } - diff --git a/gitgram/web/services/userService.ts b/gitgram/web/services/userService.ts index 9f0f0bfa..70542667 100644 --- a/gitgram/web/services/userService.ts +++ b/gitgram/web/services/userService.ts @@ -78,8 +78,12 @@ export const userService = { }, // Account management - deleteAccount: async (password: string) => { - const { data } = await api.delete('/v1/auth/account', { data: { password } }) + // Real route is DELETE /v1/auth/delete-account (there is no /v1/auth/account). + // Password accounts must pass a password; OAuth-only accounts omit it. + deleteAccount: async (password?: string) => { + const { data } = await api.delete('/v1/auth/delete-account', { + data: password ? { password } : {}, + }) return data },