简体   繁体   English

如果未登录,如何将用户重定向到登录页面

[英]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.如果用户尝试访问 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.现在的问题是登录路由是在 router.js 中定义的,我无法找出一种方法来访问 rails 控制器中的 vue 路由。

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路由器.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.您无法在 Rails 控制器中访问 Vue 路由。 Vue code, which is just JavaScript code running in your browser, communicates to your Rails controller via HTTP requests and responses. Vue 代码只是运行在浏览器中的 JavaScript 代码,通过 HTTP 请求和响应与 Rails 控制器通信。

From here, it's totally up to you how you choose to communicate somehow from a controller to the JS running in the browser.从这里开始,完全取决于您如何选择以某种方式从控制器到浏览器中运行的 JS 进行通信。

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.有一种状态非常适合您:401 未经授权。 You could你可以

head :unauthorized

from an action and check response status in Vue somehow.从一个动作并以某种方式检查 Vue 中的响应状态。

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.响应头和正文没有太大区别:标题总是传输一个键/值表,对于正文你可以传递任何字符串,但大多数情况下,对于 Vue,你会选择一个带有 JSON 的字符串,它是一个键/值表以及。

You could pass a你可以通过一个

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

in the body and check those values in Vue somehow.并以某种方式在 Vue 中检查这些值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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