-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
69 lines (61 loc) · 1.86 KB
/
router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const express = require('express')
const bodyParser = require('body-parser')
const {AuthenticationError} = require('./postfix-accounts')
/**
* Creates an API router that exposes functions from postfixAccounts to the interface
* @param {PostfixAccounts} postfixAccounts
*/
function createRouter (postfixAccounts) {
const router = express.Router()
router.use(bodyParser.json())
/**
* Change the password of a user given the old password and the new password
*/
router.post('/user/:username', async function (req, res, next) {
try {
const username = req.params.username
const {oldPassword, newPassword} = req.body
if (oldPassword == null || newPassword == null) {
throw new BadRequestError('Request must contain username, oldPassword and newPassword')
}
await postfixAccounts.verifyAndUpdateUserPassword(username, oldPassword, newPassword)
res.contentType('application/json')
res.send(JSON.stringify({
success: true,
username
}))
} catch (err) {
next(err)
}
})
/**
* Error handler
*/
router.use(function (err, req, res, next) {
// eslint-disable-next-line no-console
console.error('Error', err.message, err.stack)
if (err instanceof AuthenticationError) {
return sendError(res, 403, 'Bad username or password')
}
/* istanbul ignore else */
if (err instanceof BadRequestError) {
return sendError(res, 400, err.message)
}
/* istanbul ignore next */
return sendError(res, 500, 'Internal server error')
})
return router
}
class BadRequestError extends Error {
}
function sendError (response, responseCode, message) {
response
.status(responseCode)
.contentType('application/json')
.send(JSON.stringify({
success: false,
code: responseCode,
message: message
}))
}
module.exports = {createRouter}