UNPKG

2.3 kBJavaScriptView Raw
1module.exports = requestRoutes
2module.exports.attributes = {
3 name: 'account-routes-requests'
4}
5
6var Boom = require('boom')
7var nodemailer = require('nodemailer')
8var randomstring = require('randomstring')
9
10var errors = require('./utils/errors')
11var joiFailAction = require('./utils/joi-fail-action')
12var validations = require('./utils/validations')
13
14function 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
56you can now sign in with
57username: ${account.username}
58password: ${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}