Skip to content
Draft
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
27 changes: 27 additions & 0 deletions backend/src/auth/__tests__/auth-copy-capability.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { AuthResolver } from '../auth.resolver';
import { AuthService } from '../auth.service';

// No password operations are under test. Avoid requiring a native bcrypt
// binary just to read a deployment-wide boolean.
jest.mock('bcrypt', () => ({ hash: jest.fn(), compare: jest.fn() }));
jest.mock('sqlite3', () => ({ Database: jest.fn() }));

describe('password reset email availability', () => {
it.each([false, true])(
'reports only the global mail flag (%s)',
(enabled) => {
// Exercise the real service getter and resolver without an account, mail
// server, or database. This capability must never look up an address.
const service = Object.create(AuthService.prototype) as AuthService;
Object.defineProperty(service, 'isMailEnabled', { value: enabled });
Object.defineProperty(service, 'userRepository', {
get: () => {
throw new Error('A global capability must not inspect any account');
},
});
expect(new AuthResolver(service).passwordResetEmailAvailable()).toBe(
enabled,
);
},
);
});
13 changes: 12 additions & 1 deletion backend/src/auth/auth.resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ export class AuthResolver {
return process.env.MAIL_ENABLED?.toLowerCase() === 'true';
}

/** Never offer email recovery when this deployment cannot send it. */
@Query(() => Boolean)
@Public()
passwordResetEmailAvailable(): boolean {
return this.authService.passwordResetEmailAvailable;
}

/**
* Whether "Continue with Google" can actually work. The strategy boots on
* placeholder credentials when unconfigured, so the button used to send
Expand Down Expand Up @@ -116,7 +123,11 @@ export class AuthResolver {
@Args('currentPassword') currentPassword: string,
@Args('newPassword') newPassword: string,
): Promise<RefreshTokenResponse> {
return this.authService.changePassword(userId, currentPassword, newPassword);
return this.authService.changePassword(
userId,
currentPassword,
newPassword,
);
}

/**
Expand Down
7 changes: 6 additions & 1 deletion backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@
this.isMailEnabled = this.configService.isMailEnabled;
}

/** Deployment-wide mail capability, independent of any account or address. */
get passwordResetEmailAvailable(): boolean {
return this.isMailEnabled;
}

async confirmEmail(token: string): Promise<EmailConfirmationResponse> {
try {
const payload = await this.jwtService.verifyAsync(token);
Expand Down Expand Up @@ -83,7 +88,7 @@
message: 'Email already confirmed or user not found.',
success: false,
};
} catch (error) {

Check warning on line 91 in backend/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / autofix

'error' is defined but never used
return {
message: 'Invalid or expired token',
success: false,
Expand Down Expand Up @@ -181,7 +186,7 @@
): Promise<EmailConfirmationResponse> {
const same = {
message:
'If that address has an account, a reset link is on its way. Check your inbox.',
'If this account can receive password reset email, check your inbox for a reset link.',
success: true,
};

Expand Down Expand Up @@ -492,7 +497,7 @@
});

