Free and Open-source video streaming suite. https://miracle-tv.live
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

81 lines
2.3 KiB

  1. import { Response, Router } from 'express';
  2. import IUser from 'miracle-tv-shared/src/types/api/v1/interfaces/IUser';
  3. import * as createUserJson from 'miracle-tv-shared/src/types/api/v1/schemas/user/createUser.json';
  4. import * as updateUserJson from 'miracle-tv-shared/src/types/api/v1/schemas/user/updateUser.json';
  5. import { Request } from 'server/lib/http/interfaces';
  6. import {
  7. sendData,
  8. sendCreated,
  9. dataOrNotFound,
  10. sendDuplicate,
  11. sendUnauthorized,
  12. } from 'server/lib/http/response';
  13. import Users from 'server/db/Users';
  14. import { acceptsSchema, authenticateUser, authorizeRoles } from 'server/lib/http/middleware';
  15. import { getIdFromParams } from 'server/lib/http/request';
  16. import { isAdmin } from 'server/lib/crypto';
  17. export function getList (_: Request, res: Response) {
  18. Users
  19. .getV1UsersSafe()
  20. .then(sendData(res));
  21. }
  22. export function getId (req: Request, res: Response) {
  23. const id = getIdFromParams(req);
  24. Users.getV1UserSafe(id).then(dataOrNotFound(res, { id }));
  25. }
  26. export function create (req: Request, res: Response) {
  27. const { email } = req.body;
  28. Users.getV1UserByEmail(email).then((user) => {
  29. if (!user) {
  30. Users.createV1User(req.body).then(sendCreated(res));
  31. } else {
  32. sendDuplicate(res, { email });
  33. }
  34. });
  35. }
  36. export function update (req: Request, res: Response) {
  37. const id = getIdFromParams(req);
  38. const body: IUser = req.body as IUser;
  39. const currentUser = req.session.user;
  40. if (id === currentUser.id || isAdmin(currentUser)) {
  41. Users.updateV1User(id, body).then(sendData(res));
  42. } else {
  43. sendUnauthorized(res)({ id: req.session.user.id });
  44. }
  45. }
  46. export function del (req: Request, res: Response) {
  47. const id = getIdFromParams(req);
  48. const currentUser = req.session.user;
  49. if (id === currentUser.id || isAdmin(currentUser)) {
  50. Users.deleteV1User(id).then(sendData(res));
  51. } else {
  52. sendUnauthorized(res)({ id: req.session.user.id });
  53. }
  54. }
  55. export function getSelf(req: Request, res: Response) {
  56. Users.getV1UserSafe(req.session.user.id).then(sendData(res));
  57. }
  58. const router = Router();
  59. router.get('/', getList);
  60. router.post(
  61. '/', authenticateUser, authorizeRoles(['admin']), acceptsSchema(createUserJson), create,
  62. );
  63. router.get('/:id', getId);
  64. router.put('/:id', authenticateUser, acceptsSchema(updateUserJson), update);
  65. router.delete('/:id', authenticateUser, del);
  66. export default router;