hasPermission.js 8.7 KB

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