hasPermission.js 10 KB

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