2012-11-29 5 views
3

레일 백엔드가있는 PhoneGap 앱이 있습니다. json을 사용하여 모바일 앱에서 사용자를 인증하는 것이 가장 좋은 방법인지 알아 내려고합니다.PhoneGap Mobile Rails 인증 (처음부터 인증?)

현재 사용중인 기기는 이지만 사용하지 않아도됩니다.. Phonegap에서 모바일 앱으로 작업 할 수있는 가장 간단한 방법은 무엇입니까?

나는 여기에 꽤 많은 게시물이 있다는 것을 알고있다. 그러나 그들 중 일부는 구식이거나 매우 복잡한 해킹처럼 보인다. 시험되고 테스트 된 일부 프로젝트 또는 자습서에서 최신 정보가 더 많을 수 있습니다.

하나의 게시물에서 jsonp를 사용하는 것이 좋습니다.하지만 꽤 복잡한 해킹처럼 보입니다. 당신은 여기에서 찾을 수 있습니다 http://vimeo.com/18763953

을 난 그냥이 Railscast에 규정되어있는대로, 처음부터 인증을 밖으로 시작하는 더 나을 것인지 나도 궁금 해요 : http://railscasts.com/episodes/250-authentication-from-scratch

감사합니다!

답변

12

컨트롤러의 sessionsregistrations 컨트롤러를 무시해야합니다. 세션 컨트롤러를 재정의하는 방법을 보여 드리겠습니다.

먼저 사용자 모델로 이동하여 토큰 인증 모듈을 추가하십시오. 이런 식으로 뭔가 : 이제

# You can skip storage for :http_auth and :token_auth by adding those symbols to the array below. 
config.skip_session_storage = [:token_auth] 

# Defines name of the authentication token params key 
config.token_authentication_key = :auth_token 

새 컨트롤러에 경로와 지점을 편집 :

devise_for :users, :controllers => { :registrations => 'registrations', :sessions => 'sessions' } 

그리고

devise :token_authenticatable 

before_save :ensure_authentication_token 

그런 다음 해당 모듈을 구성하기 위해 devise.rb 파일을 편집 다음과 같이 컨트롤러를 만드십시오.

class SessionsController < Devise::SessionsController 
    def create 
    respond_to do |format| 
     format.html { 
     super 
     } 
     format.json { 
     build_resource 
     user = User.find_for_database_authentication(:email => params[:user][:email]) 
     return invalid_login_attempt unless resource 

     if user.valid_password?(params[:user][:password]) 
      render :json => { :auth_token => user.authentication_token }, success: true, status: :created 
     else 
      invalid_login_attempt 
     end 
     } 
    end 
    end 

    def destroy 
    respond_to do |format| 
     format.html { 
     super 
     } 
     format.json { 
     user = User.find_by_authentication_token(params[:auth_token]) 
     if user 
      user.reset_authentication_token! 
      render :json => { :message => 'Session deleted.' }, :success => true, :status => 204 
     else 
      render :json => { :message => 'Invalid token.' }, :status => 404 
     end 
     } 
    end 
    end 

    protected 
    def invalid_login_attempt 
    warden.custom_failure! 
    render json: { success: false, message: 'Error with your login or password' }, status: 401 
    end 
end 

Devise has a page about this이지만 이미 구식 인 안내 서를 가리키고 있습니다. 그러나 아마도 그것은 당신을 도울 것입니다.

+0

+1 감사합니다. 모바일 세션에 세션을 저장하는 것에 대해 많이 알고 있습니까? 나는 그 phonegap 쿠키가 없다고, 그래서 그 쿠키를 저장하고 각 요청에 어떻게 든 게시 localStorage 사용해야 줄래? – botbot

+1

btw @Ashitaka, 네 말이 맞아, 그 문서는 좀 구식이야. 모바일 앱과 레일이 요즘 유행하는 것처럼 보이기 때문에 이런 종류의 설정이 더 문서화되지 않았다는 사실에 정말 놀랐습니다. – botbot

+1

로컬 저장소를 검색하면 쉽게 찾을 수 있습니다. Phonegap 앱에서 로그인 할 때 세션 URL에 ajax 호출을하고 ('rake routes'를 사용하여 찾을 수 있습니다.)'localStorage.setItem ('auth_token', authentication_token);'토큰을 저장하십시오. 그런 다음'localStorage.getItem ('auth_token')'으로 검색 할 수 있습니다. – Ashitaka