sorceryを使ってapiのユーザー認証をつくる【rails】
はじめに
sorceryを使ってユーザー認証機能のapiを作る準備。
前提
fast_jsonapiというserializerを使用
class UserSerializer include FastJsonapi::ObjectSerializer has_many :articles attributes :name, :email end
sorceryをインストール
gem 'sorcery'
Gemfileにsorcery
と記載してbundle install
。
下記コマンドでsorceryをインストールします。
$ rails g sorcery:install
続いて、authentication
コントローラを作成。
$ rails g controller authentications
ルーティングを追加。
resource :authentication, only: %i[create]
コントローラの中身を記述します。
module Api module V1 class AuthenticationsController < BaseController def create @user = login(params[:email], params[:password]) raise ActiveRecord::RecordNotFound unless user json_string = UserSerializer.new(user).serialized_json render json: json_string end private def form_authenticity_token; end end end end
sorceryのloginメソッドで、メールアドレスとパスワードを認証します。
該当するユーザーがいない場合はエラーを返します。
ユーザーがいる場合は、json形式でユーザーの情報を返します。
確認
postmanを使ってlocalhost:3000/api/v1/authentication
にemailとpasswordを指定してpostリクエストを送ります。
すると、下記のような値が帰ってきます。
{ "data": { "id": "1", "type": "user", "attributes": { "name": "Test1", "email": "test1@example.com" } } }