return true;
} catch (error) {

Check warning on line 500 in backend/src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / autofix

'error' is defined but never used
return false;
}
}
Expand Down
19 changes: 19 additions & 0 deletions frontend/jest.auth-copy.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module.exports = {
rootDir: '.',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/src/**/__tests__/auth-copy*.spec.ts?(x)'],
moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1' },
setupFilesAfterEnv: ['@testing-library/jest-dom'],
transform: {
'^.+\\.tsx?$': [
'ts-jest',
{
tsconfig: {
jsx: 'react-jsx',
module: 'commonjs',
moduleResolution: 'node',
},
},
],
},
};
21 changes: 11 additions & 10 deletions frontend/src/app/auth/confirm/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from '@/components/ui/texture-card';
import { AlertCircle, CheckCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { getVerificationFailureMessage } from '@/lib/auth-copy';

export default function ConfirmEmailPage() {
const searchParams = useSearchParams();
Expand All @@ -25,21 +26,19 @@ export default function ConfirmEmailPage() {
onCompleted: (data) => {
if (data.confirmEmail.success) {
setStatus('success');
setMessage(data.confirmEmail.message || 'Email verified successfully!');
setMessage('Email verified. You can sign in now.');
// Redirect to home page after a short delay
setTimeout(() => {
router.push('/');
}, 3000);
} else {
setStatus('error');
setMessage(data.confirmEmail.message || 'Failed to verify email.');
setMessage(getVerificationFailureMessage(data.confirmEmail.message));
}
},
onError: (error) => {
onError: () => {
setStatus('error');
setMessage(
error.message || 'An error occurred while verifying your email.'
);
setMessage('We couldn’t verify your email. Try opening the link again.');
},
});

Expand All @@ -48,7 +47,9 @@ export default function ConfirmEmailPage() {

if (!token) {
setStatus('error');
setMessage('Invalid verification link. No token provided.');
setMessage(
'This verification link is incomplete. Open the full link from your CodeFox email.'
);
return;
}

Expand All @@ -65,7 +66,7 @@ export default function ConfirmEmailPage() {
<BackgroundGradient className="rounded-[22px] p-4 bg-background max-w-md w-full">
<TextureCardHeader className="flex flex-col gap-2 items-center justify-center p-4">
<TextureCardTitle className="text-center text-2xl">
Email Verification
Verify your email
</TextureCardTitle>

<div className="mt-4 flex items-center justify-center">
Expand All @@ -86,13 +87,13 @@ export default function ConfirmEmailPage() {

{status === 'success' && (
<p className="text-sm text-muted-foreground">
You will be redirected to the home page shortly...
Returning to CodeFox…
</p>
)}

{status === 'error' && (
<Button onClick={() => router.push('/')} className="mt-4">
Go to Home Page
Back to CodeFox
</Button>
)}
</TextureCardContent>
Expand Down
18 changes: 11 additions & 7 deletions frontend/src/app/auth/oauth-callback/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,19 @@ export default function OAuthCallbackPage() {
// Handle error cases
if (error) {
console.error('Authentication error:', error);
toast.error('Authentication failed');
toast.error(
'Google sign-in didn’t finish. Return to CodeFox and try again.'
);
router.push('/');
return;
}

// Check if tokens exist
if (!accessToken || !refreshToken) {
console.error('Missing tokens in callback');
toast.error('Authentication failed: Missing tokens');
toast.error(
'Google sign-in didn’t finish. Return to CodeFox and try again.'
);
router.push('/');
return;
}
Expand All @@ -40,13 +44,15 @@ export default function OAuthCallbackPage() {
login(accessToken, refreshToken);

// Show success message
toast.success('Logged in successfully!');
toast.success('Signed in');

// Redirect to home or dashboard
router.push('/');
} catch (error) {
console.error('Error processing authentication:', error);
toast.error('Authentication processing failed');
toast.error(
'Google sign-in didn’t finish. Return to CodeFox and try again.'
);
router.push('/');
}
};
Expand All @@ -57,9 +63,7 @@ export default function OAuthCallbackPage() {
return (
<div className="flex h-screen w-full items-center justify-center">
<div className="text-center p-8 max-w-md rounded-xl bg-background shadow-lg">
<h1 className="text-2xl font-bold mb-4">
Completing authentication...
</h1>
<h1 className="text-2xl font-bold mb-4">Signing you in…</h1>
<p className="text-muted-foreground mb-4">
Please wait while we sign you in.
</p>
Expand Down
13 changes: 8 additions & 5 deletions frontend/src/app/reset-password/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ function ResetPasswordForm() {
setError(data.resetPassword.message);
}
},
onError: () => setError('Could not reach the server. Try again.'),
onError: () => setError('We couldn’t update your password. Try again.'),
});

const submit = (e: React.FormEvent) => {
Expand Down Expand Up @@ -78,15 +78,18 @@ function ResetPasswordForm() {
{!token ? (
<div className="text-center">
<p className="mb-6">
This link is missing its token. Open the link from your email
again, or request a new one.
This reset link is incomplete. Open the full link from your
email, or go to Sign in → Forgot your password to request
another.
</p>
<Button onClick={() => router.push('/')}>Go home</Button>
<Button onClick={() => router.push('/')}>Back to CodeFox</Button>
</div>
) : done ? (
<div className="text-center">
<p className="mb-2">Password updated. You can sign in now.</p>
<p className="text-sm text-muted-foreground">Taking you home…</p>
<p className="text-sm text-muted-foreground">
Returning to CodeFox…
</p>
</div>
) : (
<form onSubmit={submit} className="space-y-4">
Expand Down
Loading
Loading