okupter / kitforstartups

The Open Source SvelteKit SaaS boilerplate.
https://kitforstartups.com
MIT License
705 stars 32 forks source link

Password reset link: Invalid user error #22

Open svenissimo opened 6 months ago

svenissimo commented 6 months ago

When going through the password-reset flow for email/password breaks when entering new password

Error Invalid user The user associated with this session is invalid.

Configuration

Steps

Appears that locals does not have valid user.


        try {
            const { token } = params;
            const userId = await validatePasswordResetToken(token);
            const { user } = locals;

            console.log('XXX', { user, userId });
            if (!user || user.id !== userId) {
                const feedbacks = getFeedbackObjects([
                    {
                        type: 'error',
                        title: 'Invalid user',
                        message: 'The user associated with this session is invalid.'
                    }
                ]);
ihsanmohamad commented 5 months ago

I did something like this for my project. where I add my own getUserById in my users.ts inside postgres drizzle.

try {
            const { token } = event.params;
            const userId = await validatePasswordResetToken(token);
            const user = await getUserById(userId);

            if (!user || user.id !== userId) {
                setFlash({ type: 'error', title: 'Invalid user', description: 'The user associated with this session is invalid.' }, event);
                return fail(400, {
                    form
                });
            }
            // Invalidate all sessions and update the password
            await lucia.invalidateUserSessions(userId);
            await resetPassword(userId, await new Argon2id().hash(password));

            // If the user has not verified their email, verify it now
            if (!user.emailVerified) {
                await updateUserData(userId, { emailVerified: true });
            }

            const session = await lucia.createSession(user.id, {
                createdAt: new Date(),
                updatedAt: new Date()
            });

            const sessionCookie = lucia.createSessionCookie(session.id);
            event.cookies.set(sessionCookie.name, sessionCookie.value, {
                path: '.',
                ...sessionCookie.attributes
            });
        } catch (e) {
            setFlash({ type: 'error', title: 'Invalid reset link', description: 'Your password reset link is invalid or has expired. Please try again..' }, event);
            return fail(400, {
                form
            });
        }
svenissimo commented 5 months ago

@ihsanmohamad thanks I already resolved doing almost the exact approach :)

I had contemplated raising a PR but I feel like the repo is not actively maintained.