Creating a web service with API. To implement a user login function. Since it was the first time to create an API login function, I implemented it referring to the following page.
Implementation of login API for token authentication in Rails --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
The following is created
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: "certification failed" }
end
end
private
def session_params
params.require(:session).permit(:email, :password)
end
end
end
end
It looks like it's done.
I have to implement the logout function from now on.
Recommended Posts