I am writing backend of an app in Rails. As I work on the backend, I need to give the frontend developer a REST API to start building the frontend. Eventually, the frontend and backend will reside together in a single app, but for now they are separate.
For time being I have enabled Cross-origin resource sharing in my app, by adding following to ApplicationController:
config.action_dispatch.default_headers.merge!({
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => '*'
});
For now, I have also turned off CSRF tokens by adding following to application.rb:
skip_before_filter :verify_authenticity_token
I am using Devise for authenticating users. To make Devise work with JSON requests, I have done following:
In devise.rb
config.navigational_formats = ['*/*', :html, :json]
In routes.rb
devise_for :users, :controllers => {:omniauth_callbacks => "omniauth_callbacks", :sessions => 'sessions', :registrations => 'registrations' }
My SessionsController
class SessionsController < Devise::SessionsController
#todo had to do following to support logging in through ajax. need to add logic to send back error response when login fails.
#todo see http://stackoverflow.com/questions/5973327/using-devise-1-3-to-authenticate-json-login-requests/8402035#8402035 and
#todo https://web.archive.org/web/20130928040249/http://jessehowarth.com/devise
#todo see http://stackoverflow.com/questions/11277300/devise-failure-authentication-via-json-sends-back-html-instead-of-json
def create
respond_to do |format|
format.html { super }
format.json {
resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
sign_in(resource_name, resource)
return render :json => {:success => true, :user => resource}
}
end
end
def destroy
respond_to do |format|
format.html { super }
format.json {
Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
render :json => {}
}
end
end
def failure
render :json => {:success => false, :errors => ["Login Failed"]}, :status => 422
end
end
I have a extended Devise's RegistrationsController as well as indicated in routes.rb, but am not posting its content here, as I don't think it is relevant to this question.
With the above setup I am able to send an ajax request to '/users/sign_in' with user[email] and user[password] parameters and have the user signed in. The response looks something like this:
{
success: true
user: {
authentication_token: "SNa2kPqkm5ENsZMx7yEi"
created_at: "2014-12-16T02:40:39.179Z"
email: "xyz#xyz.com"
id: 99999
name: null
provider: null
uid: null
updated_at: "2014-12-17T02:29:31.537Z"
}
}
Now how do I use the authentication_token I received in the sign_in response to send requests to other controller actions that require user to be authenticated? Do I need to set this token in a request header? I am not able to find information on how to use this token. Please help.
It seems following as described in the gist here, the answer is that you send the suer's email and authetication_token with every request to the backend. You may choose to send it in request header or simply as parameters. You simply modify the method that checks the email and token and signs in the user in ApplicationController accordingly. This is my ApplicationController (I am now sending the email and token as parameters in the request):
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
#todo remove this once ui is integrated. following turns off the csrf token:
skip_before_filter :verify_authenticity_token
#todo begin code to support authentication using token
# This is our new function that comes before Devise's one
before_filter :authenticate_user_from_token!
# This is Devise's authentication
before_filter :authenticate_user!
private
def authenticate_user_from_token!
user_email = params[:user_email].presence
user = user_email && User.find_by_email(user_email)
# Notice how we use Devise.secure_compare to compare the token
# in the database with the token given in the params, mitigating
# timing attacks.
if user && Devise.secure_compare(user.authentication_token, params[:user_token])
sign_in user, store: false
end
end
#todo end code to support authentication using token
end
I forgot to mention in my post that I had already added the migration to add a authentication_token column to User model. Also, I had to add following in the User model (as described in the gist), so that an authentication token is generated each time a user is created/updated:
#todo begin code to support ajax authentication of users
#todo see https://gist.github.com/josevalim/fb706b1e933ef01e4fb6
# You likely have this before callback set up for the token.
before_save :ensure_authentication_token
def ensure_authentication_token
if authentication_token.blank?
self.authentication_token = generate_authentication_token
end
end
private
def generate_authentication_token
loop do
token = Devise.friendly_token
break token unless User.where(authentication_token: token).first
end
end
#todo end code to support ajax authentication of users
Related
Currently I am writing some controller test with rspec. The controller requires user to sign in before being usable.
if #current_user.nil?
do something
else
redirect
I currently have issues on how to stub the local variable current_user.
Why not have rspec login to your test system rather than stubbing current_user. You could do something like the following:
describe "Req #5 - login" do
it 'loads the login page' do
get '/login'
expect(last_response.status).to eq(200)
end
it 'loads the user index after login' do
user = User.create(:username => "Raptor", :password => "Raptor")
params = {
:username => "Raptor",
:password => "Raptor"
}
post '/login', params
follow_redirect!
expect(last_response.body).to include("Home Page for: Raptor")
end
end
You can stub the controller's current_user method like this:
let(:current_user) { User.create(...) }
before do
allow(#controller).to receive(:current_user).and_return(current_user)
end
I'm trying to verify my update_password api which updates current user password. I'm using devise and my application is SPA, angular on the front end side. I'm currently getting this error when I try to verify the api with postman client.
def update
#user = User.find(current_user.id)
if #user.update_with_password(user_params)
# Sign in the user by passing validation in case their password changed
sign_in #user, :bypass => true
redirect_to root_path , notice: "Password was successfully changed"
else
# render "edit"
respond_to do |format|
format.html { redirect_to edit_user_registration_path, alert: #user.errors.full_messages.first.to_s }
end
# render "edit"
end
end
It looks to me like you need to specify the user in your headers in Postman. The uri you listed in Postman is to update a user, but your error is saying there's no user sign in path, which I would assume means it doesn't have access to a user to update.
I've got a Sinatra/Warden Remote API, and a client in RubyMotion.
How can I post the Authentication Token and User Object with AFMotion for initial registration (from client)?
This more or less what I have so far, not much I know.
Basically I need to pass through a token to the remote api and a user object.
def register_user(user)
#client = AFMotion::Client.build("http://localhost:9393/register") do
header "Accept", "application/json"
request_serializer: :json
response_serializer :json
end
end
Help?
You can change the line you initiate #client object to something like this
#client = AFMotion::Client.build("http://localhost:9393/") do
header "Accept", "application/json"
response_serializer :json
end
and when you want to do a POST request, you can do
#client.post('register', {
token: 'TOKEN HERE',
user: 'USER OBJECT HERE'
}) do |result|
puts result
end
You can find out more here.
I'm creating an application, which has authentication based on external API with login/register methods. I have a simple controller called RegistrationsController which fires a request using Curb.
This is the controller:
class RegistrationsController < ApplicationController
def new
end
def create
if params[:user][:email].present? && params[:user][:password].present? && params[:user][:phone].present? && params[:user][:login].present?
# API request
password = params[:user][:password]
body = {
"register" => {
"password" => password,
"email" => params[:user][:email],
"phone" => params[:user][:phone],
"login" => params[:user][:login]
}
}
c = Curl::Easy.http_post("http://domain.com/register", body.to_json
) do |curl|
curl.headers['Content-Type'] = 'application/json'
curl.headers['application'] = 'appname'
curl.headers['device'] = 'www'
end
c.perform
response_body = JSON.parse(c.body_str)
throw response_body # This line ALLWAYS gives me 'login taken' error
return
else
#user = User.new(params[:user])
render action: "new", notice: 'Error'
end
end
end
(I also have a views/registrations/new.html.slim view with a simple form but it's not important right now.)
My routes look like this:
match 'users/sign_up' => 'registrations#new', :via => :get, :as => :user_register
match 'users/sign_up' => 'registrations#create', :via => :post, :as => :user_create
My application, after I click the "Register" button on the registrations#new page, is triggering the Curb request two times. As a result, I'm always getting a 'login taken' error. The user is registered successfully but I'm not getting any result from the first request, just from the second one.
It's somehow caused by Rails and I'm 100% sure about it because it can be seen in the API server logs that the request is triggered twice. Also, I have exactly the same script written in PHP and, in there, the registration works fine.
In my Rails dev console, the request is triggered just one time so it's really strange.
Does anyone have any idea what is going on here?
I found the answer.
If anyone struggles with something similar, it was caused by the c.perform line. Just remove it and it will work fine.
I should study the docs better in the future.
I have problem with Same Origin Policy. I want to make cross domain request - I found nice solution: http://www.w3.org/TR/cors/
But I don't want set header in Apache because I have there many domains and only one need it. Is it possible to add Access-Control-Allow-Origin header via Virtual Host or Passenger?
I do it, because I need use Redmine REST API (XHR) in Chrome/Mozilla plugin.
I had a similar requirement. If you want Redmine to serve these headers then you need to modify the Redmine source. I've written a blog post about doing this.
Credit to this blog post for most of the details.
I'll reproduce what I had to do here for convenience:
First let's adress the preflight check. I've added a whole new controller, just for this, at /app/controllers/cors_controller.rb. It looks like:
class CorsController < ApplicationController
skip_before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
def preflight
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version, Content-Type'
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
Pretty simple stuff. I've then routed all OPTIONS requests to this controller in /config/routes.rb:
match '*path', :to => 'cors#preflight', :constraints => {:method => 'OPTIONS'}
Preflight checks taken care of, it's just a case of adding the headers to the main response using an after_filter in /app/controllers/application_controller.rb as suggested by Tom:
class ApplicationController < ActionController::Base
include Redmine::I18n
# ...
before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
#************ Begin Added Code ****************
after_filter :cors_set_access_control_headers
# For all responses in this application, return the CORS access control headers.
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
headers['Access-Control-Max-Age'] = "1728000"
end
#************* End Added Code *****************
#...
end