hasPermission.js 8.6 KB

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