简体   繁体   English

如果满足条件,即当前登录的用户是管理员,如何仅显示页面?

[英]How do I only display a page if conditions are met i.e. if current logged in user is an admin?

This is more of a syntactical question than anything. 这比什么都更是一个语法问题。 Can't seem to figure out the syntax to write out this proof of concept. 似乎无法弄清楚该概念证明的语法。 I currently have a RoR / psql database that users can sign up for and log in to. 我目前有一个RoR / psql数据库,用户可以注册并登录。 A few forms are restricted for admins (user accounts are not admins by default). 管理员只能使用几种形式(默认情况下,用户帐户不是管理员)。

The actual tab in the navigation header that leads to the form should be visible to all users. 导航标题中指向该表单的实际选项卡应对所有用户可见。 Regular users can even click through, but the page they are directed to should omit the form altogether and inform them that access has been denied. 普通用户甚至可以单击,但他们所指向的页面应完全省略该表格,并告知他们访问已被拒绝。 Below is the idea of what I'm trying to do. 以下是我要执行的操作的想法。 For simplicity, the actual form contents has been omitted. 为简单起见,实际的表格内容已被省略。

Below is /app/views/parts/new.html.erb 以下是/app/views/parts/new.html.erb

<html>
  <head></head>
  <body>
    <%= if current_user.admin? %>
      <div class= "container">
        <!-- form content  -->
      </div>
    <%= else %>
      <div class ="alert alert-danger">
        <strong>Access Denied.</strong> Page requires admin status.
      </div>
    <%end%>
  </body>
</html>

Below is /config/routes.rb 以下是/config/routes.rb

Rails.application.routes.draw do

  root 'sessions#new'
  get '/home', to: 'static_pages#home'
  get '/add/parts', to: 'static_pages#part'
  get '/signup', to: 'users#new'
  post '/signup', to: 'users#create'
  get '/login', to: 'sessions#new'
  post '/login', to: 'sessions#create'


  delete '/logout', to: 'sessions#destroy'

  resources :users
  resources :account_activations, only: [:edit]
  #users can generate new passwords (reset), and change them 
  resources :password_resets, only: [:new, :create, :edit, :update]
  resources :inquires,  only: [:new, :create]
  resources :parts
end

Below is /app/views/layouts/_header.html.erb 以下是/app/views/layouts/_header.html.erb

<html>
<head>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<style>

* {
    box-sizing: border-box;
    margin: 0; 
    padding: 0;
}

html{
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
}

body{
    padding: 80px;
}

header {
    padding: 10px;
    top: 0px;
    left: 0px;
    margin: 0;
    background: #fff;
    min-width: 100%;
    z-index: 1;
    justify-content: center;
    position: fixed;
    display: flex;
}

.nav {
    background: #232323;
    height: 60px;
    *display:inline;
    *zoom:1;
    width: 60%;
    margin: 0;
    padding: 0;
    text-align: center;
    vertical-align: top;
}

.nav li {
    display: inline;
    float: left;
    list-style-type: none;
    position: relative;
}

.nav li a {
    font-size: 14px; 
    color: white;
    display: block;
    line-height: 60px;
    padding: 0 26px;
    text-decoration: none;
    border-left: 1px solid #2e2e2e;
    font-family: Arial;
    text-shadow: 0 0 1px rgba(255, 255, 255, 0.5);
}
.nav li a:hover {
    background-color: #2e2e2e;
}

#search {
    width: 357px;
    margin: 4px;
}
#search_text{
    width: 297px;
    padding: 15px 0 15px 20px;
    font-size: 16px;
    font-family: Arial;
    border: 0 none;
    height: 52px;
    margin-right: 0;
    color: white;
    outline: none;
    background: #494949;
    float: left;
    box-sizing: border-box;
    transition: all 0.15s;
}
::-webkit-input-placeholder { /* WebKit browsers */
    color: white;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color: white;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
    color: white;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
    color: white;
}
#search_text:focus {
    background: #5a5a5a;
}

#options a{
    border-left: 0 none;
}

.subnav {
    visibility: hidden;
    position: absolute;
    top: 110%;
    right: 0;
    width: 200px;
    height: auto;
    opacity: 0;
    z-index: 1;
    transition: all 0.1s;
    background: #232323;
}
.subnav li {
    float: none;
}
.subnav li a {
    border-bottom: 1px solid #2e2e2e;
}
#options:hover .subnav {
    visibility: visible;
    top: 100%;
    opacity: 1;
}

button {
  display: inline-block;
  padding: 10px;
}

