authentication.js 1.8 KB

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