hasPermission.js 8.6 KB

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