You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

43 line
1.2 KiB

  1. // Code taken from https://github.com/jshttp/basic-auth/blob/master/index.js
  2. // Copyright(c) 2013 TJ Holowaychuk
  3. // Copyright(c) 2014 Jonathan Ong
  4. // Copyright(c) 2015-2016 Douglas Christopher Wilson
  5. module.exports = auth;
  6. module.exports.parse = parse;
  7. const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/;
  8. const USER_PASS_REGEXP = /^([^:]*):(.*)$/;
  9. function auth(req) {
  10. if (!req) throw new Error('argument req is required.');
  11. if (typeof req != 'object') throw new Error('argument req needs to be an object.');
  12. return parse(getAuthorization(req));
  13. }
  14. function decodeBase64(str) {
  15. return Buffer.from(str, 'base64').toString();
  16. }
  17. function getAuthorization(req) {
  18. if (!req.headers || typeof req.headers != 'object') {
  19. throw new Error('argument req needs to have headers.');
  20. }
  21. return req.headers.authorization;
  22. }
  23. function parse(str) {
  24. if (typeof str != 'string') {
  25. return undefined;
  26. }
  27. const match = CREDENTIALS_REGEXP.exec(str);
  28. if (!match) return undefined;
  29. const userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]));
  30. if (!userPass) return undefined;
  31. return { username: userPass[1], password: userPass[2] };
  32. }