authentication.js 1.8 KB

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