|
| 1 | +const path = require('path'); |
| 2 | +const Newsletter = require('../models/newsletter'); |
| 3 | +const Subscription = require('../models/subscription'); |
| 4 | +const sendMail = require('mailer').send; |
| 5 | +const config = require('config'); |
| 6 | + |
| 7 | +// subscribe a single newsletter (post from somewhere outside of the module) |
| 8 | +exports.post = function*() { |
| 9 | + |
| 10 | + const newsletter = yield Newsletter.findOne({ |
| 11 | + slug: this.request.body.slug |
| 12 | + }).exec(); |
| 13 | + |
| 14 | + if (!newsletter) { |
| 15 | + this.throw(404, "Нет такой рассылки"); |
| 16 | + } |
| 17 | + |
| 18 | + if (this.req.user && this.req.user.email == this.request.body.email) { |
| 19 | + // registered users need no confirmation |
| 20 | + |
| 21 | + var subscription = yield Subscription.findOne({ |
| 22 | + email: this.request.body.email |
| 23 | + }).exec(); |
| 24 | + |
| 25 | + if (subscription) { |
| 26 | + subscription.newsletters.addToSet(newsletter._id); |
| 27 | + subscription.confirmed = true; |
| 28 | + } else { |
| 29 | + subscription = new Subscription({ |
| 30 | + email: this.request.body.email, |
| 31 | + newsletters: [newsletter._id], |
| 32 | + confirmed: true |
| 33 | + }); |
| 34 | + } |
| 35 | + |
| 36 | + yield subscription.persist(); |
| 37 | + |
| 38 | + this.body = { |
| 39 | + message: `Вы успешно подписаны, ждите писем на адрес ${subscription.email}.` |
| 40 | + }; |
| 41 | + |
| 42 | + } else { |
| 43 | + var subscription = yield Subscription.findOne({ |
| 44 | + email: this.request.body.email |
| 45 | + }).exec(); |
| 46 | + |
| 47 | + if (!subscription) { |
| 48 | + subscription = new Subscription({ |
| 49 | + email: this.request.body.email, |
| 50 | + confirmed: false |
| 51 | + }); |
| 52 | + } |
| 53 | + |
| 54 | + subscription.newsletters.addToSet(newsletter._id); |
| 55 | + |
| 56 | + yield subscription.persist(); |
| 57 | + |
| 58 | + if (subscription.confirmed) { |
| 59 | + this.body = { |
| 60 | + message: `Вы успешно подписаны.` |
| 61 | + }; |
| 62 | + } else { |
| 63 | + |
| 64 | + yield sendMail({ |
| 65 | + templatePath: path.join(this.templateDir, 'confirm-email'), |
| 66 | + subject: "Подтверждение подписки на JavaScript.ru", |
| 67 | + to: subscription.email, |
| 68 | + link: (config.server.siteHost || 'http://javascript.in') + '/newsletter/confirm/' + subscription.accessKey |
| 69 | + }); |
| 70 | + |
| 71 | + this.body = { |
| 72 | + message: `Проверьте почту ${subscription.email} и подтвердите подписку, перейдя по ссылке в письме.` |
| 73 | + }; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + |
| 78 | +}; |
| 79 | + |
0 commit comments