42 lines
1.3 KiB
JavaScript
42 lines
1.3 KiB
JavaScript
'use strict';
|
|
|
|
const express = require('express');
|
|
const { models } = require('../../core/db');
|
|
const { authenticateToken } = require('../../core/auth');
|
|
const { ok, noContent } = require('../../core/respond');
|
|
const { AppError } = require('../../core/errors');
|
|
const { changeOwnPassword: changeOwnPasswordSchema } = require('../../core/schemas/auth');
|
|
const svc = require('./service');
|
|
|
|
const router = express.Router();
|
|
router.prefix = 'my';
|
|
|
|
function validate(schema) {
|
|
return (req, res, next) => {
|
|
const result = schema.safeParse(req.body);
|
|
if (!result.success) {
|
|
const e = result.error.errors[0];
|
|
return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0]));
|
|
}
|
|
req.body = result.data;
|
|
next();
|
|
};
|
|
}
|
|
|
|
router.get('/profile', authenticateToken, async (req, res, next) => {
|
|
try {
|
|
const user = await models.User.findByPk(req.user.id);
|
|
if (!user) return next(new AppError('NOT_FOUND', 'User not found.', 404));
|
|
ok(res, user.toPublic());
|
|
} catch (err) { next(err); }
|
|
});
|
|
|
|
router.put('/password', authenticateToken, validate(changeOwnPasswordSchema), async (req, res, next) => {
|
|
try {
|
|
await svc.changeOwnPassword(models, req, req.user.id, req.body.currentPassword, req.body.newPassword);
|
|
noContent(res);
|
|
} catch (err) { next(err); }
|
|
});
|
|
|
|
module.exports = router;
|