Browse Source

Setup tokens controller

Lou 3 years ago
parent
commit
2753b9f6c8

+ 20
- 0
app/controllers/api/v1/tokens_controller.rb View File

@@ -0,0 +1,20 @@
1
+class Api::V1::TokensController < ApplicationController
2
+  def create
3
+    @user = User.find_by_email(user_params[:email])
4
+    if @user&.authenticate(user_params[:password])
5
+      render json: {
6
+        token: JsonWebToken.encode(user_id: @user.id),
7
+        email: @user.email
8
+      }
9
+    else
10
+      head :unauthorized
11
+    end
12
+  end
13
+
14
+  private
15
+
16
+  # Only allow a trusted parameter "white list" through.
17
+  def user_params
18
+    params.require(:user).permit(:email, :password)
19
+  end
20
+end

+ 3
- 0
config/application.rb View File

@@ -36,5 +36,8 @@ module RegistraApi
36 36
     # Middleware like session, flash, cookies can be added back manually.
37 37
     # Skip views, helpers and assets when generating a new resource.
38 38
     config.api_only = true
39
+
40
+    # Adds the content of 'lib' folder to Ruby on Rails _autoload_s
41
+    config.eager_load_paths << Rails.root.join('lib')
39 42
   end
40 43
 end

+ 1
- 0
config/routes.rb View File

@@ -2,6 +2,7 @@ Rails.application.routes.draw do
2 2
   namespace :api, defaults: { format: :json }  do
3 3
     namespace :v1 do
4 4
       resources :users
5
+      resources :tokens, only: %i[create]
5 6
     end
6 7
   end
7 8
 end

+ 13
- 0
lib/json_web_token.rb View File

@@ -0,0 +1,13 @@
1
+class JsonWebToken
2
+  SECRET_KEY = Rails.application.credentials.secret_key_base.to_s
3
+
4
+  def self.encode(payload, exp = 24.hours.from_now)
5
+    payload[:exp] = exp.to_i
6
+    JWT.encode(payload, SECRET_KEY)
7
+  end
8
+
9
+  def self.decode(token)
10
+    decoded = JWT.decode(token, SECRET_KEY).first
11
+    HashWithIndifferentAccess.new decoded
12
+  end
13
+end

+ 20
- 0
test/controllers/api/v1/tokens_controller_test.rb View File

@@ -0,0 +1,20 @@
1
+require "test_helper"
2
+
3
+class Api::V1::TokensControllerTest < ActionDispatch::IntegrationTest
4
+  setup do
5
+    @user = users(:one)
6
+  end
7
+
8
+  test 'should get JWT token' do
9
+    post api_v1_tokens_url, params: { user: { email: @user.email, password: 'g00d_pa$$' } }, as: :json
10
+    assert_response :success
11
+
12
+    json_response = JSON.parse(response.body)
13
+    assert_not_nil json_response['token']
14
+  end
15
+
16
+  test 'should not get JWT token' do
17
+    post api_v1_tokens_url, params: { user: { email: @user.email, password: 'b@d_pa$$' } }, as: :json
18
+    assert_response :unauthorized
19
+  end
20
+end

+ 1
- 1
test/fixtures/users.yml View File

@@ -3,4 +3,4 @@
3 3
 one:
4 4
   email: one@one.com
5 5
   username: OneUsername
6
-  password_digest: v@lid_pa$$w0rd
6
+  password_digest: <%= BCrypt::Password.create('g00d_pa$$') %>

Loading…
Cancel
Save