hasPermission.js 8.7 KB

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