Junior
What query should be executed to confirm user registration?
sobes.tech AI
Answer from AI
Usually, this is a PUT or POST request to an address containing the confirmation token.
Example:
// On the client side
fetch('/api/auth/confirm-email', {
method: 'PUT', // or POST
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ token: 'received_token_from_link' })
})
.then(response => {
if (!response.ok) {
throw new Error('Confirmation error');
}
return response.json();
})
.then(data => {
console.log('User confirmed:', data);
})
.catch(error => {
console.error('Error:', error);
});
// On the server side (Node.js with Express)
app.put('/api/auth/confirm-email', async (req, res) => {
const { token } = req.body;
if (!token) {
return res.status(400).json({ message: 'Token not provided' });
}
try {
// Find user by token
const user = await User.findOne({ confirmationToken: token });
if (!user) {
return res.status(404).json({ message: 'Invalid or expired token' });
}
// Set confirmation flag and clear token
user.isConfirmed = true;
user.confirmationToken = null; // Clear token after use
user.confirmationTokenExpires = null; // Clear token expiry
await user.save();
res.status(200).json({ message: 'Email successfully confirmed' });
} catch (error) {
console.error('Email confirmation error:', error);
res.status(500).json({ message: 'Server error during email confirmation' });
}
});