I am building a React - Rails API application. Following a tutorial, I intentionally did not instantiate Rails as an API, rather it's the full framework. So, according to the the tutorial giver, I should have access to session and not have to download any gems.
Problem: When I refresh the page the session should keep the user logged in. It is not. Instead of returning with: { logged_in: true, user: {...} }, it is returning with { logged_in: false } (the else conditional in session's logged_in method). The #current_user from the concern file is returning as nil, more specifically, its session[:user_id] is returning nil, so the conditional is failing.
I'm out of ideas, I've been messing with this for over an hour and still no luck. If anything else is needed please let me know.
Rails: Sessions Controller
class SessionsController < ApplicationController
include CurrentUserConcern
def create
user = User.find_by(email: params["user"]["email"])
.try(:authenticate, params["user"]["password"])
if user
session[:user_id] = user.id
// binding.pry shows session[:user_id] = 4 (or whatever the id is)
render json: {
status: :created,
logged_in: true,
user: user
}
else
render json: { status: 401 }
end
end
// Method in question:
def logged_in
// #current_user == nil
if #current_user
render json: {
logged_in: true,
user: #current_user
}
else
render json: {
logged_in: false
}
end
end
def logout
reset_session
render json: { status: 200, logged_out: true }
end
end
Rails: controllers/concerns/current_user_concern.rb
module CurrentUserConcern
extend ActiveSupport::Concern
included do
before_action :set_current_user
end
def set_current_user
if session[:user_id]
// binding.pry shows session[:user_id] = nil
#current_user = User.find_by(id: session[:user_id])
end
end
end
React: App.js
// Method that is interacting with Rails
checkLoginStatus = () => {
axios
.get('http://localhost:3001/logged_in', { withCredentials: true })
.then((response) => {
// Does not enter the conditions RESPONSE = data.logged_in: false
if (response.data.logged_in && this.state.loggedInStatus === 'NOT_LOGGED_IN') {
this.setState({ loggedInStatus: 'LOGGED_IN', user: response.data.user });
} else if (!response.data.logged_in && this.state.loggedInStatus === 'LOGGED_IN') {
this.setState({ loggedInStatus: 'NOT_LOGGED_IN', user: {} });
}
})
.catch((error) => console.log('hello error.', error));
};
you need to add the following config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore to config/application.rb
Related
I recently deployed my site on Heroku and Netlify and was having issues with Auth. My current issue (and hopefully last) is that upon login, rails is sending back a user instance instead of the object with information (i.e #User:0x000056205efbbad8). I get a token from my rails response and upon refresh am logged in but am not automatically logged in because of the user instance being returned instead of an object with user information.
This is my auth controller
class AuthController < ApplicationController
def login
user = User.find_by(username: params[:username])
if user && user.authenticate(params[:password])
secret = ENV["SECRET_KEY_BASE"]
token = JWT.encode({ user_id: user.id }, secret, 'HS256')
render json: { user: UserSerializer.new(user), token: token }
else
render json: { failure: "Invalid Username or Password" }
end
end
def signup
auth_params = params.permit(:username, :password, :email, :avatar)
if params[:avatar].instance_of?(String) || params[:avatar].nil?
user = User.create(auth_params)
render json: user
else
imageUploaded = Cloudinary::Uploader.upload(params[:avatar])
user_params_new = auth_params
user_params_new[:avatar] = imageUploaded["url"]
user = User.create(user_params_new)
if user.valid?
secret = ENV["SECRET_KEY_BASE"]
token = JWT.encode({ user_id: user.id }, secret, 'HS256')
render json: {user: user, token: token }, status: :created
else
render json: { error: user.errors.full_messages }, status: :unprocessable_entity
end
end
end
end
Here is my login function on my React frontend
function handleLogin(e) {
e.preventDefault()
fetch(`${process.env.REACT_APP_API_BASE_URL}/login`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(loginData)
})
.then(r => r.json())
.then(data => {
if (data.failure) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Incorrect Username or Password!'
})
} else {
setCurrentUser(data.user)
setUserReviews(data.user.reviews)
setFavorites(data.user.favorites)
localStorage.setItem("token", data.token)
history.push("/festivals")
}
})
}
I so appreciate any help on this, thanks so much!
Link to github repo: https://github.com/connormul/festie-backend
https://github.com/connormul/festie-frontend
render json: { user: UserSerializer.new(user), token: token }
This doesn't look a correct use of serializer
try to change it to
render json: { user: UserSerializer.new(user).as_json, token: token }
I am trying to implement Omniauth with Devise in Rails API with NuxtJS framework.
I did auth module connexion and user account creation with Omniauth method but i would like understand how redirect the user afer signin/signup, i am Rails developer and beginner with NuxtJS.
BACKEND
User model oauth registration method:
def self.from_facebook(auth)
where(uid: auth.uid, provider: auth.provider).first_or_create do |user|
user.email = auth.info.email
user.first_name = auth.info.first_name
user.last_name = auth.info.last_name
user.password = Devise.friendly_token[0, 20]
user.provider = auth.provider
user.uid = auth.uid
Client.create(user: user)
end
end
Registration controller:
# frozen_string_literal: true
module Overrides
class RegistrationsController < DeviseTokenAuth::ApplicationController
before_action :set_user_by_token, only: [:destroy, :update]
before_action :validate_sign_up_params, only: :create
before_action :validate_account_update_params, only: :update
skip_after_action :update_auth_header, only: [:create, :destroy]
def create
build_resource
unless #resource.present?
raise DeviseTokenAuth::Errors::NoResourceDefinedError,
"#{self.class.name} #build_resource does not define #resource,"\
' execution stopped.'
end
# give redirect value from params priority
#redirect_url = params.fetch(
:confirm_success_url,
DeviseTokenAuth.default_confirm_success_url
)
# success redirect url is required
if confirmable_enabled? && !#redirect_url
return render_create_error_missing_confirm_success_url
end
# if whitelist is set, validate redirect_url against whitelist
return render_create_error_redirect_url_not_allowed if blacklisted_redirect_url?
# override email confirmation, must be sent manually from ctrl
resource_class.set_callback('create', :after, :send_on_create_confirmation_instructions)
resource_class.skip_callback('create', :after, :send_on_create_confirmation_instructions)
if #resource.respond_to? :skip_confirmation_notification!
# Fix duplicate e-mails by disabling Devise confirmation e-mail
#resource.skip_confirmation_notification!
end
if #resource.save
if params[:farmer]
Farmer.create(
user: #resource
)
else
Client.create(
user: #resource
)
end
yield #resource if block_given?
unless #resource.confirmed?
# user will require email authentication
#resource.send_confirmation_instructions({
client_config: params[:config_name],
redirect_url: #redirect_url
})
end
if active_for_authentication?
# email auth has been bypassed, authenticate user
#client_id, #token = #resource.create_token
#resource.save!
update_auth_header
end
render_create_success
else
clean_up_passwords #resource
render_create_error
end
end
def update
if #resource
if #resource.send(resource_update_method, account_update_params)
yield #resource if block_given?
render_update_success
else
render_update_error
end
else
render_update_error_user_not_found
end
end
def destroy
if #resource
#resource.destroy
yield #resource if block_given?
render_destroy_success
else
render_destroy_error
end
end
def sign_up_params
params.permit(
:first_name,
:last_name,
:email,
:cellphone,
:phone,
:password,
:password_confirmation,
:birthdate
)
end
def account_update_params
params.permit(*params_for_resource(:account_update))
end
protected
def build_resource
#resource = resource_class.new(sign_up_params)
#resource.provider = provider
# honor devise configuration for case_insensitive_keys
if resource_class.case_insensitive_keys.include?(:email)
#resource.email = sign_up_params[:email].try(:downcase)
else
#resource.email = sign_up_params[:email]
end
end
def render_create_error_missing_confirm_success_url
response = {
status: 'error',
data: resource_data
}
message = I18n.t('devise_token_auth.registrations.missing_confirm_success_url')
render_error(422, message, response)
end
def render_create_error_redirect_url_not_allowed
response = {
status: 'error',
data: resource_data
}
message = I18n.t('devise_token_auth.registrations.redirect_url_not_allowed', redirect_url: #redirect_url)
render_error(422, message, response)
end
def render_create_success
render json: {
status: 'success',
data: resource_data
}
end
def render_create_error
render json: {
status: 'error',
data: resource_data,
errors: resource_errors
}, status: 422
end
def render_update_success
render json: {
status: 'success',
data: resource_data
}
end
def render_update_error
render json: {
status: 'error',
errors: resource_errors
}, status: 422
end
def render_update_error_user_not_found
render_error(404, I18n.t('devise_token_auth.registrations.user_not_found'), status: 'error')
end
def render_destroy_success
render json: {
status: 'success',
message: I18n.t('devise_token_auth.registrations.account_with_uid_destroyed', uid: #resource.uid)
}
end
def render_destroy_error
render_error(404, I18n.t('devise_token_auth.registrations.account_to_destroy_not_found'), status: 'error')
end
private
def resource_update_method
if DeviseTokenAuth.check_current_password_before_update == :attributes
'update_with_password'
elsif DeviseTokenAuth.check_current_password_before_update == :password && account_update_params.key?(:password)
'update_with_password'
elsif account_update_params.key?(:current_password)
'update_with_password'
else
'update_attributes'
end
end
def validate_sign_up_params
validate_post_data sign_up_params, I18n.t('errors.messages.validate_sign_up_params')
end
def validate_account_update_params
validate_post_data account_update_params, I18n.t('errors.messages.validate_account_update_params')
end
def validate_post_data which, message
render_error(:unprocessable_entity, message, status: 'error') if which.empty?
end
def active_for_authentication?
!#resource.respond_to?(:active_for_authentication?) || #resource.active_for_authentication?
end
end
end
Omniauth callbacks controller:
def facebook
#user = User.from_facebook(request.env["omniauth.auth"])
# NOTE: redirection here
end
FRONTEND
Stategie:
facebook: {
client_id: 'CLIENT_ID',
userinfo_endpoint: 'https://graph.facebook.com/v2.12/me?fields=about,name,picture{url},email,birthday',
redirect_uri:'http://localhost:3000/omniauth/facebook',
scope: ['public_profile', 'email', 'user_birthday']
}
Login method:
facebookLogin () {
this.$auth.loginWith('facebook')
.then((response) => {
this.$toast.success({
title: 'Connexion réussie',
message: 'Vous vous êtes bien connecté.',
position: 'bottom center',
timeOut: 3000
})
})
.catch(() => {
this.$toast.error({
title: 'Erreur',
message: 'L\'email ou le mot de passe ne sont pas valides. Vérifiez votre saisie.',
position: 'bottom center',
timeOut: 8000
})
})
.finally(() => this.$wait.end('signing in'))
}
A couple of things...
Omniauth callbacks controller is missing the redirect information (is that why that note is there?). If you're using Devise, it should say something like sign_in_and_redirect #user underneath the #user = ... line.
Devise comes with built in routes. To use them, you must include something like, devise for :users in your routes.rb file. Check out the "Devise_for magic" section on this page to see an example of these built in routes. Note that you have to have some Devise models configured for this to work.
Run rake routes to see if the routes you have defined are what you're expecting.
If you can't figure it out, I also created a project using Omniauth and devise. You can view my code here.
I'm working on authentication (using Knock) for my rails API and I can't hit my POST route to create a new user using a react client. I am able to hit this route in Postman and it successfully creates a new user. I can see I hit the route in postman from the terminal, but when I try it on my client I don't get any response in the terminal.
Things I've tried
Ensured client and server are running on different ports
I have my client on localhost:3000 and my server on localhost:3001
Made sure I have CORS set up
I am using the gem 'rack-cors' and have a cors initializer setup according to the docs for Rails 5. (I can include this file if you believe its needed)
I also have enabled CORS on my chrome web browser
Try another POST route
I am able to successfully log in on the client side (using a user's email/password I created in postman) and generate a JWT token using a POST route to my api
Made sure I am getting to the action creator from my container
I put a debugger in the action creator to make sure I am hitting it when I submit the form. I hit it and have all the relevant info I need (first name, last name, email, and password) to complete the request.
I think the problem lies somewhere in my userSignUpFetch action creator or in my user Controller.
Action creator that handle process of sending new user object to rails
export const userSignUpFetch = (user) => {
const newUser = user
return dispatch => {
return fetch(`http://localhost:3001/api/users`, {
method: "POST",
headers: {
Accept:"application/json",
"Content-Type":"application/json"
},
body: JSON.stringify({user: user})
})
.then(response => response.json())
.then(jresp => {
dispatch(loginUserFetch({
first_name: newUser.first_name,
last_name: newUser.last_name,
email: newUser.email,
password: newUser.password})
);
})
.catch((errors) => {
dispatch(authFailure(errors))
})
};
}
My current Routes for auth in Rails
api_users GET /api/users(.:format) api/users#index
POST /api/users(.:format) api/users#create
api_user GET /api/users/:id(.:format) api/users#show
PATCH /api/users/:id(.:format) api/users#update
PUT /api/users/:id(.:format) api/users#update
DELETE /api/users/:id(.:format) api/users#destroy
api_user_token POST /api/user_token(.:format) api/user_token#create
api_find_user POST /api/find_user(.:format) api/users#find
My Rails User Controller
class Api::UsersController < ApplicationController
before_action :set_user, only: [:show, :update]
def index
#users = User.all
render json: #users
end
def create
#user = User.create(user_params)
if #user.valid? && #user.save
render json: #user
else
render json: #user.errors, status: 400
end
end
def show
render json: #user
end
def update
if #user.update(user_params)
render json: #user
else
render json: #user.errors, status: 400
end
end
def destroy
#user.destroy
end
def find
#user = User.find_by(email: params[:user][:email])
if #user
render json: #user
else
#errors = #user.errors.full_messages
render json: #errors
end
end
private
def set_user
#user = User.find_by(id: params[:id])
end
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password)
end
end
I'm expecting to see something like
Started POST "/api/users" for ::1 at 2019-05-28 17:56:41 -0500
in my terminal, but when I hit that action creator I don't get any response from my terminal running the server. I'm wondering if anybody has any suggestions on what to look for. Thanks.
Update
I believe it is something with my dispatch.
This below works, up until jresp.loginUserFetch
export const userSignUpFetch = user => {
//Fetch request info
const newUser = JSON.stringify({user: user})
const userAuth = JSON.stringify({user})
const options = {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: newUser
}
const fetchURL = `${API_URL}/users`
return fetch(fetchURL, options)
.then(resp => resp.json())
.then(jresp => jresp.loginUserFetch({
first_name: userAuth.first_name,
last_name: userAuth.last_name,
email: userAuth.email,
password: userAuth.password}))
.catch( err => {
console.log('Request Failed:', err)
})
}
Update 2- Got it To work
I imported fetch from cross fetch as well as cleaned it up a little, but it works as attended now which makes me believe I needed cross-fetch in the file.
export const userSignUpFetch = user => {
//Fetch request info
const newUser = JSON.stringify({user: user})
const options = {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: newUser
}
const fetchURL = `${API_URL}/users`
return dispatch => {
return fetch(fetchURL, options)
.then(resp => resp.json())
.then(jresp => { dispatch(loginUserFetch({
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
password: user.password})
)
})
.catch( err => {
console.log('Request Failed:', err)
})
}
}
authenticate_with_http_token do |token, options|
auth_key = AuthKey.find_by(authentication_token: token)
if auth_key.present?
if auth_key.token_valid?
auth_key.touch
sign_in(:user, auth_key.user, store: false, bypass: false) unless current_user.present?
else
render json: { message: t('invalid_otp_access'), errors: [t('token_expired')] }, status: 401 and return
end
else
render json: { message: t('invalid_access_message'), errors: [t('invalid_access')] }, status: 401 and return
end
end
i need to write spec for the above code, in my controller i am using current_user.
My controller looks like below.
def index
schedules = params[:type] == "upcoming" ? :upcoming : :past
schedules = current_user.audit_schedules.send(schedules)
if schedules.present?
paginate json: schedules, per_page:10, root: false, each_serializer: Api::V1::MyAuditSerializer
else
render json: { message: t('.no_audits_scheduled'), errors: [] }
end
end
and i am trying to test my index with passing valid token and params
context "with invalid attributes" do
it "It will return list of audits" do
request.headers["Authorization"] = "Token #{auth_key.authentication_token}"
#request.env["devise.mapping"] = Devise.mappings[:user]
get :index, { params: { type: "upcoming" } }
expect(response.body).to eq 200
end
end
the above spec returning body like
<html><body>You are being redirected.</body></html>
And in my spec helper i included devise helpers like
config.include Devise::TestHelpers, type: :controller
If i remove that helper current_user is always nil. if i add that helper it is redirecting like above, please let me know what i missed and how can i test those spec.
I think you want user_signed_in? vs. current_user.present?. This doesn't fix the problem.
You're sure user is not null? and that the user has been confirmed if you're using confirmable?
Digging through the code, I see this:
if options[:bypass]
warden.session_serializer.store(resource, scope)
elsif warden.user(scope) == resource && !options.delete(:force)
# Do nothing. User already signed in and we are not forcing it.
true
else
warden.set_user(resource, options.merge!(scope: scope))
end
source: https://github.com/hassox/warden/blob/906edf86c6c31be917a921097031b89361d022e8/lib/warden/proxy.rb
You can try adding :force which should force the setting of the user.
I did an update from 0.6.4 to 0.7.2 with Ember Simple Auth (not Ember CLI version) for devise, now my authentification doesn't work at all :(, do you have an idea ? thank you very much for your help :)
PS : apparently, ApplicationController (application_controller.rb) don't continue after authenticate_with_http_token do |token, options| and authenticate_with_http_token is empty (tested with puts)
login_controller.js
App.LoginController = Ember.Controller.extend(SimpleAuth.LoginControllerMixin, {
authenticator: 'simple-auth-authenticator:devise'
//authenticator: 'authenticator:custom'
});
application.js.coffee
Ember.Application.initializer
name: "authentication"
after: "simple-auth"
initialize: (container, application) ->
applicationRoute = container.lookup("route:application")
session = container.lookup("simple-auth-session:main")
# handle the session events
session.on "sessionAuthenticationSucceeded", ->
applicationRoute.transitionTo "Myspace"
return
return
window.ENV = window.ENV || {}
window.ENV["simple-auth"] = { store: 'simple-auth-session-store:local-storage', authorizer: "simple-auth-authorizer:devise" };
window.ENV['simple-auth-devise'] = {
crossOriginWhitelist: ['*'],
serverTokenEndpoint: 'users/sign_in',
};
login.hbs
<br />
<div class="row">
<div class="large-12 columns">
<form {{action 'authenticate' on='submit'}}>
<label for="identification">Login</label>
{{input id='identification' placeholder='Enter Login' value=identification}}
<label for="password">Password</label>
{{input id='password' placeholder='Enter Password' type='password' value=password}}
<button type="submit">Login</button>
</form>
</div>
</div>
login_route.js.coffee
App.LoginRoute = Ember.Route.extend(
#model: (params) ->
#return #store.find('user', #get('session.user_id'))
setupController: (controller, model) ->
#controller.set "content", model
controller.set "errorMessage", null
return
actions:
sessionAuthenticationFailed: (responseBody) ->
message = responseBody.error
#controller.set "errorMessage", message
console.log "errorMessage : " + message
return )
myspace_route.js.coffee
App.MyspaceRoute = Ember.Route.extend(SimpleAuth.AuthenticatedRouteMixin, ....)
session_controller.rb
class SessionsController < Devise::SessionsController
def create
respond_to do |format|
format.html { super }
format.json do
self.resource = warden.authenticate!(auth_options)
sign_in(resource_name, resource)
data = {
user_token: self.resource.authentication_token,
user_email: self.resource.email
}
render json: data, status: 201
end
end
end
end
application_controller.rb
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: :null_session,
if: Proc.new { |c| c.request.format =~ %r{application/json} }
before_filter :skip_trackable, :authenticate_user_from_token!
private
def skip_trackable
request.env['warden'].request.env['devise.skip_trackable'] = '1'
end
def authenticate_user_from_token!
puts "authentification"
puts authenticate_with_http_token
authenticate_with_http_token do |token, options|
user_email = options[:user_email].presence
user = user_email && User.find_by_email(user_email)
puts "user.authentication_token"
puts user.authentication_token
puts token
puts "token"
if user && Devise.secure_compare(user.authentication_token, token)
sign_in user, store: false
end
end
end
end
You're setting up the window.ENV object in the initializer that runs after the 'simple-auth' initializer so Ember Simple Auth cannot actually see the values that you set when its initializer runs. Make sure the values are set before the 'simple-auth' initializer runs.
Also you should switch to Ember CLI of course ;)
After a run of debugger, it goes to :
ember-simple-auth.js
authenticate: function() {
var args = Array.prototype.slice.call(arguments);
var authenticator = args.shift();
Ember.assert('Session#authenticate requires the authenticator factory to be specified, was ' + authenticator, !Ember.isEmpty(authenticator));
var _this = this;
var theAuthenticator = this.container.lookup(authenticator);
Ember.assert('No authenticator for factory "' + authenticator + '" could be found', !Ember.isNone(theAuthenticator));
return new Ember.RSVP.Promise(function(resolve, reject) {
theAuthenticator.authenticate.apply(theAuthenticator, args).then(function(content) {
_this.setup(authenticator, content, true);
resolve(); // <- it goes to here
}, function(error) {
_this.clear();
_this.trigger('sessionAuthenticationFailed', error);
reject(error);
});
});
},
The json response with token seems to be ok, and authenticator config seems to be ok also ...
Also i have a "Rejected" in this promise
ember-simple-auth.js
restore: function() {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var restoredContent = _this.store.restore();
var authenticator = restoredContent.authenticator;
if (!!authenticator) {
delete restoredContent.authenticator;
_this.container.lookup(authenticator).restore(restoredContent).then(function(content) {
_this.setup(authenticator, content);
resolve();
}, function() {
_this.store.clear();
reject();
});
} else {
_this.store.clear();
reject();
}
});
},
Trace of the Rejected promise :
VM7522:164 Ember Inspector (Promise Trace):
at new Promise (http://localhost:3000/assets/ember.js?body=1:10174:9)
at __exports__.default.Ember.ObjectProxy.extend.restore (http://localhost:3000/assets/ember-simple-auth.js?body=1:1116:16)
at __exports__.default (http://localhost:3000/assets/ember-simple-auth.js?body=1:1337:15)
at __exports__.default.initialize (http://localhost:3000/assets/ember-simple-auth.js?body=1:447:9)
at http://localhost:3000/assets/ember.js?body=1:43164:11
at visit (http://localhost:3000/assets/ember.js?body=1:43556:7)
at DAG.topsort (http://localhost:3000/assets/ember.js?body=1:43610:11)
at Namespace.extend.runInitializers (http://localhost:3000/assets/ember.js?body=1:43161:15)
at Namespace.extend._initialize (http://localhost:3000/assets/ember.js?body=1:43046:14)
Edit 1: and also this one :
ember-simple-auth-devise.js
restore: function(properties) {
var _this = this;
var propertiesObject = Ember.Object.create(properties);
return new Ember.RSVP.Promise(function(resolve, reject) {
if (!Ember.isEmpty(propertiesObject.get(_this.tokenAttributeName)) && !Ember.isEmpty(propertiesObject.get(_this.identificationAttributeName))) {
resolve(properties);
} else {
reject();
}
});
},
with trace :
Ember Inspector (Promise Trace):
at new Promise (http://localhost:3000/assets/ember.js?body=1:10174:9)
at __exports__.default.Base.extend.restore (http://localhost:3000/assets/ember-simple-auth-devise.js?body=1:156:16)
at apply (http://localhost:3000/assets/ember.js?body=1:7993:27)
at superWrapper [as restore] (http://localhost:3000/assets/ember.js?body=1:7571:15)
at http://localhost:3000/assets/ember-simple-auth.js?body=1:1121:51
at invokeResolver (http://localhost:3000/assets/ember.js?body=1:10192:9)
at new Promise (http://localhost:3000/assets/ember.js?body=1:10178:9)
at __exports__.default.Ember.ObjectProxy.extend.restore (http://localhost:3000/assets/ember-simple-auth.js?body=1:1116:16)
at __exports__.default (http://localhost:3000/assets/ember-simple-auth.js?body=1:1337:15)
With the help of marcoow, just modified https://github.com/simplabs/ember-simple-auth/tree/master/packages/ember-simple-auth-devise#server-side-setup SessionsController like this :
class SessionsController < Devise::SessionsController
def create
respond_to do |format|
format.html { super }
format.json do
self.resource = warden.authenticate!(auth_options)
sign_in(resource_name, resource)
#data = {
user_token: self.resource.authentication_token,
user_email: self.resource.email
}
render json: #data.to_json, status: 201
end
end
end
end
Now it's working
Edit : to_json explanation : http://apidock.com/rails/ActiveRecord/Serialization/to_json