0.0.3 • Published 6 years ago

hapi-current-user v0.0.3

Weekly downloads
1
License
MIT
Repository
github
Last release
6 years ago

hapi-current-user

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

  1. Define Plugin options

    import { User } from "/path/to/models";
    
    module.exports = {
      model: User,
      authColumn: "email"
    };
  2. Register plugin in server.js

    import currentUser from "hapi-current-user";
    import currentUserOptions from "hapi-current-user";
    
    await server.register({
      plugin: currentUser,
      options: currentUserOptions
    });
  3. 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: 'john@email.com',
           *   ...
           * }
           */
        }
      }
    ];

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: 'john@email.com',
       *   ...
       * }
       */
    }
  }
]);
.
.
.
// register currentUser after hapi-auth-jwt2

await server.register({
  plugin: currentUser,
  options: {
    model: User,
    authColumn: "email"
  }
});
.
.
.

Contributing

Feel free to contribute

LICENSE

package licensed under MIT License

Social

Twitter Follow