hasPermission.js 9.6 KB

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