Advertisement
gir0fa6723

OAuth2 Error - Need Help

Apr 28th, 2024
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // require modules
  2. require('dotenv').config();
  3. const express = require('express');
  4. const axios = require('axios');
  5. const url = require('url');
  6. const fs = require('fs');
  7.  
  8. // load config
  9. const config = require("./config.json");
  10.  
  11. // website
  12. const port = config.website.port;
  13. const redirect_uri = config.website.redirect_uri;
  14. const webid = config.website.client_id;
  15. const websecret = config.website.client_secret;
  16. const app = express();
  17.  
  18. app.get('/api/auth/discord/redirect', async (req, res) => {
  19.     const { code } = req.query;
  20.  
  21.     if (code) {
  22.  
  23.         // authorize for later use
  24.  
  25.         try {
  26.  
  27.             // gain refresh token for later use
  28.  
  29.             const formData = new url.URLSearchParams({
  30.                 client_id: webid,
  31.                 client_secret: websecret,
  32.                 grant_type: 'authorization_code',
  33.                 code: code.toString(),
  34.                 redirect_uri: redirect_uri,
  35.             });
  36.            
  37.             const oauthInfo = await axios.post(`https://discord.com/api/v10/oauth2/token`,
  38.                 formData,
  39.             {
  40.                 headers: {'Content-Type': 'application/x-www-form-urlencoded',}
  41.             });
  42.  
  43.             // gain info on user
  44.  
  45.             const userinfo = await axios.get('https://discord.com/api/v10/users/@me', {
  46.                 headers: {
  47.                     'Authorization': `Bearer ${oauthInfo.data.access_token}`
  48.                 }
  49.             });
  50.             const userData = {
  51.                 "id": userinfo.data.id,
  52.                 "username": userinfo.data.username,
  53.                 "display_name": userinfo.data.global_name,
  54.                 "email": userinfo.data.email,
  55.                 "refresh_token": oauthInfo.data.refresh_token
  56.             };
  57.  
  58.             // edit users.json folder
  59.  
  60.             let jsonfile = fs.readFileSync("src/users.json").toString()
  61.             let jsonparse = JSON.parse(jsonfile)
  62.             jsonparse[userData.username] = userData
  63.             fs.writeFileSync("src/users.json", JSON.stringify(jsonparse));
  64.  
  65.            
  66.         } catch (error) {
  67.             console.log("Error occured:\n", error)
  68.         }
  69.     };
  70.  
  71.     res.redirect("https://discord.com/oauth2/authorized")
  72.  
  73.  
  74. });
  75.  
  76. // start the bot and website
  77. app.listen(port, () => {console.log(`Running on ${port}.`)});
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement