hasPermission.js 9.1 KB

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