From 60e1e99b4f2fef7178f8770dcba9e82e5ed31f15 Mon Sep 17 00:00:00 2001 From: Julian Lam Date: Fri, 6 Nov 2020 10:56:18 -0500 Subject: [PATCH] feat: new shorthand route /api/v3/users/bySlug/:userslug closes #8844 --- src/controllers/helpers.js | 2 +- src/controllers/write/users.js | 12 ++++++++++++ src/routes/write/users.js | 3 +++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/controllers/helpers.js b/src/controllers/helpers.js index 3c1ace728f..e64ac024b2 100644 --- a/src/controllers/helpers.js +++ b/src/controllers/helpers.js @@ -144,7 +144,7 @@ helpers.notAllowed = async function (req, res, error) { }; helpers.redirect = function (res, url, permanent) { - if (res.locals.isAPI) { + if (res.locals.isAPI && !url.startsWith('/api/v3/')) { res.set('X-Redirect', encodeURI(url)).status(200).json(url); } else { res.redirect(permanent ? 308 : 307, relative_path + encodeURI(url)); diff --git a/src/controllers/write/users.js b/src/controllers/write/users.js index 8e7ea756b9..e3336ccb5b 100644 --- a/src/controllers/write/users.js +++ b/src/controllers/write/users.js @@ -1,6 +1,7 @@ 'use strict'; const api = require('../../api'); +const user = require('../../user'); const meta = require('../../meta'); const privileges = require('../../privileges'); const utils = require('../../utils'); @@ -16,6 +17,17 @@ const hasAdminPrivilege = async (uid, privilege) => { } }; +Users.redirectBySlug = async (req, res) => { + const uid = await user.getUidByUserslug(req.params.userslug); + + if (uid) { + const path = req.path.split('/').slice(3).join('/'); + helpers.redirect(res, `/api/v3/users/${uid}/${path}`, false); + } else { + helpers.formatApiResponse(404, res); + } +}; + Users.create = async (req, res) => { await hasAdminPrivilege(req.uid, 'users'); const userObj = await api.users.create(req, req.body); diff --git a/src/routes/write/users.js b/src/routes/write/users.js index 7241f7f183..3863f75ee9 100644 --- a/src/routes/write/users.js +++ b/src/routes/write/users.js @@ -33,6 +33,9 @@ function authenticatedRoutes() { setupApiRoute(router, 'post', '/:uid/tokens', [...middlewares, middleware.assert.user], controllers.write.users.generateToken); setupApiRoute(router, 'delete', '/:uid/tokens/:token', [...middlewares, middleware.assert.user], controllers.write.users.deleteToken); + + // Shorthand route to access user routes by userslug + router.all('/+bySlug/:userslug*?', [...middlewares], controllers.write.users.redirectBySlug); } module.exports = function () {