Nuxt.jsとRails APIで認証機能を実装中です。
Nuxt.jsではAuth Moduleを使用しており、Rails APIではknockを使用してトークンを返しております。
Auth Moduleを使用してログインすることはできたのですが、ログインした際$auth.user
に全ユーザーのデータが返ってきてしまいます。
ログインしたユーザーのデータだけを取得したいのですが、どうしたらよいでしょうか?
nuxt.config.js
index.vue
(ログインページ)
users_controller.rb
(Railsのコントローラー)
は以下のようになっております。
js
1// nuxt.config.js 2 3 modules: [ 4 '@nuxtjs/axios', 5 '@nuxtjs/proxy', 6 '@nuxtjs/auth' 7 ], 8 9 auth: { 10 redirect: { 11 login: '/', // ログインページ 12 logout: '/', // ログアウト後の遷移先 13 home: '/mypage' // ログイン後の遷移先 14 }, 15 strategies: { 16 local: { 17 endpoints: { 18 login: { 19 url: '/user_token', 20 method: 'post', 21 propertyName: 'jwt' 22 }, 23 user: { 24 url: '/users', 25 method: 'get', 26 propertyName: 'data' 27 } 28 }, 29 tokenRequired: true 30 } 31 } 32 }, 33 34 axios: { 35 baseURL: 'http://localhost:3333/api/v1', 36 credentials: true 37 }
js
1 2// index.vue 3// ログインボタンを押したら以下のメソッドを呼び出しログインします 4 5 methods: { 6 async login() { 7 this.error = false 8 try { 9 await this.$auth.loginWith('local', { 10 data: { 11 auth: { 12 email: this.email, 13 password: this.password 14 } 15 } 16 }) 17 this.$router.push('/mypage') 18 } catch (e) { 19 this.error = true 20 console.log('Error: ' + e) 21 } 22 } 23 }
rb
1# users_controller.rb 2 3module Api 4 module V1 5 class UsersController < ApplicationController 6 before_action :authenticate_user 7 before_action :set_user, only: [:show, :update, :destroy] 8 9 def index 10 users = User.order(created_at: :desc) 11 render json: { status: 'SUCCESS', message: 'Loaded users', data: users } 12 end 13 14 def show 15 render json: { status: 'SUCCESS', message: 'Loaded the user', data: @user } 16 end 17 18 def create 19 user = User.new(user_params) 20 if user.save 21 render json: { status: 'SUCCESS', data: user } 22 else 23 render json: { status: 'ERROR', data: user.errors } 24 end 25 end 26 27 def destroy 28 @user.destroy 29 render json: { status: 'SUCCESS', message: 'Deleted the user', data: @user } 30 end 31 32 def update 33 if @user.update(user_params) 34 render json: { status: 'SUCCESS', message: 'Updated the user', data: @user } 35 else 36 render json: { status: 'SUCCESS', message: 'Not updated', data: @user.errors } 37 end 38 end 39 40 private 41 42 def set_user 43 @user = User.find(params[:id]) 44 end 45 46 def user_params 47 params.require(:user).permit(:name, :email, :password_digest) 48 end 49 end 50 end 51end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。