LoginSignup
0
0

More than 3 years have passed since last update.

【RubyonRails】APIでadd_token_to_usersしてログイン機能を実装する

Last updated at Posted at 2020-09-11

はじめに

APIでウェブサービスを制作中。
ユーザーのログイン機能を実装することに。
APIのログイン機能作るのは初めてだったので、下記のページを参考に実装。

Railsでトークン認証のログインAPI実装 - Qiita

環境

MacBookAir
ruby 2.6.3
Rails 6.0.3.2

ルーティングを考える

config/routes.rb
Rails.application.routes.draw do
  namespace 'api' do
    namespace 'v1' do
      post '/login', to: 'sessions#create'
    end
  end
end

マイグレーションの追加

$rails g migration Add_token_To_Users token:token

以下が作成される

db/migrate/20200911133819_add_token_to_users.rb
class AddTokenToUsers < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :token, :string
    add_index :users, :token, unique: true
  end
end

モデル

class User < ApplicationRecord
    has_secure_token
end

コントローラー

app/controllers/api/v1/users_controller.rb
module Api
    module V1
class SessionsController < ApplicationController
  def create
    user = User.find_by(email: session_params[:email])

    if user&.authenticate(session_params[:password])
        session[:user_id] = user.id
        return render json: { token: user.token}
    else
        return render json: { status: 401, message: "認証に失敗しました" } 
    end

   end

  private

  def session_params
    params.require(:session).permit(:email, :password)
  end
end
end
end

POSTMANでログインを試してみる

できたっぽい。

スクリーンショット 2020-09-19 16.51.37.png

終わりに

これからログアウト機能も実装しないと。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0