lokalise_auth.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.LokaliseAuth = void 0;
  4. const auth_request_1 = require("./auth_request");
  5. class LokaliseAuth {
  6. authData = {
  7. client_id: "",
  8. client_secret: "",
  9. };
  10. /*
  11. * Instantiate LokaliseAuth to work with OAuth 2 tokens
  12. * @param clientId string, mandatory
  13. * @param clientSecret string, mandatory
  14. * @returns LokaliseAuth object to work with.
  15. */
  16. constructor(clientId, clientSecret, host) {
  17. if (clientId == null ||
  18. clientId.length == 0 ||
  19. clientSecret == null ||
  20. clientSecret.length == 0) {
  21. throw new Error("Error: Instantiation failed: Please pass client id and client secret");
  22. }
  23. this.authData.client_id = clientId;
  24. this.authData.client_secret = clientSecret;
  25. this.authData.host = host;
  26. }
  27. auth(scope, redirect_uri, state) {
  28. if (scope instanceof Array) {
  29. scope = scope.join(" ");
  30. }
  31. const params = {
  32. client_id: this.authData.client_id,
  33. scope: scope,
  34. };
  35. if (state) {
  36. params["state"] = state;
  37. }
  38. if (redirect_uri) {
  39. params["redirect_uri"] = redirect_uri;
  40. }
  41. return this.buildUrl(params);
  42. }
  43. async token(code) {
  44. const params = {
  45. ...this.base_params(),
  46. ...{
  47. code: code,
  48. grant_type: "authorization_code",
  49. },
  50. };
  51. return await this.doRequest(params);
  52. }
  53. async refresh(refresh_token) {
  54. const params = {
  55. ...this.base_params(),
  56. ...{
  57. refresh_token: refresh_token,
  58. grant_type: "refresh_token",
  59. },
  60. };
  61. return await this.doRequest(params);
  62. }
  63. async doRequest(params) {
  64. try {
  65. const data = await auth_request_1.AuthRequest.createPromise("token", "POST", params, this.authData.host);
  66. return Promise.resolve(data["json"]);
  67. }
  68. catch (err) {
  69. return Promise.reject(this.handleReject(err));
  70. }
  71. }
  72. buildUrl(params) {
  73. const url = new URL("auth", this.authData.host ?? auth_request_1.AuthRequest.urlRoot);
  74. const sParams = new URLSearchParams(params);
  75. url.search = sParams.toString();
  76. return url.toString();
  77. }
  78. base_params() {
  79. return {
  80. client_id: this.authData.client_id,
  81. client_secret: this.authData.client_secret,
  82. };
  83. }
  84. handleReject(data) {
  85. return data;
  86. }
  87. }
  88. exports.LokaliseAuth = LokaliseAuth;
  89. //# sourceMappingURL=lokalise_auth.js.map