hasPermission.js 9.8 KB

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