authentication.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. Meteor.startup(() => {
  2. Authentication = {};
  3. Authentication.checkUserId = function (userId) {
  4. if (userId === undefined) {
  5. const error = new Meteor.Error('Unauthorized', 'Unauthorized');
  6. error.statusCode = 401;
  7. throw error;
  8. }
  9. const admin = Users.findOne({ _id: userId, isAdmin: true });
  10. if (admin === undefined) {
  11. const error = new Meteor.Error('Forbidden', 'Forbidden');
  12. error.statusCode = 403;
  13. throw error;
  14. }
  15. };
  16. // This will only check if the user is logged in.
  17. // The authorization checks for the user will have to be done inside each API endpoint
  18. Authentication.checkLoggedIn = function(userId) {
  19. if(userId === undefined) {
  20. const error = new Meteor.Error('Unauthorized', 'Unauthorized');
  21. error.statusCode = 401;
  22. throw error;
  23. }
  24. };
  25. // An admin should be authorized to access everything, so we use a separate check for admins
  26. // This throws an error if otherReq is false and the user is not an admin
  27. Authentication.checkAdminOrCondition = function(userId, otherReq) {
  28. if(otherReq) return;
  29. const admin = Users.findOne({ _id: userId, isAdmin: true });
  30. if (admin === undefined) {
  31. const error = new Meteor.Error('Forbidden', 'Forbidden');
  32. error.statusCode = 403;
  33. throw error;
  34. }
  35. };
  36. // Helper function. Will throw an error if the user does not have read only access to the given board
  37. Authentication.checkBoardAccess = function(userId, boardId) {
  38. Authentication.checkLoggedIn(userId);
  39. const board = Boards.findOne({ _id: boardId });
  40. const normalAccess = board.permission === 'public' || board.members.some((e) => e.userId === userId);
  41. Authentication.checkAdminOrCondition(userId, normalAccess);
  42. };
  43. });