oauth.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. const crypto = require('crypto');
  2. const cheerio = require('cheerio');
  3. const {defaultPermissions} = require('../util/default.json');
  4. const {db, settingsData, sendMsg, createNotice, hasPerm} = require('./util.js');
  5. const DiscordOauth2 = require('discord-oauth2');
  6. const oauth = new DiscordOauth2( {
  7. clientId: process.env.bot,
  8. clientSecret: process.env.secret,
  9. redirectUri: process.env.dashboard
  10. } );
  11. const file = require('fs').readFileSync('./dashboard/login.html');
  12. /**
  13. * Let a user login
  14. * @param {import('http').ServerResponse} res - The server response
  15. * @param {String} [state] - The user state
  16. * @param {String} [action] - The action the user made
  17. */
  18. function dashboard_login(res, state, action) {
  19. if ( state && settingsData.has(state) ) {
  20. if ( !action ) {
  21. res.writeHead(302, {Location: '/'});
  22. return res.end();
  23. }
  24. settingsData.delete(state);
  25. }
  26. var $ = cheerio.load(file);
  27. let invite = oauth.generateAuthUrl( {
  28. scope: ['identify', 'guilds', 'bot'],
  29. permissions: defaultPermissions, state
  30. } );
  31. $('.guild#invite a, .channel#invite-wikibot').attr('href', invite);
  32. let responseCode = 200;
  33. let prompt = 'none';
  34. if ( action === 'unauthorized' ) {
  35. createNotice($, {
  36. type: 'info',
  37. title: 'Not logged in!',
  38. text: 'Please login before you can change any settings.'
  39. }).prependTo('#text');
  40. }
  41. if ( action === 'failed' ) {
  42. responseCode = 400;
  43. createNotice($, {
  44. type: 'error',
  45. title: 'Login failed!',
  46. text: 'An error occurred while logging you in, please try again.'
  47. }).prependTo('#text');
  48. }
  49. if ( action === 'logout' ) {
  50. prompt = 'consent';
  51. createNotice($, {
  52. type: 'success',
  53. title: 'Successfully logged out!',
  54. text: 'You have been successfully logged out. To change any settings you need to login again.'
  55. }).prependTo('#text');
  56. }
  57. if ( process.env.READONLY ) {
  58. createNotice($, {
  59. type: 'info',
  60. title: 'Read-only database!',
  61. text: 'You can currently only view your settings but not change them.'
  62. }).prependTo('#text');
  63. }
  64. state = crypto.randomBytes(16).toString("hex");
  65. while ( settingsData.has(state) ) {
  66. state = crypto.randomBytes(16).toString("hex");
  67. }
  68. let url = oauth.generateAuthUrl( {
  69. scope: ['identify', 'guilds'],
  70. prompt, state
  71. } );
  72. $('.channel#login, #login-button').attr('href', url);
  73. let body = $.html();
  74. res.writeHead(responseCode, {
  75. 'Set-Cookie': [
  76. ...( res.getHeader('Set-Cookie') || [] ),
  77. `wikibot="${state}"; HttpOnly; Path=/`
  78. ],
  79. 'Content-Length': body.length
  80. });
  81. res.write( body );
  82. return res.end();
  83. }
  84. /**
  85. * Load oauth data of a user
  86. * @param {import('http').ServerResponse} res - The server response
  87. * @param {String} state - The user state
  88. * @param {URLSearchParams} searchParams - The url parameters
  89. * @param {String} [lastGuild] - The guild to return to
  90. */
  91. function dashboard_oauth(res, state, searchParams, lastGuild) {
  92. if ( state !== searchParams.get('state') || !searchParams.get('code') ) {
  93. res.writeHead(302, {Location: '/login?action=failed'});
  94. return res.end();
  95. }
  96. settingsData.delete(state);
  97. return oauth.tokenRequest( {
  98. scope: ['identify', 'guilds'],
  99. code: searchParams.get('code'),
  100. grantType: 'authorization_code'
  101. } ).then( ({access_token}) => {
  102. return Promise.all([
  103. oauth.getUser(access_token),
  104. oauth.getUserGuilds(access_token)
  105. ]).then( ([user, guilds]) => {
  106. guilds = guilds.filter( guild => {
  107. return ( guild.owner || hasPerm(guild.permissions, 'MANAGE_GUILD') );
  108. } ).map( guild => {
  109. return {
  110. id: guild.id,
  111. name: guild.name,
  112. acronym: guild.name.replace( /'s /g, ' ' ).replace( /\w+/g, e => e[0] ).replace( /\s/g, '' ),
  113. icon: ( guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.`
  114. + ( guild.icon.startsWith( 'a_' ) ? 'gif' : 'png' ) : null ),
  115. userPermissions: guild.permissions
  116. };
  117. } );
  118. sendMsg( {
  119. type: 'getGuilds',
  120. member: user.id,
  121. guilds: guilds.map( guild => guild.id )
  122. } ).then( response => {
  123. var settings = {
  124. state: `${state}-${user.id}`,
  125. access_token,
  126. user: {
  127. id: user.id,
  128. username: user.username,
  129. discriminator: user.discriminator,
  130. avatar: 'https://cdn.discordapp.com/' + ( user.avatar ?
  131. `avatars/${user.id}/${user.avatar}.` +
  132. ( user.avatar.startsWith( 'a_' ) ? 'gif' : 'png' ) :
  133. `embed/avatars/${user.discriminator % 5}.png` ) + '?size=64',
  134. locale: user.locale
  135. },
  136. guilds: {
  137. count: guilds.length,
  138. isMember: new Map(),
  139. notMember: new Map()
  140. }
  141. };
  142. response.forEach( (guild, i) => {
  143. if ( guild ) {
  144. settings.guilds.isMember.set(guilds[i].id, Object.assign(guilds[i], guild));
  145. }
  146. else settings.guilds.notMember.set(guilds[i].id, guilds[i]);
  147. } );
  148. settingsData.set(settings.state, settings);
  149. res.writeHead(302, {
  150. Location: ( lastGuild ? '/guild/' + lastGuild : '/' ),
  151. 'Set-Cookie': [`wikibot="${settings.state}"; HttpOnly; Path=/`]
  152. });
  153. return res.end();
  154. }, error => {
  155. console.log( '- Dashboard: Error while getting the guilds:', error );
  156. res.writeHead(302, {Location: '/login?action=failed'});
  157. return res.end();
  158. } );
  159. }, error => {
  160. console.log( '- Dashboard: Error while getting user and guilds: ' + error );
  161. res.writeHead(302, {Location: '/login?action=failed'});
  162. return res.end();
  163. } );
  164. }, error => {
  165. console.log( '- Dashboard: Error while getting the token: ' + error );
  166. res.writeHead(302, {Location: '/login?action=failed'});
  167. return res.end();
  168. } );
  169. }
  170. /**
  171. * Reload the guild of a user
  172. * @param {import('http').ServerResponse} res - The server response
  173. * @param {String} state - The user state
  174. * @param {String} [returnLocation] - The return location
  175. */
  176. function dashboard_refresh(res, state, returnLocation = '/') {
  177. var settings = settingsData.get(state);
  178. return oauth.getUserGuilds(settings.access_token).then( guilds => {
  179. guilds = guilds.filter( guild => {
  180. return ( guild.owner || hasPerm(guild.permissions, 'MANAGE_GUILD') );
  181. } ).map( guild => {
  182. return {
  183. id: guild.id,
  184. name: guild.name,
  185. acronym: guild.name.replace( /'s /g, ' ' ).replace( /\w+/g, e => e[0] ).replace( /\s/g, '' ),
  186. icon: ( guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.`
  187. + ( guild.icon.startsWith( 'a_' ) ? 'gif' : 'png' ) : null ),
  188. userPermissions: guild.permissions
  189. };
  190. } );
  191. sendMsg( {
  192. type: 'getGuilds',
  193. member: settings.user.id,
  194. guilds: guilds.map( guild => guild.id )
  195. } ).then( response => {
  196. let isMember = new Map();
  197. let notMember = new Map();
  198. response.forEach( (guild, i) => {
  199. if ( guild ) isMember.set(guilds[i].id, Object.assign(guilds[i], guild));
  200. else notMember.set(guilds[i].id, guilds[i]);
  201. } );
  202. settings.guilds = {count: guilds.length, isMember, notMember};
  203. res.writeHead(302, {Location: returnLocation + '?refresh=success'});
  204. return res.end();
  205. }, error => {
  206. console.log( '- Dashboard: Error while getting the refreshed guilds:', error );
  207. res.writeHead(302, {Location: returnLocation + '?refresh=failed'});
  208. return res.end();
  209. } );
  210. }, error => {
  211. console.log( '- Dashboard: Error while refreshing guilds: ' + error );
  212. res.writeHead(302, {Location: returnLocation + '?refresh=failed'});
  213. return res.end();
  214. } );
  215. }
  216. module.exports = {
  217. login: dashboard_login,
  218. oauth: dashboard_oauth,
  219. refresh: dashboard_refresh
  220. };