grant-user-app.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (C) 2024 Puter Technologies Inc.
  3. *
  4. * This file is part of Puter.
  5. *
  6. * Puter is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published
  8. * by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. const APIError = require("../../api/APIError");
  20. const eggspress = require("../../api/eggspress");
  21. const { UserActorType } = require("../../services/auth/Actor");
  22. const { Context } = require("../../util/context");
  23. module.exports = eggspress('/auth/grant-user-app', {
  24. subdomain: 'api',
  25. auth2: true,
  26. allowedMethods: ['POST'],
  27. }, async (req, res, next) => {
  28. const x = Context.get();
  29. const svc_permission = x.get('services').get('permission');
  30. // Only users can grant user-app permissions
  31. const actor = Context.get('actor');
  32. if ( ! (actor.type instanceof UserActorType) ) {
  33. throw APIError.create('forbidden');
  34. }
  35. if ( req.body.origin ) {
  36. const svc_auth = x.get('services').get('auth');
  37. req.body.app_uid = await svc_auth.app_uid_from_origin(req.body.origin);
  38. }
  39. if ( ! req.body.app_uid ) {
  40. throw APIError.create('field_missing', null, { key: 'app_uid' });
  41. }
  42. if ( ! req.body.permission ) {
  43. throw APIError.create('field_missing', null, {
  44. key: 'permission'
  45. });
  46. }
  47. const token = await svc_permission.grant_user_app_permission(
  48. actor, req.body.app_uid, req.body.permission,
  49. req.body.extra || {}, req.body.meta || {}
  50. );
  51. res.json({});
  52. });