Skip to content

Commit 15982df

Browse files
committed
correct errors
1 parent 60f8da7 commit 15982df

File tree

3 files changed

+20
-22
lines changed

3 files changed

+20
-22
lines changed

controllers/auth.js

+15-17
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,15 @@ const register = async(req, res) => {
2222
// 10 - сіль - набір випадкових символів - складність алгоритму генерації солі
2323

2424
const avatarURL = gravatar.url(email); // генеруємо посилання на тимчасову аватарку по email-у користувача
25-
const verificationCode = nanoid();
26-
const newUser = await User.create({ ...req.body, password: hashPassword, avatarURL, verificationCode }) // в БД зберігаємо пароль у захешованому вигляді (post-запит)
25+
const verificationToken = nanoid();
26+
const newUser = await User.create({ ...req.body, password: hashPassword, avatarURL, verificationToken }) // в БД зберігаємо пароль у захешованому вигляді (post-запит)
2727

2828
const verifyEmail = {
2929
to: email, // кому буде приходити email на підтвердження (можна використати тимчасову пошту на https://temp-mail.org/uk/)
30-
subject: 'Verify email 2',
31-
html: `<a target='_blank' href="${BASE_URL}/api/auth/verify/${verificationCode}">Let's verify your email so you can start login. Click here to verify.</a>`
30+
subject: 'Verify email 7',
31+
html: `<a target='_blank' href="${BASE_URL}/api/auth/verify/${verificationToken}">Let's verify your email so you can start login. Click here to verify.</a>`
3232
} // при переході за посиланням спрацьовує GET-запит
33-
// Congratulations! Your sender identity has been successfully verified.
33+
3434
await sendEmail(verifyEmail);
3535

3636
res.status(201).json({
@@ -44,38 +44,36 @@ const register = async(req, res) => {
4444

4545
// Зміна статусу email-у на "верифікований" та очищення верифікаційного коду в БД після підтвердження пошти в отриманому листі
4646
const verifyEmail = async(req, res) => {
47-
const { verificationCode } = req.params;
48-
const user = await User.findOne({verificationCode}); // перевіряємо чи є в БД користувач з таким кодом
47+
const { verificationToken } = req.params;
48+
const user = await User.findOne({ verificationToken }); // перевіряємо чи є в БД користувач з таким кодом
4949
if(!user) {
5050
throw HttpError(401, 'Email is not found')
5151
}
52-
await User.findByIdAndUpdate(user._id, {verify: true, verificationCode: ''}); // якщо є такий користувач, то вносимо зміни до БД
53-
54-
console.log('user:', user);
52+
await User.findByIdAndUpdate(user._id, { verify: true, verificationToken: "" }); // якщо є такий користувач, то вносимо зміни до БД
5553

5654
res.json({
57-
message: "The email is successfully verified."
55+
message: "Congratulations! The email has been successfully verified."
5856
})
5957
};
6058

6159
const resendVerifyEmail = async(req, res) => {
6260
const { email } = req.body;
63-
const user = await User.findOne({email});
61+
const user = await User.findOne({ email });
6462
if(!user){
6563
throw HttpError(401, 'Email is not found');
6664
}
67-
if(user.verify) { //якщо користувач не підтвердив email (user.verify = false)
68-
throw HttpError(401, 'The email is already verified')
65+
if(user.verify) { //якщо користувач вже підтвердив email (user.verify = true)
66+
throw HttpError(401, 'The email is already verified') // не спрацює, бо спочатку Postman видасть "Email already in use"
6967
}
7068
const verifyEmail = {
7169
to: email,
7270
subject: 'Verify email',
73-
html: `<a target='_blank' href="${BASE_URL}/api/auth/verify/${user.verificationCode}">Let's verify your email so you can start login. Click here to verify.</a>`,
71+
html: `<a target='_blank' href="${BASE_URL}/api/auth/verify/${user.verificationToken}">Let's verify your email so you can start login. Click here to verify.</a>`,
7472
};
75-
await sendEmail(verifyEmail);
73+
await sendEmail(verifyEmail); //якщо користувач ще не підтвердив email
7674

7775
res.json({
78-
message: 'Verification email is resent.'
76+
message: 'Congratulations! The email has been successfully verified.'
7977
})
8078
}
8179

models/user.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,10 @@ const userSchema = new Schema({ //mongoose-схема - перевіряє те
3434
type: Boolean,
3535
default: false // після реєстрації, але до логіну - false
3636
},
37-
verificationCode: { // або verificationToken - код (згенерований nanoid), що зашитий у лінку, що приходить на пошту для підтвердження email-у
37+
verificationToken: { // або verificationCode - код (згенерований nanoid), що зашитий у лінку, що приходить на пошту для підтвердження email-у
3838
type: String,
3939
default: '',
40-
required: [true, 'Token verification is required']
40+
// required: [true, 'Token verification is required'] // не працює
4141
}
4242
}, { versionKey: false, timestamps: true });
4343

routes/api/auth.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@ const router = express.Router();
88

99
router.post('/register', validateBody(schemas.registerSchema), authCtrl.register); //signup
1010

11-
router.get('/verify/:verificationCode', authCtrl.verifyEmail);
12-
router.post('/verify', validateBody(schemas.emailSchema), authCtrl.resendVerifyEmail);
11+
router.get('/verify/:verificationToken', authCtrl.verifyEmail); // на пошту приходить лист з посиланням для верифікації (при переході по ньому спрацьовує цей GET-запит)
12+
router.post('/verify', validateBody(schemas.emailSchema), authCtrl.resendVerifyEmail);
1313

1414
router.post('/login', validateBody(schemas.loginSchema), authCtrl.login); //signin
1515

16-
router.get('/current', authenticate, authCtrl.getCurrent);
16+
router.get('/current', authenticate, authCtrl.getCurrent); // отримання поточного користувача
1717
router.patch('/subscription', authenticate, validateBody(schemas.subscriptionSchema), authCtrl.updateSubscription);
1818
router.post('/logout', authenticate, authCtrl.logout);
1919
router.patch('/avatars', authenticate, upload.single('avatar'), authCtrl.updateAvatar); //можливість змінити аватарку

0 commit comments

Comments
 (0)