Advertisement
Tarna256

Untitled

Feb 9th, 2022
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. const DISCORD_CLIENT_ID = import.meta.env.VITE_DISCORD_CLIENT_ID;
  2. const DISCORD_CLIENT_SECRET = import.meta.env.VITE_DISCORD_CLIENT_SECRET;
  3. const DISCORD_REDIRECT_URI = import.meta.env.VITE_DISCORD_REDIRECT_URI;
  4.  
  5. /**
  6. * @type {import('@sveltejs/kit').RequestHandler}
  7. */
  8. export async function get({ query }) {
  9. // fetch returnCode set in the URL parameters.
  10. const returnCode = query.get('code');
  11. console.log('returnCode =>', returnCode);
  12.  
  13. // initializing data object to be pushed to Discord's token endpoint.
  14. // the endpoint returns access & refresh tokens for the user.
  15. const dataObject = {
  16. client_id: DISCORD_CLIENT_ID,
  17. client_secret: DISCORD_CLIENT_SECRET,
  18. grant_type: 'authorization_code',
  19. redirect_uri: DISCORD_REDIRECT_URI,
  20. code: returnCode,
  21. scope: 'identify email guilds'
  22. };
  23.  
  24. // performing a Fetch request to Discord's token endpoint
  25. const request = await fetch('https://discord.com/api/oauth2/token', {
  26. method: 'POST',
  27. body: new URLSearchParams(dataObject),
  28. headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  29. });
  30.  
  31. const response = await request.json();
  32.  
  33. // redirect to front page in case of error
  34. if (response.error) {
  35. console.log('redirect to / due error');
  36. return {
  37. headers: { Location: '/' },
  38. status: 302
  39. }
  40. }
  41.  
  42. // redirect user to front page with cookies set
  43. const access_token_expires_in = new Date(Date.now() + response.expires_in); // 10 minutes
  44. const refresh_token_expires_in = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30 days
  45. console.log('redirect to / with cookies');
  46. return {
  47. headers: {
  48. 'set-cookie': [
  49. `disco_access_token=${response.access_token}; Path=/; HttpOnly; SameSite=Strict; Expires=${access_token_expires_in}}`,
  50. `disco_refresh_token=${response.refresh_token}; Path=/; HttpOnly; SameSite=Strict; Expires=${refresh_token_expires_in}`,
  51. ],
  52. Location: '/'
  53. },
  54. status: 302
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement