Issue with using devise gem authentication with Mobile app (Titanium) - ruby-on-rails

I am using Devise gem in my Rails app for authentication. I could able to create user by passing data in Json request format to devise rails app from Titanium mobile application.
But when i try to set up login in mobile app to use devise, it shows an error like below
{"error":"You need to sign in or sign up before continuing."}
My code looks like below
var regDetails = '{"email": "'+userNmTxt.value+'", "password": "'+passwordTxt.value+'"}';
var client = Titanium.Network.createHTTPClient({timeout: 5000});
client.open("POST", "http://10.100.85.43:3000/session/create");
client.setRequestHeader("Content-Type", "application/json");
client.send(regDetails);
client.onload = function(e)
{
alert('Logged in successfully' + this.responseText);
}
client.onerror = function(e)
{
alert('On error' + this.responseText);
}
What am i doing wrong?

I found the solution, i was missing some routing information in routes.rb file
devise_scope :user do
match "/session/create" => "session#create" #, :via => [:get, :post]
match "/session/destroy" => "session#destroy" #, :via => [:get, :post]
match "/registration/create" => "registration#create" #, :via => [:get, :post]
end
Hope this will help someone :)

Related

Authenticating Rails Application With Omniauth Github in Local

I am working on authenticating users using GitHub in local development mode.
I am using using omniauth-github Rubygem.
I have bellow code in config/initializers/omniauth.rb
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'],
{
:client_options => {
:site => 'https://github.com/api/v3',
:authorize_url => 'https://github.com/login/oauth/authorize',
:token_url => 'https://github.com/login/oauth/access_token',
}
}
end
In view layout I have
<%= link_to "Sign in with Github", "/auth/github" %>
In routes.rb I have
match 'auth/:provider/callback' => 'session#create', :via => [:get, :post]
match 'signout' => 'session#destroy', :via => [:delete], :as => 'signout'
I have registered new application in github with
Homepage URL : http://localhost:3000
, Authorization callback URL : http://localhost:3000/callback
After clicking on Sign in with Github, I am getting following error.
http://localhost:3000/callback?error=redirect_uri_mismatch&error_description=The redirect_uri MUST match the registered callback URL for this application.&error_uri=https://developer.github.com/v3/oauth/#redirect-uri-mismatch&state=14216a2416431297d9690e68efe0723a03aa7a1eaee51db3
Kindly help me to set proper values for site ,authorize_url , token_url to work in local system.

No route matches [GET] sessions

I've made authorization following this tutorial: https://www.railstutorial.org/book/sign_in_out#cha-sign_in_sign_out but now I want to add subdomains to my application.
I've added this to my routes.rb:
match '/' => 'students/board', :constraints => { :subdomain => 'student' }, via: 'get'
If I want to redirect user after sign in to his subdomain like this:
redirect_to :subdomain => 'student', :path => '/'
I'm getting this error:
No route matches [GET] "/sessions"
If I redirect user without a subdomain he is normally redirected. I don't understand why it's trying to get 'sessions' path. I would be grateful for some suggestions. I didn't find anything online which is related to login sessions and subdomains.
Thanks!
There might be something in your code you aren't showing us redirecting you to the sessions path.
Have you tried naming the path then redirecting there?
routes.rb:
get '/' => 'students/board', :constraints => { :subdomain => 'student' }, as: 'student_login'
then use:
redirect_to student_login_path

Omniauth-saml in Rails: Route not found error for /auth/saml/metadata

I have a routing question in Rails (3.2.1).
I am using omniauth-saml for authentication (https://github.com/PracticallyGreen/omniauth-saml). The doc says:
"The service provider metadata used to ease configuration of the SAML SP in the IdP can be retrieved from http://example.com/auth/saml/metadata. Send this URL to the administrator of the IdP."
When I go to myserver.com/auth/saml/metadata, I get a routing error (No route matches). The only relevant route I have in routes.rb is /auth/:provider/callback. What route do I need to add to be able to access the metadata URL?
The authentication itself is working as expected. I am only having problems with the metadata.
Thanks a lot!
You can generate a metadata route by adding the following matcher to routes.rb*:
devise_scope :user do
match "/users/auth/:action/metadata",
constraints: { action: /saml/ },
to: "omniauth_callbacks",
as: :user_omniauth_metadata,
via: [:get, :post]
end
Resulting in the following route (sans "(.format)"):
user_omniauth_metadata GET|POST /users/auth/:action/metadata omniauth_callbacks#(?-mix:saml)
This is in addition to the standard omniauth routes:
user_omniauth_authorize GET|POST /users/auth/:provider omniauth_callbacks#passthru {:provider=>/saml/}
user_omniauth_callback GET|POST /users/auth/:action/callback omniauth_callbacks#(?-mix:saml)
which results from:
devise_for :users, controllers: { omniauth_callbacks: "omniauth_callbacks" }
Note: I am doing this with devise in the :user scope, but outside the scope it would look more like:
match( "/auth/:action/metadata",
constraints: { action: /saml/ },
to: "omniauth_callbacks",
as: :omniauth_metadata,
via: [:get, :post]
)
You also need to define a callback for "other_phase";
e.g. add something like the following to your SAML strategy
module OmniAuth
module Strategies
class Saml
include OmniAuth::Strategy
def other_phase
if on_path?("#{request_path}/metadata")
# omniauth does not set the strategy on the "other_phase"
#env['omniauth.strategy'] ||= self
setup_phase
response = OneLogin::RubySaml::Metadata.new
settings = OneLogin::RubySaml::Settings.new # set whatever params you want on this guy
Rack::Response.new(response.generate(settings), 200,
{ "Content-Type" => "application/xml" }).finish
else
call_app!
end
end
end
end
end
The routes matching I derived from this handy post: http://answer.techwikihow.com/1312028/omniauth-rails-change-url.html

How can I use Rails routes to redirect from one domain to another?

My app used to run on foo.tld but now it runs on bar.tld. Requests will still come in for foo.tld, I want to redirect them to bar.tld.
How can I do this in rails routes?
This works in Rails 3.2.3
constraints(:host => /foo.tld/) do
match "/(*path)" => redirect {|params, req| "http://bar.tld/#{params[:path]}"}
end
This works in Rails 4.0
constraints(:host => /foo.tld/) do
match "/(*path)" => redirect {|params, req| "http://bar.tld/#{params[:path]}"}, via: [:get, :post]
end
This does the job of the other answer. Though in addition, it preserves query strings as well. (Rails 4):
# http://foo.tld?x=y redirects to http://bar.tld?x=y
constraints(:host => /foo.tld/) do
match '/(*path)' => redirect { |params, req|
query_params = req.params.except(:path)
"http://bar.tld/#{params[:path]}#{query_params.keys.any? ? "?" + query_params.to_query : ""}"
}, via: [:get, :post]
end
Note: If you're dealing with full domains instead of just subdomains, use :domain instead of :host.
similar to other answers, this one worked for me:
# config/routes.rb
constraints(host: "foo.com", format: "html") do
get ":any", to: redirect(host: "bar.com", path: "/%{any}"), any: /.*/
end
The following solution redirects multiple domains on GET and HEAD requests while returning http 400 on all other requests (as per this comment in a similar question).
/lib/constraints/domain_redirect_constraint.rb:
module Constraints
class DomainRedirectConstraint
def matches?(request)
request_host = request.host.downcase
return request_host == "foo.tld1" || \
request_host == "foo.tld2" || \
request_host == "foo.tld3"
end
end
end
/config/routes.rb:
require 'constraints/domain_redirect_constraint'
Rails.application.routes.draw do
match "/(*path)", to: redirect {|p, req| "//bar.tld#{req.fullpath}"}, via: [:get, :head], constraints: Constraints::DomainRedirectConstraint.new
match "/(*path)", to: proc { [400, {}, ['']] }, via: :all, constraints: Constraints::DomainRedirectConstraint.new
...
end
For some reason constraints Constraints::DomainRedirectConstraint.new do didn't work for me on heroku but constraints: Constraints::DomainRedirectConstraint.new worked fine.
Bit more modern approach:
constraints(host: 'www.mydomain.com') do
get '/:param' => redirect('https://www.mynewurl.com/:param')
end
constraints(host: /subdomain\.domain\.com/) do
match '/(*path)' => redirect { |params, req|
"https://www.example.com#{req.fullpath}"
}, via: [:get, :head]
end
I use this when using custom domains on Heroku and I want to redirect from the myapp.herokuapp.com -> www.example.com.

How to access POST variables in Rails?

I'm not really a Rails developer and I'm working on someone else's code.
Anyway, I'm trying to change the login function so that it uses POST instead of GET. Right now it looks like this:
def login
email = params[:email];
password = params[:password];
# login logic ...
end
What do I need to change to use POST variables instead?
EDIT: The line that looked relevant in routes.rb
match "service/login", :to => "service#login"
If there's something else I'm looking for, please let me know.
Change:
match "service/login", :to => "service#login"
to:
match "service/login", :to => "service#login", :via => :post
or (shorter):
post "service/login"
please try this:
match "service/login", :to => "service#login", :via => :post
and don't forget to use :method => :post in your login form :)

Resources