hasPermission.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import async from "async";
  2. // eslint-disable-next-line
  3. import moduleManager from "../../index";
  4. const permissions = {};
  5. permissions.dj = {
  6. "stations.autofill": true,
  7. "stations.blacklist": true,
  8. "stations.index": true,
  9. "stations.playback.toggle": true,
  10. "stations.queue.remove": true,
  11. "stations.queue.reposition": true,
  12. "stations.queue.reset": true,
  13. "stations.request": true,
  14. "stations.skip": true,
  15. "stations.view": true,
  16. "stations.view.manage": true
  17. };
  18. permissions.owner = {
  19. ...permissions.dj,
  20. "stations.remove": true,
  21. "stations.update": true
  22. };
  23. permissions.moderator = {
  24. ...permissions.owner,
  25. "admin.view": true,
  26. "admin.view.import": true,
  27. "admin.view.news": true,
  28. "admin.view.playlists": true,
  29. "admin.view.punishments": true,
  30. "admin.view.reports": true,
  31. "admin.view.songs": true,
  32. "admin.view.stations": true,
  33. "admin.view.youtubeVideos": true,
  34. "apis.searchDiscogs": true,
  35. "news.create": true,
  36. "news.update": true,
  37. "playlists.get": true,
  38. "playlists.update.displayName": false,
  39. "playlists.update.privacy": true,
  40. "playlists.songs.add": true,
  41. "playlists.songs.remove": true,
  42. "playlists.songs.reposition": true,
  43. "playlists.view.others": true,
  44. "punishments.banIP": true,
  45. "punishments.get": true,
  46. "reports.get": true,
  47. "reports.update": true,
  48. "songs.create": true,
  49. "songs.get": true,
  50. "songs.update": true,
  51. "songs.verify": true,
  52. "stations.create.official": true,
  53. "stations.index": false,
  54. "stations.index.other": true,
  55. "stations.remove": false,
  56. "youtube.requestSetAdmin": true
  57. };
  58. permissions.admin = {
  59. ...permissions.moderator,
  60. "admin.view.statistics": true,
  61. "admin.view.users": true,
  62. "admin.view.youtube": true,
  63. "dataRequests.resolve": true,
  64. "media.recalculateAllRatings": true,
  65. "media.removeImportJobs": true,
  66. "news.remove": true,
  67. "playlists.clearAndRefill": true,
  68. "playlists.clearAndRefillAll": true,
  69. "playlists.createMissing": true,
  70. "playlists.deleteOrphaned": true,
  71. "playlists.removeAdmin": true,
  72. "playlists.requestOrphanedPlaylistSongs": true,
  73. "reports.remove": true,
  74. "songs.remove": true,
  75. "songs.updateAll": true,
  76. "stations.clearEveryStationQueue": true,
  77. "stations.remove": true,
  78. "users.get": true,
  79. "users.update": true,
  80. "users.remove": true,
  81. "users.remove.sessions": true,
  82. "users.requestPasswordReset": true,
  83. "users.resendVerifyEmail": true,
  84. "users.ban": true,
  85. "utils.getModules": true,
  86. "youtube.getApiRequest": true,
  87. "youtube.resetStoredApiRequests": true,
  88. "youtube.removeStoredApiRequest": true,
  89. "youtube.removeVideos": true
  90. };
  91. export const hasPermission = async (permission, session, stationId) => {
  92. const CacheModule = moduleManager.modules.cache;
  93. const DBModule = moduleManager.modules.db;
  94. const StationsModule = moduleManager.modules.stations;
  95. const UtilsModule = moduleManager.modules.utils;
  96. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  97. return new Promise((resolve, reject) => {
  98. async.waterfall(
  99. [
  100. next => {
  101. let userId;
  102. if (typeof session === "object") {
  103. if (session.userId) userId = session.userId;
  104. else
  105. CacheModule.runJob(
  106. "HGET",
  107. {
  108. table: "sessions",
  109. key: session.sessionId
  110. },
  111. this
  112. )
  113. .then(_session => {
  114. if (_session && _session.userId) userId = _session.userId;
  115. })
  116. .catch(next);
  117. } else userId = session;
  118. if (!userId) return next("User ID required.");
  119. return userModel.findOne({ _id: userId }, next);
  120. },
  121. (user, next) => {
  122. if (!user) return next("Login required.");
  123. if (!stationId) return next(null, [user.role]);
  124. return StationsModule.runJob("GET_STATION", { stationId }, this)
  125. .then(station => {
  126. if (!station) return next("Station not found.");
  127. if (station.type === "community" && station.owner === user._id.toString())
  128. return next(null, [user.role, "owner"]);
  129. // if (station.type === "community" && station.djs.find(userId))
  130. // return next(null, [user.role, "dj"]);
  131. if (user.role === "admin" || user.role === "moderator") return next(null, [user.role]);
  132. return next("Invalid permissions.");
  133. })
  134. .catch(next);
  135. },
  136. (roles, next) => {
  137. if (!roles) return next("Role required.");
  138. let permissionFound;
  139. roles.forEach(role => {
  140. if (permissions[role] && permissions[role][permission]) permissionFound = true;
  141. });
  142. if (permissionFound) return next();
  143. return next("Insufficient permissions.");
  144. }
  145. ],
  146. async err => {
  147. const userId = typeof session === "object" ? session.userId || session.sessionId : session;
  148. if (err) {
  149. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  150. UtilsModule.log(
  151. "INFO",
  152. "HAS_PERMISSION",
  153. `User "${userId}" does not have required permission "${permission}". "${err}"`
  154. );
  155. return reject(err);
  156. }
  157. UtilsModule.log(
  158. "INFO",
  159. "HAS_PERMISSION",
  160. `User "${userId}" has required permission "${permission}".`,
  161. false
  162. );
  163. return resolve();
  164. }
  165. );
  166. });
  167. };
  168. export const useHasPermission = (options, destination) =>
  169. async function useHasPermission(session, ...args) {
  170. const UtilsModule = moduleManager.modules.utils;
  171. const permission = typeof options === "object" ? options.permission : options;
  172. const stationId = typeof options === "object" ? options.stationId : null;
  173. const cb = args[args.length - 1];
  174. async.waterfall(
  175. [
  176. next => {
  177. if (!session || !session.sessionId) return next("Login required.");
  178. return hasPermission(permission, session, stationId)
  179. .then(() => next())
  180. .catch(next);
  181. }
  182. ],
  183. async err => {
  184. if (err) {
  185. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  186. this.log(
  187. "INFO",
  188. "USE_HAS_PERMISSION",
  189. `User "${session.userId}" does not have required permission "${permission}". "${err}"`
  190. );
  191. return cb({ status: "error", message: err });
  192. }
  193. this.log(
  194. "INFO",
  195. "USE_HAS_PERMISSION",
  196. `User "${session.userId}" has required permission "${permission}".`,
  197. false
  198. );
  199. return destination.apply(this, [session].concat(args));
  200. }
  201. );
  202. };
  203. export const getUserPermissions = async (session, stationId) => {
  204. const CacheModule = moduleManager.modules.cache;
  205. const DBModule = moduleManager.modules.db;
  206. const StationsModule = moduleManager.modules.stations;
  207. const UtilsModule = moduleManager.modules.utils;
  208. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  209. return new Promise((resolve, reject) => {
  210. async.waterfall(
  211. [
  212. next => {
  213. let userId;
  214. if (typeof session === "object") {
  215. if (session.userId) userId = session.userId;
  216. else
  217. CacheModule.runJob(
  218. "HGET",
  219. {
  220. table: "sessions",
  221. key: session.sessionId
  222. },
  223. this
  224. )
  225. .then(_session => {
  226. if (_session && _session.userId) userId = _session.userId;
  227. })
  228. .catch(next);
  229. } else userId = session;
  230. if (!userId) return next("User ID required.");
  231. return userModel.findOne({ _id: userId }, next);
  232. },
  233. (user, next) => {
  234. if (!user) return next("Login required.");
  235. if (!stationId) return next(null, [user.role]);
  236. return StationsModule.runJob("GET_STATION", { stationId }, this)
  237. .then(station => {
  238. if (!station) return next("Station not found.");
  239. if (station.type === "community" && station.owner === user._id.toString())
  240. return next(null, [user.role, "owner"]);
  241. // if (station.type === "community" && station.djs.find(userId))
  242. // return next(null, [user.role, "dj"]);
  243. if (user.role === "admin" || user.role === "moderator") return next(null, [user.role]);
  244. return next("Invalid permissions.");
  245. })
  246. .catch(next);
  247. },
  248. (roles, next) => {
  249. if (!roles) return next("Role required.");
  250. let rolePermissions = {};
  251. roles.forEach(role => {
  252. if (permissions[role]) rolePermissions = { ...rolePermissions, ...permissions[role] };
  253. });
  254. return next(null, rolePermissions);
  255. }
  256. ],
  257. async (err, rolePermissions) => {
  258. const userId = typeof session === "object" ? session.userId || session.sessionId : session;
  259. if (err) {
  260. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  261. UtilsModule.log(
  262. "INFO",
  263. "GET_USER_PERMISSIONS",
  264. `Failed to get permissions for user "${userId}". "${err}"`
  265. );
  266. return reject(err);
  267. }
  268. UtilsModule.log("INFO", "GET_USER_PERMISSIONS", `Fetched permissions for user "${userId}".`, false);
  269. return resolve(rolePermissions);
  270. }
  271. );
  272. });
  273. };