OAuthWindow.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { BrowserWindow, BrowserWindowConstructorOptions } from "electron";
  2. import url from "url";
  3. import querystring from "querystring";
  4. import { isString } from "util";
  5. import { EventEmitter } from "events";
  6. function formatUrl(
  7. client_id: string,
  8. redirect_uri: string,
  9. response_type: string,
  10. scope: string[]
  11. ): string{
  12. return url.format({
  13. protocol: "https",
  14. hostname: "id.twitch.tv",
  15. pathname: "/oauth2/authorize",
  16. query: {
  17. client_id: client_id,
  18. redirect_uri: redirect_uri,
  19. response_type: response_type,
  20. scope: scope.join(" ")
  21. }
  22. });
  23. }
  24. function parseTwitchRedirect(twitchUrl: string): string{
  25. let parsed = url.parse(twitchUrl);
  26. let query = querystring.parse(parsed.hash.slice(1));
  27. if(isString(query["access_token"])){
  28. return query["access_token"];
  29. }
  30. return "";
  31. }
  32. declare interface OAuthWindow {
  33. on(event: "authcode", listener: (authcode: string) => void): this;
  34. on(event: "close", listener: () => void): this;
  35. emit(event: "authcode", authcode: string): boolean;
  36. emit(event: "close"): boolean;
  37. }
  38. class OAuthWindow extends EventEmitter {
  39. url: string;
  40. win?: BrowserWindow;
  41. constructor(clientId: string){
  42. super();
  43. if(clientId == ""){
  44. throw new Error("You need to specifie clientId");
  45. }
  46. this.url = formatUrl(
  47. clientId,
  48. "http://localhost",
  49. "token",
  50. ["channel:read:redemptions"]
  51. );
  52. }
  53. openWindow(windowParams: BrowserWindowConstructorOptions){
  54. this.win = new BrowserWindow(windowParams);
  55. // this.win.webContents.openDevTools();
  56. this.win.loadURL(this.url);
  57. this.win.show();
  58. this.win.webContents.on("will-redirect", (ev, nurl)=>{
  59. let authcode = parseTwitchRedirect(nurl);
  60. if(authcode != ""){
  61. this.emit("authcode", authcode);
  62. this.win.close();
  63. }
  64. })
  65. this.win.on("close", ()=>{
  66. this.emit("close")
  67. })
  68. }
  69. }
  70. export default OAuthWindow