hasPermission.js 8.5 KB

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