This plugin supprots only Hapi and assumes you are using hapi-auth-jwt2 for authentication
current-user
plugin adds property currentUser
(can be modified) to request object. Now, every handler will have current user
{
method: 'GET',
path: '/api/v1/user',
handler: (request, handler) => {
return request.currentUser;
}
}
Usage
-
Define Plugin options
import { User } from "/path/to/models"; module.exports = { model: User, authColumn: "email" };
-
Register plugin in server.js
import currentUser from "hapi-current-user"; import currentUserOptions from "hapi-current-user"; await server.register({ plugin: currentUser, options: currentUserOptions });
-
In handler you have
// file: routes.js [ { method: "GET", path: "/api/v1/user", handler: (request, handler) => { return request.currentUser; /** Response * { * id: 1, * name: 'John Doe', * email: '[email protected]', * ... * } */ } } ];
Example
import currentUser from "hapi-current-user";
import loginuser from "/path/to/loginUser";
import { User } from "/path/to/models";
server.route([
{
method: "POST",
path: "/api/v1/authenticate",
handler: (request, handler) => {
// hapi-auth-jwt2 is implemented
// in loginUser
return loginUser(request);
},
options: {
auth: false
}
},
{
method: "GET",
path: "/api/v1/user",
handler: (request, handler) => {
return request.currentUser;
/** Response
* {
* id: 1,
* name: 'John Doe',
* email: '[email protected]',
* ...
* }
*/
}
}
]);
.
.
.
// register currentUser after hapi-auth-jwt2
await server.register({
plugin: currentUser,
options: {
model: User,
authColumn: "email"
}
});
.
.
.
Feel free to contribute
package licensed under MIT License