简体   繁体   中英

How to redirect user to sign in page if not logged in

I am trying to redirect the user to sign-in page if the user tries to access MyAccountController. Now the issue is that the sign-in route is defined in router.js and I am not able to figure-out a way to access vue routes in rails controller.

class MyAccountController < ApplicationController
  before_action :authenticate_user!
  before_action :require_user

  private

  def require_user
    head(401) unless user_signed_in?
  end

  def authenticate_user
   if user_signed_in?
      super
    else
      redirect_to 'sign-in'
    end
  end   
end

router.js

const SessionsVue = () => import('views/sessions/new.vue')

const routes = [
 { 'path': '/sign-in', component: SessionsVue, meta: { requiresAuth: true } }
]

You cannot access Vue routes in Rails controller. Vue code, which is just JavaScript code running in your browser, communicates to your Rails controller via HTTP requests and responses.

From here, it's totally up to you how you choose to communicate somehow from a controller to the JS running in the browser.

You don't have many options:

  1. Response status
  2. Response headers
  3. Response body

Response statuses correspond to predefined messages . There's a status that suits you perfectly: 401 Unauthorized. You could

head :unauthorized

from an action and check response status in Vue somehow.

Response headers and body don't differ much: headers always transmit a table of keys/values, for the body you can pass any string, but most often for Vue you would choose a string with JSON, which is a table of keys/values as well.

You could pass a

{ errors: ["Unauthorized"], ok: false }

in the body and check those values in Vue somehow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM