hasPermission.js 9.3 KB

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