oauth.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. const crypto = require('crypto');
  2. const cheerio = require('cheerio');
  3. const {defaultPermissions} = require('../util/default.json');
  4. const Wiki = require('../util/wiki.js');
  5. const {got, settingsData, sendMsg, createNotice, hasPerm} = require('./util.js');
  6. const DiscordOauth2 = require('discord-oauth2');
  7. const oauth = new DiscordOauth2( {
  8. clientId: process.env.bot,
  9. clientSecret: process.env.secret,
  10. redirectUri: process.env.dashboard
  11. } );
  12. const file = require('fs').readFileSync('./dashboard/login.html');
  13. /**
  14. * Let a user login
  15. * @param {import('http').ServerResponse} res - The server response
  16. * @param {String} [state] - The user state
  17. * @param {String} [action] - The action the user made
  18. */
  19. function dashboard_login(res, state, action) {
  20. if ( state && settingsData.has(state) ) {
  21. if ( !action ) {
  22. res.writeHead(302, {Location: '/'});
  23. return res.end();
  24. }
  25. settingsData.delete(state);
  26. }
  27. var $ = cheerio.load(file);
  28. let responseCode = 200;
  29. let prompt = 'none';
  30. if ( process.env.READONLY ) createNotice($, 'readonly');
  31. if ( action ) createNotice($, action);
  32. if ( action === 'unauthorized' ) $('head').append(
  33. $('<script>').text('history.replaceState(null, null, "/login");')
  34. );
  35. if ( action === 'logout' ) prompt = 'consent';
  36. if ( action === 'loginfail' ) responseCode = 400;
  37. state = crypto.randomBytes(16).toString("hex");
  38. while ( settingsData.has(state) ) {
  39. state = crypto.randomBytes(16).toString("hex");
  40. }
  41. let invite = oauth.generateAuthUrl( {
  42. scope: ['identify', 'guilds', 'bot'],
  43. permissions: defaultPermissions, state
  44. } );
  45. $('.guild#invite a, .channel#invite-wikibot').attr('href', invite);
  46. let url = oauth.generateAuthUrl( {
  47. scope: ['identify', 'guilds'],
  48. prompt, state
  49. } );
  50. $('.channel#login, #login-button').attr('href', url);
  51. let body = $.html();
  52. res.writeHead(responseCode, {
  53. 'Set-Cookie': [
  54. ...( res.getHeader('Set-Cookie') || [] ),
  55. `wikibot="${state}"; HttpOnly; Path=/`
  56. ],
  57. 'Content-Length': body.length
  58. });
  59. res.write( body );
  60. return res.end();
  61. }
  62. /**
  63. * Load oauth data of a user
  64. * @param {import('http').ServerResponse} res - The server response
  65. * @param {String} state - The user state
  66. * @param {URLSearchParams} searchParams - The url parameters
  67. * @param {String} [lastGuild] - The guild to return to
  68. */
  69. function dashboard_oauth(res, state, searchParams, lastGuild) {
  70. if ( searchParams.get('error') === 'access_denied' && state === searchParams.get('state') && settingsData.has(state) ) {
  71. res.writeHead(302, {Location: '/'});
  72. return res.end();
  73. }
  74. if ( state !== searchParams.get('state') || !searchParams.get('code') ) {
  75. res.writeHead(302, {Location: '/login?action=failed'});
  76. return res.end();
  77. }
  78. settingsData.delete(state);
  79. return oauth.tokenRequest( {
  80. scope: ['identify', 'guilds'],
  81. code: searchParams.get('code'),
  82. grantType: 'authorization_code'
  83. } ).then( ({access_token}) => {
  84. return Promise.all([
  85. oauth.getUser(access_token),
  86. oauth.getUserGuilds(access_token)
  87. ]).then( ([user, guilds]) => {
  88. guilds = guilds.filter( guild => {
  89. return ( guild.owner || hasPerm(guild.permissions, 'MANAGE_GUILD') );
  90. } ).map( guild => {
  91. return {
  92. id: guild.id,
  93. name: guild.name,
  94. acronym: guild.name.replace( /'s /g, ' ' ).replace( /\w+/g, e => e[0] ).replace( /\s/g, '' ),
  95. icon: ( guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.`
  96. + ( guild.icon.startsWith( 'a_' ) ? 'gif' : 'png' ) : null ),
  97. userPermissions: guild.permissions
  98. };
  99. } );
  100. sendMsg( {
  101. type: 'getGuilds',
  102. member: user.id,
  103. guilds: guilds.map( guild => guild.id )
  104. } ).then( response => {
  105. var settings = {
  106. state: `${state}-${user.id}`,
  107. access_token,
  108. user: {
  109. id: user.id,
  110. username: user.username,
  111. discriminator: user.discriminator,
  112. avatar: 'https://cdn.discordapp.com/' + ( user.avatar ?
  113. `avatars/${user.id}/${user.avatar}.` +
  114. ( user.avatar.startsWith( 'a_' ) ? 'gif' : 'png' ) :
  115. `embed/avatars/${user.discriminator % 5}.png` ) + '?size=64',
  116. locale: user.locale
  117. },
  118. guilds: {
  119. count: guilds.length,
  120. isMember: new Map(),
  121. notMember: new Map()
  122. }
  123. };
  124. response.forEach( (guild, i) => {
  125. if ( guild ) {
  126. if ( guild === 'noMember' ) return;
  127. settings.guilds.isMember.set(guilds[i].id, Object.assign(guilds[i], guild));
  128. }
  129. else settings.guilds.notMember.set(guilds[i].id, guilds[i]);
  130. } );
  131. settingsData.set(settings.state, settings);
  132. res.writeHead(302, {
  133. Location: ( lastGuild && /^\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(lastGuild) ? `/guild/${lastGuild}` : '/' ),
  134. 'Set-Cookie': [`wikibot="${settings.state}"; HttpOnly; Path=/`]
  135. });
  136. return res.end();
  137. }, error => {
  138. console.log( '- Dashboard: Error while getting the guilds:', error );
  139. res.writeHead(302, {Location: '/login?action=failed'});
  140. return res.end();
  141. } );
  142. }, error => {
  143. console.log( '- Dashboard: Error while getting user and guilds: ' + error );
  144. res.writeHead(302, {Location: '/login?action=failed'});
  145. return res.end();
  146. } );
  147. }, error => {
  148. console.log( '- Dashboard: Error while getting the token: ' + error );
  149. res.writeHead(302, {Location: '/login?action=failed'});
  150. return res.end();
  151. } );
  152. }
  153. /**
  154. * Reload the guild of a user
  155. * @param {import('http').ServerResponse} res - The server response
  156. * @param {String} state - The user state
  157. * @param {String} [returnLocation] - The return location
  158. */
  159. function dashboard_refresh(res, state, returnLocation = '/') {
  160. var settings = settingsData.get(state);
  161. return oauth.getUserGuilds(settings.access_token).then( guilds => {
  162. guilds = guilds.filter( guild => {
  163. return ( guild.owner || hasPerm(guild.permissions, 'MANAGE_GUILD') );
  164. } ).map( guild => {
  165. return {
  166. id: guild.id,
  167. name: guild.name,
  168. acronym: guild.name.replace( /'s /g, ' ' ).replace( /\w+/g, e => e[0] ).replace( /\s/g, '' ),
  169. icon: ( guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.`
  170. + ( guild.icon.startsWith( 'a_' ) ? 'gif' : 'png' ) : null ),
  171. userPermissions: guild.permissions
  172. };
  173. } );
  174. sendMsg( {
  175. type: 'getGuilds',
  176. member: settings.user.id,
  177. guilds: guilds.map( guild => guild.id )
  178. } ).then( response => {
  179. let isMember = new Map();
  180. let notMember = new Map();
  181. response.forEach( (guild, i) => {
  182. if ( guild ) {
  183. if ( guild === 'noMember' ) return;
  184. isMember.set(guilds[i].id, Object.assign(guilds[i], guild));
  185. }
  186. else notMember.set(guilds[i].id, guilds[i]);
  187. } );
  188. settings.guilds = {count: guilds.length, isMember, notMember};
  189. res.writeHead(302, {Location: returnLocation + '?refresh=success'});
  190. return res.end();
  191. }, error => {
  192. console.log( '- Dashboard: Error while getting the refreshed guilds:', error );
  193. res.writeHead(302, {Location: returnLocation + '?refresh=failed'});
  194. return res.end();
  195. } );
  196. }, error => {
  197. console.log( '- Dashboard: Error while refreshing guilds: ' + error );
  198. res.writeHead(302, {Location: returnLocation + '?refresh=failed'});
  199. return res.end();
  200. } );
  201. }
  202. /**
  203. * Check if a wiki is availabe
  204. * @param {import('http').ServerResponse} res - The server response
  205. * @param {String} input - The wiki to check
  206. */
  207. function dashboard_api(res, input) {
  208. var wiki = Wiki.fromInput('https://' + input + '/');
  209. var result = {
  210. api: true,
  211. error: false,
  212. wiki: wiki.href,
  213. MediaWiki: false,
  214. TextExtracts: false,
  215. PageImages: false,
  216. RcGcDw: '',
  217. customRcGcDw: wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit')
  218. };
  219. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general|extensions' + ( wiki.isFandom() ? '|variables' : '' ) + '&format=json' ).then( response => {
  220. if ( response.statusCode === 404 && typeof response.body === 'string' ) {
  221. let api = cheerio.load(response.body)('head link[rel="EditURI"]').prop('href');
  222. if ( api ) {
  223. wiki = new Wiki(api.split('api.php?')[0], wiki);
  224. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general|extensions' + ( wiki.isFandom() ? '|variables' : '' ) + '&format=json' );
  225. }
  226. }
  227. return response;
  228. } ).then( response => {
  229. var body = response.body;
  230. if ( response.statusCode !== 200 || !body?.query?.allmessages || !body?.query?.general || !body?.query?.extensions ) {
  231. console.log( '- Dashboard: ' + response.statusCode + ': Error while checking the wiki: ' + body?.error?.info );
  232. result.error = true;
  233. return;
  234. }
  235. wiki.updateWiki(body.query.general);
  236. result.wiki = wiki.href;
  237. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) >= 30 ) {
  238. result.MediaWiki = true;
  239. }
  240. if ( body.query.extensions.some( extension => extension.name === 'TextExtracts' ) ) {
  241. result.TextExtracts = true;
  242. }
  243. if ( body.query.extensions.some( extension => extension.name === 'PageImages' ) ) {
  244. result.PageImages = true;
  245. }
  246. if ( body.query.allmessages[0]['*'] ) {
  247. result.RcGcDw = body.query.allmessages[0]['*'];
  248. }
  249. result.customRcGcDw = wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit');
  250. }, error => {
  251. console.log( '- Dashboard: Error while checking the wiki: ' + error );
  252. result.error = true;
  253. } ).finally( () => {
  254. let body = JSON.stringify(result);
  255. res.writeHead(200, {
  256. 'Content-Length': body.length,
  257. 'Content-Type': 'application/json'
  258. });
  259. res.write( body );
  260. return res.end();
  261. } );
  262. }
  263. module.exports = {
  264. login: dashboard_login,
  265. oauth: dashboard_oauth,
  266. refresh: dashboard_refresh,
  267. api: dashboard_api
  268. };