</style>
</head>
<body>
  <header>
    <ul class= "nav">
      <li><a class="active" href="/home">Home</a></li>
      <li><%= link_to "Profile", edit_user_path(current_user.id) %></li>
      <li id= "options">
        <a href="#">Add</a>
        <ul class= "subnav">
            <li><%= link_to "Part", new_part_path%></li>
            <li><a href= "/add/projects">Project</a></li>
            <li><a href= "/add/vendors">Vendor</a></li>
        </ul>
      </li>
      <li><%= link_to "Contact", new_part_path(current_user.id) %></li>
      <li><%= link_to "Log Out", logout_path, method: :delete %></li>
      <li id= "search">
        <form action= "" method= "get">
            <input type="text" name="search_text" id= "search_text" placeholder="Search Page"/>
            <button type="submit"><i class="fa fa-search"></i></button>
        </form>
      </li>
    </ul>
  </header>

</body>
</html>

Below is the users_controller.rb 以下是users_controller.rb

class UsersController < ApplicationController
  protect_from_forgery
  #must be logged in to make changes    
  before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
  before_action :correct_user, only: [:edit, :update]
  before_action :admin_user, only: :destroy

  def index
     @users = User.where(activated: true).paginate(page: params[:page])
  end

  def show
    @user= User.find(params[:id])
    redirect_to root_url and return unless @user.activated?
  end

  def new
    @user= User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      @user.send_activation_email
      flash[:info]= "Account created. Check your email to activate it."
      redirect_to root_url
    else
      render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile successfully updated"
      redirect_to @user
    else
      render 'edit' #false, so render the same edit page
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User successfully deleted"
    redirect_to users_url
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

    #users must be logged in to view content
    def logged_in_user
        unless logged_in?
            store_location #store location for after user logs in -> can access 
            flash[:danger]= "Log in to continue."
            redirect_to root_url
      end
    end

    #users can only edit their own profiles
    def correct_user
        @user= User.find(params[:id])
        unless current_user?(@user)
        flash[:danger]= "You do not have permission to do that."
        redirect_to root_url 
      end
    end

    #check for admin status
    def admin_user
      unless current_user.admin?
        flash[:danger]= "Access denied. Not admin."
        redirect_to(root_url) 
      end
    end
end

Conceptually the best way to handle this is to not do it in the view at all. 从概念上讲,处理此问题的最佳方法是根本不执行此操作。

Instead you should handle the authorization logic in the controller and use a before_action filter to redirect the user to the login or somewhere else that makes sense for your application. 相反,您应该处理控制器中的授权逻辑,并使用before_action过滤器将用户重定向到登录名或其他对您的应用程序有意义的位置。

This avoids duplicating the authorization logic in different parts of the MVC stack - it also lets you send an appropriate response code which tells robots not to index / retry the page. 这避免了在MVC堆栈的不同部分中复制授权逻辑-它还使您可以发送适当的响应代码,该代码告诉机械手不要对页面进行索引/重试。

Just remove = from your <% %> blocks that have logic such as if and else . 只需从具有逻辑如ifelse <% %>块中删除= Only use <%= %> blocks for a self-contained variable or function call that returns a value by itself. 仅将<%= %>块用于自行包含返回值的变量或函数调用。

<html>
  <head></head>
  <body>
    <% if current_user.admin? %>
      <div class="container">
        <!-- form content  -->
      </div>
    <% else %>
      <div class="alert alert-danger">
        <strong>Access Denied.</strong> Page requires admin status.
      </div>
    <% end %>
  </body>
</html>

暂无
暂无

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

相关问题 仅当管理员已登录并在 php 中为用户禁用时,我如何启用链接 - how do i enable a link only if admin is logged in and disabled for users in php 当我的循环内条件满足时,如何仅显示特定的控制台 - How do i display only the specific console when my condition inside loop is met 如果用户登录,我如何告诉网页? - How do I tell a webpage if a user is logged in? 如何在用户登录时显示“下载”和“实时预览”按钮,而在用户注销时仅显示“实时预览”按钮? - How do I make “download” and “Live Preview” buttons appear when user logged in but only “Live Preview” button when user logged out? 在 HTML 中,我怎样才能获得只有屏幕阅读器(即盲人)才能访问的文本? - In HTML, how can I have text that is only accessible for screen readers (i.e. for blind people)? 如何获取写入文本的登录用户的用户名并将其永久显示在 Django 中的文本旁边? - How do i get the username of a logged user writing a text and display it beside the text permanently in Django? 当使用if语句过滤前3个图像时,如何从左侧开始显示(即)第3个索引(第4个)图像? - How do I display (i.e.) 3rd index (4th) image in an array starting from the left, when the first 3 images are filtered with if statement? 如何让iframe占据全宽(即像div一样显示) - How to get an iframe to occupy full width (i.e. display like a div) 如何展开和折叠(即切换)表行(tr)? - How do I expand and collapse (i.e. toggling) a table row (tr)? 我如何解构一个 javascript 用户 object 以显示在帐户页面上? - How do i deconstruct a javascript user object to display on an account page?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM