index.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. module.exports = authenticationPlugin;
  2. const { createTokenAuth } = require("@octokit/auth-token");
  3. const { Deprecation } = require("deprecation");
  4. const once = require("once");
  5. const beforeRequest = require("./before-request");
  6. const requestError = require("./request-error");
  7. const validate = require("./validate");
  8. const withAuthorizationPrefix = require("./with-authorization-prefix");
  9. const deprecateAuthBasic = once((log, deprecation) => log.warn(deprecation));
  10. const deprecateAuthObject = once((log, deprecation) => log.warn(deprecation));
  11. function authenticationPlugin(octokit, options) {
  12. // If `options.authStrategy` is set then use it and pass in `options.auth`
  13. if (options.authStrategy) {
  14. const auth = options.authStrategy(options.auth);
  15. octokit.hook.wrap("request", auth.hook);
  16. octokit.auth = auth;
  17. return;
  18. }
  19. // If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
  20. // is unauthenticated. The `octokit.auth()` method is a no-op and no request hook is registred.
  21. if (!options.auth) {
  22. octokit.auth = () =>
  23. Promise.resolve({
  24. type: "unauthenticated"
  25. });
  26. return;
  27. }
  28. const isBasicAuthString =
  29. typeof options.auth === "string" &&
  30. /^basic/.test(withAuthorizationPrefix(options.auth));
  31. // If only `options.auth` is set to a string, use the default token authentication strategy.
  32. if (typeof options.auth === "string" && !isBasicAuthString) {
  33. const auth = createTokenAuth(options.auth);
  34. octokit.hook.wrap("request", auth.hook);
  35. octokit.auth = auth;
  36. return;
  37. }
  38. // Otherwise log a deprecation message
  39. const [deprecationMethod, deprecationMessapge] = isBasicAuthString
  40. ? [
  41. deprecateAuthBasic,
  42. 'Setting the "new Octokit({ auth })" option to a Basic Auth string is deprecated. Use https://github.com/octokit/auth-basic.js instead. See (https://octokit.github.io/rest.js/#authentication)'
  43. ]
  44. : [
  45. deprecateAuthObject,
  46. 'Setting the "new Octokit({ auth })" option to an object without also setting the "authStrategy" option is deprecated and will be removed in v17. See (https://octokit.github.io/rest.js/#authentication)'
  47. ];
  48. deprecationMethod(
  49. octokit.log,
  50. new Deprecation("[@octokit/rest] " + deprecationMessapge)
  51. );
  52. octokit.auth = () =>
  53. Promise.resolve({
  54. type: "deprecated",
  55. message: deprecationMessapge
  56. });
  57. validate(options.auth);
  58. const state = {
  59. octokit,
  60. auth: options.auth
  61. };
  62. octokit.hook.before("request", beforeRequest.bind(null, state));
  63. octokit.hook.error("request", requestError.bind(null, state));
  64. }