2014-07-10 2 views
1

Michael Hartl (http://www.railstutorial.org/book/modeling_users)의 레일 튜토리얼 서적을 기반으로 매우 간단한 레일 앱이 있습니다. 이 앱은 똑같이 간단한 iOS 앱을위한 콘텐츠 관리 시스템입니다. 나는 devise가 매우 유명하다는 것을 알고 있지만, 나는 이것이이 프로젝트에 필요하다고 생각하지 않는다. 내 iOS 앱을 내 레일 앱에 연결할 수 있기를 원하지만 내가 알 수있는 유일한 조언을 찾는 곳은 어디서나 궁리하다. 내가 원하는 것은 로그인 화면을 사용자에게 제공하여 세션을 설정할 수있게 한 다음 레일스 끝의 모든 권한 논리를 처리 할 수있게하려는 것뿐입니다. 여기에 내 현재 인증 방식의 아이디어를 제공 할 몇 가지 사항rails + iOS authentication with devise

내 세션 컨트롤러 :

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 

답변

1

당신은 토큰 기반의 시스템에 갈 수있다 세션 기반 시스템이 아닌

모든 사용자에 대해 인증 토큰이라는 속성을 만듭니다. 이 토큰은 가입시 생성 및 할당 할 수 있습니다. 토큰 자체는 SecureRandom.hex(n)과 같은 간단한 기술을 사용하여 생성 할 수 있습니다. n은 생성 된 임의의 16 진수의 길이입니다.

앱에서 로그인/가입 한 후 서버의 응답에 인증 토큰을 보냅니다. 그런 다음 iOS 앱에서 모든 후속 요청과 함께 토큰을 서버로 보낼 수 있습니다.

컨트롤러가 요청에 응답 할 때마다 서버가 토큰을 확인하도록하십시오. 이는 before_filter을 사용하여 수행 할 수 있습니다. 따라서 샘플 컨트롤러는 다음과 같을 수 있습니다.

before_filter :authenticate_user 

    def authenticate_user 
     # assuming the parameter sent from the app is called auth_token 
     auth_token = params[:auth_token] 
     user = User.find_by_authentication_token(auth_token) 

     if user.nil? 
     # what to do if user does not exist 
     else 
     # what to do if user exists 
     end 
    end 
0

일반적으로 모바일 응용 프로그램의 경우 세션 대신 토큰이 사용됩니다. 토큰은 본질적으로 Rails 앱이 각 모바일 장치에 액세스 권한을 부여 할 줄 문자열입니다.

  1. 1 단계는 모바일 앱이 Rails 앱 (사용자 정의 이메일/비밀번호 로그인 또는 Facebook과 같은 타사를 통해)을 통해 인증되도록하는 것입니다. 레일에
  2. 앱이 요청을 할 때마다 (또는 웹 소켓 연결 등) :
  3. 은 레일 앱이 모바일 응용 프로그램
  4. 스토어 iOS에서 UserDefaults이 토큰 (http://www.learnswiftonline.com/objective-c-to-swift-guides/nsuserdefaults-swift/ 도움말 링크)에 토큰을 보내 응용 프로그램, 토큰을 (일반적으로 헤더로) 보냅니다.
  5. iOS 앱이 열릴 때마다 UserDefaults에서 토큰을 확인하십시오. 그곳에 있으면 사용자 인증을 건너 뛰게됩니다.
  6. 정말 멋진 앱을 원한다면 Rails 앱은 토큰을 한 번만 받아 들여야하며 각 요청에 대해 새 토큰을 발행해야합니다. 따라서 iOS 앱은 각 요청마다 토큰을 보내고 각 응답마다 새 애플리케이션을 가져옵니다. 이것은 좀 더 안전한 방법이므로 누군가가 Rails 앱으로 토큰을 잡고 혼란에 빠지지 않습니다.

이 다이어그램은 상위 인증 프로세스 (초기 인증을 위해 FB 로그인을 사용하지만 사용자 대신 또는 다른 시스템을 연결할 수 있음)를 포함합니다 : http://www.eggie5.com/57-ios-rails-oauth-flow.