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.
This commit is contained in:
caelum0x 2026-10-24 04:58:48 +03:00
parent ca5c909077
commit 8a9dd77a78
7 changed files with 175 additions and 21 deletions

View File

@ -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)

View File

@ -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
);

View File

@ -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 } });
});
});

View File

@ -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<boolean | null>(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() {
<Text style={styles.listItem}>• All your saved content</Text>
</View>
{hasPassword && (
<>
<Text style={styles.confirmLabel}>Confirm with your password:</Text>
<TextInput
style={styles.input}
value={password}
onChangeText={setPassword}
placeholder="Password"
placeholderTextColor={Colors.textSecondary}
secureTextEntry
autoCapitalize="none"
autoCorrect={false}
/>
</>
)}
<Text style={styles.confirmLabel}>
Type <Text style={styles.confirmWord}>DELETE</Text> to confirm:
</Text>
@ -169,4 +216,3 @@ const styles = StyleSheet.create({
fontWeight: '600',
},
});

View File

@ -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;
},

View File

@ -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<boolean | null>(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() {
</div>
<div className="space-y-4">
{hasPassword && (
<div>
<label className="block text-sm font-medium text-foreground mb-2">
Confirm with your password
</label>
<input
type="password"
value={password}
onChange={(e) => 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"
/>
</div>
)}
<div>
<label className="block text-sm font-medium text-foreground mb-2">
Type <strong>DELETE</strong> to confirm
@ -79,4 +122,3 @@ export default function DeleteAccountPage() {
</div>
)
}

View File

@ -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
},