【发布时间】:2014-08-31 23:20:42
【问题描述】:
我有一个非常简单的 Rails 应用程序,我根据 Michael Hartl (http://www.railstutorial.org/book/modeling_users) 的 rails 教程书推出了自己的身份验证。该应用程序是一个内容管理系统,适用于同样简单的 iOS 应用程序。我知道设计很受欢迎,但我真的认为这个项目没有必要。我希望能够将我的 iOS 应用程序链接到我的 Rails 应用程序,但无论在哪里,我都能找到的唯一建议是如何使用设计来做到这一点。我想要做的就是让用户看到一个登录屏幕,这样他们就可以建立一个会话,然后我可以处理所有在 Rails 端的权限逻辑。这里有几件事可以让您了解我当前的身份验证方案:
我的会话控制器:
class SessionsController < ApplicationController
def new
end
##
#Use the email in the nested hash to find the right user
#Check to make sure that the user authenticates with the given password
##
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_back_or root_url
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
current_user.update_attribute(:remember_token,User.digest(User.new_remember_token))
cookies.delete(:remember_token)
self.current_user = nil
session.delete(:return_to) #not sure if this should really be here or if better way to fix bug
redirect_and_alert(root_url, "User Successfully Logged Out!",:success)
end
end
会话助手:
module SessionsHelper
##
#set the remember token for the user
#make the cookie reflect that token
#update the users remember token column
#set the user being passed in as the current user
##
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.digest(remember_token))
self.current_user = user
end
#set the current user
def current_user=(user)
@current_user = user
end
#Helper current user method
def current_user
remember_token = User.digest(cookies[:remember_token])
@current_user ||= User.find_by(remember_token: remember_token)
end
#Is the requesting user the current user
def current_user?(user)
user == current_user
end
#Is the user signed in?
def signed_in?
!current_user.nil?
end
#Store user request info for friendly forwarding
def redirect_back_or(default)
redirect_to(session[:return_to] || default)
session.delete(:return_to)
end
#Store user request info for friendly forwarding
def store_location
session[:return_to] = request.url if request.get?
end
#Authorization
def signed_in_user
store_location
redirect_to signin_url, notice: "Please sign in." unless signed_in?
end
def super_user
redirect_and_alert(root_url,
"You are not allowed to do that. Contact the admin for this account.",
:error) unless (current_user.role.id == 1)
end
def super_user_or_admin
redirect_and_alert(root_url,
"You are not allowed to do that. Contact the admin for this account.",
:error) unless (current_user.role.id == 1 || current_user.role.id == 2)
end
def is_super_user
current_user.role.id == 1
end
def is_admin
current_user.role.id == 2
end
def is_regular_user
current_user.role.id == 3
end
end
【问题讨论】:
标签: ios ruby-on-rails authentication devise