如何在不使用任何gem或插件的情况下创建当前用户方法? [英] How to create current user method without using any gem or plugin?

查看:71
本文介绍了如何在不使用任何gem或插件的情况下创建当前用户方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个愚蠢的做法,但是我想知道我们如何创建一个current_user方法来在不使用任何gem或插件的情况下获得整个应用程序的访问权限?为了测试它,我创建了一个应用程序,使用户能够共享文件和文件夹.如何创建用户只能访问其文件夹和文件的方法?这是我的代码示例:

i know it's a silly one but i want to know how can we create a current_user method to get access throughout the app without using any gem or plugin ? To test it i created an app that make a user able to share files and folders.How to create such method that a user can only access his folder and files?Here is my code sample:

登录控制器:

class LoginController < ApplicationController
 layout 'signup'
  #to skip checking the authentication and authorization.
  skip_before_filter  :check_authentication, :check_authorization

  def index
  end

  def authenticate
        if request.post?
            user = User.authenticate(params[:username],params[:password])
            if user
        session[:current_user_id]=user.id
        session[:name]= user.first_name
                puts "session name #{session[:name]}"
                redirect_to(:subdomain => user.company.subdomain, :controller => :dashboard)
      else
        flash.now[:notice] = "Invalid user/password combination"
      end  

        end
  end

  def destroy
    session[:current_user_id] = nil
    reset_session
    flash[:notice] = "You have been successfully logged out."
    redirect_to root_url
  end

end 

用户模型:

require 'digest/sha1'



 class User < ActiveRecord::Base

    #sharering method start
      after_create :check_and_assign_shared_ids_to_shared_folders  
      #this is to make sure the new user ,of which the email addresses already used to share folders by others, to have access to those folders  
      def check_and_assign_shared_ids_to_shared_folders      
        #First checking if the new user's email exists in any of ShareFolder records  
        shared_folders_with_same_email = SharedFolder.find_all_by_shared_email(self.email)  

        if shared_folders_with_same_email        
         #loop and update the shared user id with this new user id   
          shared_folders_with_same_email.each do |shared_folder|  
             shared_folder.shared_user_id = self.id  
             shared_folder.save  
          end  
        end      
      end 

        #to check if a user has acess to this specific folder  
      def has_share_access?(folder)  
          #has share access if the folder is one of one of his own  
          return true if self.folders.include?(folder)  

          #has share access if the folder is one of the shared_folders_by_others  
          return true if self.shared_folders_by_others.include?(folder)  

          #for checking sub folders under one of the being_shared_folders  
          return_value = false  

         folder.ancestors.each do |ancestor_folder|  

            return_value = self.being_shared_folders.include?(ancestor_folder)  
           if return_value #if it's true  
              return true  
            end  
          end  

          return false  
      end  
    #sharing method end

      def self.authenticate(name, password)
        user = self.find_by_username(name)

        if user
          expected_password = encrypt_password(password, user.salt)
          if user.hashed_password != expected_password
            user = nil
          end
        end
        user
      end

      #'password' is a virtual attribute
      def password
        @password
      end

      def password= (pwd)
        @password =pwd
        return if pwd.blank?
        create_new_salt
        self.hashed_password = User.encrypt_password( self.password, self.salt)
      end

        def self.users_in_company(user_id)
            User.find(user_id).company.users 
        end  

     private
      def password_non_blank
        errors.add(:password, "Missing password, please enter your password") if hashed_password.blank?
      end

      def create_new_salt
        self.salt = self.object_id.to_s + rand.to_s
      end

      def self.encrypt_password(password, salt)
        string_to_hash = password +"prftnxt" + salt
        Digest::SHA1.hexdigest(string_to_hash)
      end

    end

我想以"current_user.files"的身份访问所有文件吗?

i want to access all files as "current_user.files" is it possible without any gem?

应用程序助手:

module ApplicationHelper
#for current user to use through out the app
   def current_user
     @current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) # Use find_by_id to get nil instead of an error if user doesn't exist
   end

end

应用程序控制器:

class ApplicationController < ActionController::Base
      include UrlHelper 
      #include ApplicationHelper
      helper_method :current_user #make this method available in views
      protect_from_forgery


#  def current_user
#    @current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) # Use find_by_id to get nil instead of an error if user doesn't exist
#  end



end

并在任务控制器中:

class TasksController < ApplicationController


  # GET /tasks
  # GET /tasks.xml
  def index
    @menu = "Timesheet"
    @page_name = "Manage Task"
    company_id = Company.find_by_subdomain(request.subdomain)
    @users = User.find_all_by_company_id(company_id)
    @tasks = current_user.tasks.all#Task.all
    @task = Task.new

    respond_to do |format|
      format.html # index.html.erb
      format.html # new.html.erb
      format.xml  { render :xml => @tasks }
    end
  end
end

和我收到的错误消息:

NameError in TasksController#index

undefined local variable or method `current_user' for #<TasksController:0xfa7e638>

推荐答案

朋友们,我发现无需使用任何gem或插件即可创建current_user方法的方法:

Hi friends i have found the way to create current_user method without using any gem or plugin:

在我的application_helper.rb中,我这样做了:

In my application_helper.rb i did this :

module ApplicationHelper
  def current_user
    User.find(session[:current_user_id])
  end
end

,最后在我的application controller.rb中我称呼它,因为从这里我可以通过应用程序访问它:

and at the end in my application controller.rb i called this, because from here i can access it through the application:

class ApplicationController < ActionController::Base
  include UrlHelper 
  include ApplicationHelper
  helper_method :current_user
end

现在我可以访问与current user相关的任何数据:

and now i can access any data related to current user:

like:

@tasks = current_user.tasks

感谢我所有的朋友的宝贵回答.

Thanks to all my friends for their valuable answers.

这篇关于如何在不使用任何gem或插件的情况下创建当前用户方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