http-auth-client
Version:
Client side HTTP Authorization header handling
40 lines (31 loc) • 1.12 kB
JavaScript
const Auth = require('./auth')
class Basic {
constructor(params) {
params = params ? params.params || params : {}
this.realm = params.realm || ""
this.charset = params.charset == "UTF-8" ? "UTF-8" : ""
}
credentials(username, password) {
this.secret = Buffer.from(username + ":" + password, this.charset == "UTF-8" ? "utf8": "ascii").toString('base64')
return this
}
authorization() {
if(!this.secret) throw new Error("No credentials")
return this.type + " " + this.secret
}
update(params) {
if(typeof params == 'string') {
// params is a www-authenticate header
var challenges = Auth.pick(params, [Basic])
if(challenges.length != 1) throw new Error(`Challenge type ${this.type} not available`)
params = challenges[0].params
} else if(params && params.params) params = params.params
if(params.realm) this.realm = params.realm
if(params.charset) this.charset = params.charset == "UTF-8" ? "UTF-8" : ""
// Always needs new credentials
delete this.secret
return true
}
}
Basic.prototype.type = "Basic"
module.exports = Basic