hapi-auth-ownership
v1.0.1
Published
Ownership-based access control for your routes.
Downloads
2
Readme
hapi-auth-ownership
Simple authentication scheme to verify resource ownership. Clients must pass the validation rule assigned to a route to be able to access it. The ownership-access
scheme takes the following options:
rules
- (required) an object with rules; each rule is a function with the signaturefunction(request, credentials, callback)
where:request
- is the Hapi request object of the request which is being authenticatedcredentials
- the credentials object, taken fromrequest.auth.credentials
callback
- a callback function with the signaturefunction(err, isValid, credentials)
where:err
- an internal errorisValid
-true
if the client is granted accesscredentials
- a credentials object passed back to the application inrequest.auth.credentials
; if you do not include this, the plugin will pass the previous credentials back to Hapi
errorMessage
- (optional) the error message that will be sent on invalid requests; set toYou do not have access to this resource
by defaultcompanionStrategy
- (required) the strategy that will be used to retrievecredentials
; this is required because ownership checks require a credentials object
var users = {
john: {
id: '123',
username: 'john',
password: 'secret'
}
};
var validate = function(request, username, password, callback) {
var user = users[username];
if (!user) {
return callback(null, false);
}
callback(null, password === user.password, user);
};
server.register(require('hapi-auth-basic'), function(err) {
server.auth.strategy('simple', 'basic', { validateFunc: validate }); // [1]
server.register(require('hapi-auth-ownership'), function (err) {
server.auth.strategy('ownership', 'ownership-access', {
rules: {
account: function(request, credentials, callback) {
callback(null, request.params.id === credentials.account.id); // [2]
}
},
errorMessage: 'OOPS!', // [3]
companionStrategy: 'simple' // [4]
});
server.route({
method: 'DELETE',
path: '/account/{id}',
config: {
plugins: {
hapiAuthOwnership: {
ownershipRule: 'account' // [5]
}
}
}
});
});
});
- Define the companion strategy.
- The authenticated user only has access to their own account.
- Custom error message.
- The credentials will be retrieved from this strategy.
- Specify the rule to use. This will be taken from the
options.rules
object. If you don't specify anownershipRule
the request will be validated => the client has access.