hasPermission.js 8.6 KB

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