Code Monkey home page Code Monkey logo

hanami-jwt-example's Introduction

JSON API with Hanami 🌸

The goal of this project is to provide an example of a JSON API web application built with Hanami that exposes JWT-protected enpoints.

Main features:

Developed and tested with:

  • Ruby v2.3.1
  • Hanami v1.0

Try it yourself

git clone https://github.com/nickgnd/hanami-jwt-example
cd hanami-jwt-example
bundle install

then edit .env.* files to fit your environment and create the development and test databases

bundle exec hanami db create
bundle exec hanami db migrate
HANAMI_ENV=test bundle exec db create
HANAMI_ENV=test bundle exec hanami db migrate

finally, run tests to check if everything is ok

rake test

The web application exposes an API which allows authenticated users to retrieve a collection of items. The requests to this endpoint will be authenticated through a token based authentication strategy, passing a custom header Authorization containing the user's JWT.

Let's start.

bundle exec hanami server

By default it launches the development server at http://localhost:2300

  1. Before we need to register a new user

To do this, we have to make a POST request against /registration endpoint passing the required informations in the payload.

request:POST /registration

payload:

{ user: { email: "[email protected]", password: "cherryblossom", password_confirmation: "cherryblossom" } }

with curl:

curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -d '{ "user": { "email": "[email protected]", "password": "cherryblossom", "password_confirmation": "cherryblossom" } }' "http://localhost:2300/registration"
  1. Retrive user's jwt

For retrieving the JWT, we have to make a POST request to /sessions path passing user's email and password in the payload.

request: POST /sessions

payload:

{ user: { email: "[email protected]", password: "cherryblossom" } }

The response body will contain the JWT under the key auth_token, save it for the next step (retrieving item collections).

with curl:

curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{ "user": { "email": "[email protected]", "password": "cherryblossom" } }' "http://localhost:2300/sessions"

Response example:

{"auth_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxNCwiaXNzIjoiaHR0cDovL2ludmVudG9yeS5jb20iLCJleHAiOjE0ODkwNDUxNDB9.RI2F5-6rsIU02yXa158iocRP2qKQoR-mi8jbsRM0mDo"}
  1. Retrieving items

Finally, for retrieving the items we have to make a GET request against /items endpoint including the user's jwt in the headers.

request: GET /items

headers: "Authentication": "Bearer <YOUR_JWT>"

with curl:

curl -X GET -H "Content-Type: application/json" -H "Accept: application/json" -H "Authorization: Bearer <YOUR_JWT>" "http://localhost:2300/items"

The response body will be an empty array because there are not items in the database, let's create a new one through the Hanami console:

bundle exec hanami console
item = Item.new(code: 'alfa', available: true)
=> #<Item:0x007fa66b2da7d0 @attributes={:code=>"alfa", :available=>true}>

ItemRepository.new.create(item)
=> #<Item:0x007fa66e040e18 @attributes={:id=>1, :code=>"alfa", :available=>true, :created_at=>2017-03-08 23:00:11 UTC, :updated_at=>2017-03-08 23:00:11 UTC}>

Now the next request will return the item just created

[
  { "id":1,"code":"alfa","available":true,"created_at":"2017-03-08 23:00:11 UTC","updated_at":"2017-03-08 23:00:11 UTC" }
]

et voilà!

Contributing

Feel free to submit issues for questions, bugs and enhancements.

and as usual...

  1. Fork the repo
  2. Create your feature branch
  3. Commit changes to your own branch
  4. Push it
  5. Submit a Pull Request

Credits

This project is inspired by this tutorial Using rails-api to build an authenticated JSON API with warden

hanami-jwt-example's People

Contributors

nickgnd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

hanami-jwt-example's Issues

Failing tests / '==' returns true comparing digest to actual password

Hi first of all thank you for taking the time to create an example as this

After cloning the repository I realised that 4 tests are failing.

  1) Error:
JwtIssuer::#encode#test_0001_returns a new jwt:
NameError: undefined local variable or method `be_nil' for #<#<Class:0x007f8ce6c6d700>:0x007f8ce6551318>
   spec/inventory/services/jwt_issuer_spec.rb:9:in `block (3 levels) in <top (required)>'

  2) Error:
JwtIssuer::#decode#test_0001_returns valid informations if the jwt is valid:
NoMethodError: undefined method `eq' for #<#<Class:0x007f8ce6c6d200>:0x007f8ce9080d90>
    spec/inventory/services/jwt_issuer_spec.rb:18:in `block (3 levels) in <top (required)>'

  3) Error:
JwtIssuer::#decode#test_0002_returns nil if jwt is not valid:
NameError: undefined local variable or method `be_nil' for #<#<Class:0x007f8ce6c6d200>:0x007f8ce907aee0>
    spec/inventory/services/jwt_issuer_spec.rb:24:in `block (3 levels) in <top (required)>'

  4) Error:
JwtIssuer::#decode#test_0003_returns nil if jwt is expired:
NameError: undefined local variable or method `be_nil' for #<#<Class:0x007f8ce6c6d200>:0x007f8ce907a9b8>
    /spec/inventory/services/jwt_issuer_spec.rb:31:in `block (3 levels) in <top (required)>'

Drop unused dependencies if is possible

The Gemfile.lock includes the following dependencies which are not used:

  • hanami-assets
  • hanami-helpers
  • hanami-mailer
  • hanami-view

Drop these dependencies if is possible.

Dockerize

Set up Docker to start Hanami app in a container with docker-compose up

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.