1 | module.exports = requestRoutes
|
2 | module.exports.attributes = {
|
3 | name: 'account-routes-requests'
|
4 | }
|
5 |
|
6 | var Boom = require('boom')
|
7 | var nodemailer = require('nodemailer')
|
8 | var randomstring = require('randomstring')
|
9 |
|
10 | var errors = require('./utils/errors')
|
11 | var joiFailAction = require('./utils/joi-fail-action')
|
12 | var validations = require('./utils/validations')
|
13 |
|
14 | function requestRoutes (server, options, next) {
|
15 | var api = server.plugins.account.api
|
16 |
|
17 | var postRequestsRoute = {
|
18 | method: 'POST',
|
19 | path: '/requests',
|
20 | config: {
|
21 | auth: false,
|
22 | validate: {
|
23 | payload: validations.requestPayload,
|
24 | query: validations.requestQuery,
|
25 | failAction: joiFailAction
|
26 | }
|
27 | },
|
28 | handler: function (request, reply) {
|
29 | if (!options.notifications.transport) {
|
30 | reply(Boom.create(503, 'Config missing: account.notifications.transport'))
|
31 | return
|
32 | }
|
33 |
|
34 | var username = request.payload.data.attributes.username
|
35 | var newPassword = randomstring.generate({
|
36 | length: 12,
|
37 | charset: 'hex'
|
38 | })
|
39 | var requestId = randomstring.generate({
|
40 | length: 12,
|
41 | charset: 'hex'
|
42 | })
|
43 |
|
44 | api.accounts.update({username: username}, {password: newPassword})
|
45 |
|
46 | .then(function (account) {
|
47 | var transportConfig = options.notifications.transport
|
48 | var transporter = nodemailer.createTransport(transportConfig)
|
49 |
|
50 | return transporter.sendMail({
|
51 | from: options.notifications.from,
|
52 | to: account.username,
|
53 | subject: 'Password reset',
|
54 | text: `Hello there,
|
55 |
|
56 | you can now sign in with
|
57 | username: ${account.username}
|
58 | password: ${newPassword}`
|
59 | })
|
60 |
|
61 | .then(function (result) {
|
62 | return {
|
63 | data: {
|
64 | type: 'request',
|
65 | id: requestId,
|
66 | attributes: {
|
67 | username: username,
|
68 | messageId: result.messageId,
|
69 | createdAt: new Date().toISOString()
|
70 | }
|
71 | }
|
72 | }
|
73 | })
|
74 | })
|
75 |
|
76 | .then(function (json) {
|
77 | reply(json).code(201)
|
78 | })
|
79 |
|
80 | .catch(function (error) {
|
81 | error = errors.parse(error)
|
82 | reply(Boom.create(error.status || 400, error.message))
|
83 | })
|
84 | }
|
85 | }
|
86 |
|
87 | server.route([
|
88 | postRequestsRoute
|
89 | ])
|
90 |
|
91 | next()
|
92 | }
|