@turbo-tools/basic-auth
Pluggable Basic Auth functionality for turbo-http based servers
Getting Started
const check = require('@turbo-tools/basic-auth')
check(request, response, arrayWithUserPasswordPairsOrCallback)
Get the basic auth credentials from the given request. The Authorization
header is parsed and if the header is invalid, false
is returned.
It also sets the WWW-Authenticate
header to Basic realm="example"
by default.
Example
const check = require('@turbo-tools/basic-auth')
const isValid = check(request, response, [['user1', 'pass1'], ['user2', 'pass2']])
// if an `Authorization` is given, it checks for every combination in the array given,
// if it finds a matching pair, it returns true, otherwise false
With turbo-http server
const http = require('turbo-http')
const check = require('@turbo-tools/basic-auth')
// in production environments, use something like tsscmp
// to prevent short-circut and use timing-safe compare
const compare = require('tsscmp')
// Create server
const server = http.createServer(function (req, res) {
const isValid = check(req, res, function (credentials) {
let valid = true
// Simple method to prevent short-circut and use timing-safe compare
valid = compare(name, 'john') && valid
valid = compare(pass, 'secret') && valid
return valid
})
// Check if auth has been successfull & respond accordingly
if (!isValid) {
const denied = 'Access denied'
res.statusCode = 401
res.setHeader('Content-Length', denied.length)
res.write(Buffer.from(denied))
} else {
const granted = 'Access granted'
res.statusCode = 200
res.setHeader('Content-Length', granted.length)
res.write(Buffer.from(granted))
}
})
// Listen
server.listen(3000)
Installing
npm install @turbo-tools/basic-auth --save
Running the tests
All tests are contained in the test.js file, and written using Jest
Run them:
npm test
If you´d like to get the coverage data in addition to runnign the tests, use:
npm run test-coverage
Built With
- NPM - Dependency Management
- Commitizen - Easy semantic commit messages
- Jest - Easy tests
- Semantic Release - Easy software releases
Contributing
Please read CONTRIBUTING.md for details on the process for submitting pull requests to us, and CODE_OF_CONDUCT.md for details on the code of conduct.
Versioning
We use SemVer for versioning. For the versions available, see the tags on this repository.
Authors
- Sebastian Golasch - Initial work - asciidisco
See also the list of contributors who participated in this project.
License
This project is licensed under the MIT License - see the LICENSE.md file for details
Acknowledgments
- Hat tip to @mafintosh for building turbo-net and turbo-http