hasPermission.js 8.9 KB

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