diff --git a/packages/backend/src/routers/delete-own-user.js b/packages/backend/src/routers/delete-own-user.js new file mode 100644 index 00000000..03325092 --- /dev/null +++ b/packages/backend/src/routers/delete-own-user.js @@ -0,0 +1,43 @@ +const eggspress = require("../api/eggspress"); +const { deleteUser, invalidate_cached_user } = require("../helpers"); + +const config = require("../config"); + +module.exports = eggspress("/delete-own-user", { + subdomain: "api", + auth: true, + allowedMethods: ["POST"], +}, async (req, res, next) => { + const bcrypt = require('bcrypt'); + + const validate_request = async () => { + const user = req.user; + + // `user` should always have a value, but this is checked + // any way in case the auth middleware is broken. + if ( ! user ) return false; + + // temporary users don't require password verification + if ( ! user.email && ! user.password ) { + return true; + } + + if ( ! req.body.password ) return false; + if ( ! user || ! user.password ) return false; + if ( ! await bcrypt.compare(req.body.password, req.user.password) ) { + return false; + } + return true; + } + + if ( ! await validate_request() ) { + return res.status(400).send({ success: false }); + } + + res.clearCookie(config.cookie_name); + + await deleteUser(req.user.id); + invalidate_cached_user(req.user); + + return res.send({ success: true }); +}); diff --git a/packages/backend/src/services/PuterAPIService.js b/packages/backend/src/services/PuterAPIService.js index 3ccd2938..4976252b 100644 --- a/packages/backend/src/services/PuterAPIService.js +++ b/packages/backend/src/services/PuterAPIService.js @@ -37,6 +37,7 @@ class PuterAPIService extends BaseService { app.use(require('../routers/auth/check-app')) app.use(require('../routers/auth/app-uid-from-origin')) app.use(require('../routers/auth/create-access-token')) + app.use(require('../routers/auth/delete-own-user')) app.use(require('../routers/drivers/call')) app.use(require('../routers/drivers/list-interfaces')) app.use(require('../routers/drivers/usage'))