hasPermission.js 9.6 KB

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