hasPermission.js 9.0 KB

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