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
Related
I've added PWA functionality to my rails 6.0.2.1 application, also using devise, following this tutorial, with the controller method: https://onrails.blog/2019/01/08/easy-pwas-the-rails-way/
Now whenever I login with any user, I get redirected directly to the service worker file itself (http://localhost:3000/service-worker.js) instead of the root path.
The file itself is copy-pasted from the tutorial, and I followed it step by step.
No matter how hard I looked, I couldn't find what was causing the redirect to the file after login or sign up.
Update: it seems to have to do with self.find_first_by_auth_conditions, the code from devise allowing log in with username instead of email.
Thanks in advance! I'm really stuck...
Log file output on sign in:
# Service Worker Routes
get '/service-worker.js' => "service_worker#service_worker"
get '/manifest.json' => "service_worker#manifest"
# application.js
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/service-worker.js', { scope: './' })
.then(function(reg) {
console.log('[Companion]', 'Service worker registered!');
console.log(reg);
});
}
# service_worker.js.erb
var CACHE_VERSION = 'v1';
var CACHE_NAME = CACHE_VERSION + ':sw-cache-';
function onInstall(event) {
console.log('[Serviceworker]', "Installing!", event);
event.waitUntil(
caches.open(CACHE_NAME).then(function prefill(cache) {
return cache.addAll([
'<%= asset_pack_path 'application.js' %>',
'<%= asset_pack_path 'application.css' %>',
]);
})
);
}
function onActivate(event) {
console.log('[Serviceworker]', "Activating!", event);
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
return cacheName.indexOf(CACHE_VERSION) !== 0;
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
}
// Borrowed from https://github.com/TalAter/UpUp
function onFetch(event) {
event.respondWith(
// try to return untouched request from network first
fetch(event.request).catch(function() {
// if it fails, try to return request from the cache
return caches.match(event.request).then(function(response) {
if (response) {
return response;
}
// if not found in cache, return default offline content for navigate requests
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
console.log('[Serviceworker]', "Fetching offline content", event);
return caches.match('/offline.html');
}
})
})
);
}
self.addEventListener('install', onInstall);
self.addEventListener('activate', onActivate);
self.addEventListener('fetch', onFetch);
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first // row 35 referenced in log file
elsif conditions.has_key?(:username) || conditions.has_key?(:email)
where(conditions.to_h).first
end
end
I had the same problem. Just add a respond_to in your controller action and it will solve it (for me it did at lease).
Your ServiceWorkerController will look like this
class ServiceWorkerController < ApplicationController
protect_from_forgery except: :service_worker
def service_worker
respond_to do |format|
format.js
end
def manifest
end
end
I just ran into this, and in my case the issue was I was storing the previous URL to redirect back to after login and the service-worker was gumming that up. This is specific to my app, but I fixed by adding |service as seen below (the only change).
application_controller.rb
# Redirect the user back to the last page they were on before accessing the sign in/out
before_action :store_location
private
def store_location
session[:previous_url] = request.fullpath unless request.fullpath =~ /\/users|service/
end
def after_sign_in_path_for(resource)
session[:previous_url] || root_path
end
def after_sign_out_path_for(resource)
request.referrer
end
EDIT:
bwalshy - helped me solve the issue - I was rendering a static error message, instead of the actual server response. Once I rendered the server response it was obvious that I was trying to create the test account with the password as "123" which is too weak for the gem's standards. Coding is a humbling experience.
I've seen this question posted, but without any solutions that work for me. I have a React front end that is mounted on top of a Rails app. When I try to call my registrations controller I am getting the following error:
Completed 422 Unprocessable Entity in 103ms
I saw this this could be token related, and logging the token shows what appears to be a valid one: v4Ml1tlzkgBKWBcYGP9SGO+YVL7fxcxs3D8MhC3Z/3ZcZOa5rYGSHUABG+vL+yJfoVfO1Ks6RLI60sQDk7Hh8A==
which is being passed in the headers
The server response is:
{"error":"signup error"}
Here is the React component
import React from "react";
class SignUp extends React.Component {
constructor(props) {
super(props);
this.state = {
signupUnsuccessful: false,
email: '',
passwordOne: '',
passwordTwo: '',
error: null,
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
};
onChange = event => {
this.setState({ [event.target.name]: event.target.value });
}
//this is erroring and I think it's because I'm not telling devise to deliver json
onSubmit(event) {
event.preventDefault();
const url = "http://localhost:3000/users";
const { email } = this.state;
const password = this.state.passwordOne
const userInfo = {
user: {
email,
password
}
}
const token = document.querySelector('meta[name="csrf-token"]').content;
console.log(token)
fetch(url, {
method: "POST",
headers: {
"X-CSRF-Token": token,
"Content-Type": "application/json"
},
body: JSON.stringify(userInfo)
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.catch(error => console.log(error.message));
}
render() {
const {
email,
passwordOne,
passwordTwo,
error,
} = this.state;
const isInvalid =
passwordOne !== passwordTwo ||
passwordOne === '' ||
email === '';
return (
<div>
<h2>Signup</h2>
<form onSubmit={this.onSubmit}>
<input name="email"
value={email}
onChange={this.onChange}
type="text"
placeholder="Email Address"/>
<input name="passwordOne"
value={passwordOne}
onChange={this.onChange}
type="password"
placeholder="Password" />
<input name="passwordTwo"
value={passwordTwo}
onChange={this.onChange}
type="password"
placeholder="Confirm Password"/>
<button disabled={isInvalid} type="submit">
Sign Up
</button>
</form>
<button onClick={() => this.props.changePage("login")}>Login!</button>
</div>
);
};
};
export default SignUp;
and the controller:
class RegistrationsController < Devise::RegistrationsController
def create
#user = User.new(user_params)
if #user.save
render json: #user
else
warden.custom_failure!
render json: { error: 'signup error' }, status: :unprocessable_entity
end
end
def update
#user = User.find_by_email(user_params[:email])
if #user.update_attributes(user_params)
render json: #user
else
warden.custom_failure!
render :json=> #user.errors, :status=>422
end
end
def destroy
#user = User.find_by_email(user_params[:email])
if #user.destroy
render :json=> { success: 'user was successfully deleted' }, :status=>201
else
render :json=> { error: 'user could not be deleted' }, :status=>422
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
And my routes
Rails.application.routes.draw do
devise_for :users, controllers: { registrations: 'registrations', sessions: 'sessions' }
root 'homepage#index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
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
I did an update from 0.7.2 to 1.0.1 with ember-simple-authfor for devise. Reference resources: https://github.com/jimbeaudoin/ember-simple-auth-devise-example .
Now my authentification doesn't work at all, because authenticate_with_http_token alway empty, I could not find any problems with it. Do you have an idea ? Thanks.
Version:
Ember: 2.1.0
Ember Simple Auth: 1.0.1
Rails: 4.2.4
Devise: 3.5.2
No Ember data
Rails:
class Api::SessionsController < Devise::SessionsController
skip_before_action :authenticate_user_from_token!
skip_before_action :verify_authenticity_token
def create
respond_to do |format|
format.html { super }
format.json do
self.resource = warden.authenticate!(auth_options)
sign_in(resource_name, resource)
data = {
token: self.resource.authentication_token,
email: self.resource.email
}
render json: data, status: 201
end
end
end
end
class Api::BaseController < ApplicationController
respond_to :json
before_action :authenticate_user_from_token!
# Enter the normal Devise authentication path,
# using the token authenticated user if available
before_action :authenticate_user!
private
def authenticate_user_from_token!
authenticate_with_http_token do |token, options|
user_email = options[:email].presence
user = user_email && User.unscoped.find_by_email(user_email)
if user && Devise.secure_compare(user.authentication_token, token)
sign_in user, store: false
end
end
end
end
Ember:
login-controller:
import Ember from 'ember';
export default Ember.Controller.extend({
session: Ember.inject.service('session'),
actions: {
authenticate() {
let { identification, password } = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:devise', identification, password).catch((reason) => {
this.set('errorMessage', reason.error);
});
}
}
})
ember model:
import Ember from 'ember';
import PromiseArray from './promise-array';
import PromiseObject from './promise-object';
var Account = Ember.Object.extend({
...
})
Account.reopenClass({
_find() {
return $.get("/api/account.json").then(obj => {
return this.create(obj.user);
})
},
find() {
return PromiseObject.create({promise: this._find()});
}
})
export default Account;
after login route:
import Ember from 'ember';
import Account from '../models/account';
import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model: function() {
return Account.find()
}
})
I think what's failing for you is authorization of requests following the initial login request? Do you authorize outgoing requests anywhere in your Ember app?
I am setting up an ember app that is backed by ruby on rails. I am running into issues with my sign in action using simple-auth and simple-auth-devise. I successfully retrieve the sessions authentication token and username when I submit a correct username and password, but I am still given a 401 access denied error and I can't figure out why. I suspect that it may have to do with the naming of email versus user_email and token vs user_token business. I am taking this code mostly from dayjot, so you'd think it would be trivial to track down this bug but I am having tons of issues finding the exact issue. Thanks for any help you can give me!
The exact error I get in the rails server is:
Started GET "/users/me" for 127.0.0.1 at 2015-02-17 10:25:31 -0600
Processing by UsersController#me as JSON
Parameters: {"user"=>{}}
Filter chain halted as :authenticate_user! rendered or redirected
Completed 401 Unauthorized in 5ms (Views: 4.1ms | ActiveRecord: 0.0ms)
In rails, this is my application controller:
This is my application controller:
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
before_action :authenticate_user_from_token!, :handle_html
around_action :user_time_zone, if: :current_user
def index
render file: 'public/index.html'
end
protected
def authenticate_user!
render(json: {}, status: 401) unless current_user
end
private
def authenticate_user_from_token!
authenticate_with_http_token do |token, options|
user_email = options[:user_email].presence
user = user_email && User.find_by_email(user_email)
if user && Devise.secure_compare(user.authentication_token, token)
request.env['devise.skip_trackable'] = true
sign_in user, store: false
end
end
end
def user_time_zone(&block)
Time.use_zone(current_user.time_zone, &block)
end
# If this is a get request for HTML, just render the ember app.
def handle_html
render 'public/index.html' if request.method == 'GET' && request.headers['Accept'].match(/html/)
end
end
My sessions controller looks like this:
class SessionsController < Devise::SessionsController
def create
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
def destroy
sign_out :user
render json: {}, status: :accepted
end
end
My serializers are these:
class UserSerializer < ActiveModel::Serializer
attributes :id, :password, :user_email, :email, :user_token, :passwordConfirmation
end
class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :email_times, :last_export_time, :plan,
:plan_started, :plan_canceled, :plan_status, :trial_end,
:time_zone, :status, :created_at, :include_email_memory
end
My route is:
Rails.application.routes.draw do
# PLANS
post 'update_plan' => 'plans#update_plan', as: :update_plan
post 'update_card' => 'plans#update_card', as: :update_card
post 'cancel_plan' => 'plans#cancel_plan', as: :cancel_plan
# PASSWORDS
post 'start_password_reset' => 'users#start_password_reset'
put 'finish_password_reset' => 'users#finish_password_reset'
get 'password-reset' => 'application#index', as: :edit_user_password
# USERS
devise_for :users, controllers: { sessions: 'sessions' }, :skip => [:passwords]
resources :users, only: [:create, :update] do
get 'me' => 'users#me', on: :collection
end
# background processing admin
match "/delayed_job" => DelayedJobWeb, :anchor => false, via: [:get, :post]
# catch-all for ember app
get '*path' => 'application#index', :constraints => { :format => 'html' }
end
In the ember-cli app itself, my login controller is:
import Ember from "ember";
export default Ember.Controller.extend({
authenticator: 'simple-auth-authenticator:devise',
identification: null,
password: null,
error: null,
working: false,
actions: {
authenticate: function() {
var _this = this,
data = this.getProperties('identification', 'password');
this.setProperties({
working: true,
password: null,
error: null
});
this.get('session').authenticate('simple-auth-authenticator:devise', data).then(function() {
// authentication was successful
}, function(data) {
_this.set('working', false);
_this.set('error', data.error);
});
}
}
});
My application route is:
// ember-simple-auth
import Ember from "ember";
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
import Notify from 'ember-notify';
import ENV from 'front-end/config/environment';
export default Ember.Route.extend(ApplicationRouteMixin, {
beforeModel: function(transition) {
this._super(transition);
return this.setCurrentUser();
},
actions: {
sessionAuthenticationFailed: function(data) {
this.controllerFor('login').set('working', false);
this.controllerFor('login').set('loginErrorMessage', data.message);
},
sessionInvalidationSucceeded: function() {
this.transitionTo('index');
},
sessionAuthenticationSucceeded: function() {
var _this = this;
this.controllerFor('login').set('working', false);
this.setCurrentUser().then(function() {
if (_this.get('session.currentUser.mustSubscribe')) {
_this.transitionTo('plans');
} else {
_this.transitionTo('courses');
}
});
},
authorizationFailed: function() {
Notify.error("Could not be authenticated.. signing out.", {closeAfter: 5000});
this.get('session').invalidate();
}
},
setCurrentUser: function() {
var _this = this,
adapter = this.get('store').adapterFor('user');
if (this.get('session.isAuthenticated')) {
return new Ember.RSVP.Promise(function(resolve) {
adapter.ajax(ENV.APP.API_HOST + "/users/me", "GET", {}).then(
function(response){
_this.store.pushPayload(response);
var user = _this.store.find('user', response.user.id);
resolve(user);
},
function(response){
resolve(response);
}
);
}).then(function(user) {
_this.set('session.currentUser', user);
}, function() {
Notify.error("Could not be authenticated.. signing out.", {closeAfter: 5000});
_this.get('session').invalidate();
});
} else {
return new Ember.RSVP.Promise(function(resolve){ resolve(); });
}
}
});
Finally my login route is:
import Ember from "ember";
export default Ember.Route.extend({
activate: function() {
if (this.get('session').isAuthenticated) {
this.transitionTo('courses');
}
}
});
And Template is:
<form {{action 'register' on='submit'}} class='d-auth-form fade-in'>
{{#each errors}}
<div class="d-error">
{{this}}
</div>
{{/each}}
{{input placeholder='Email' type='email' value=email autocomplete='off' autocapitalize="none"}}
{{input placeholder='Password' type='password' value=password autocomplete='off'}}
<button type="submit" class='d-btn d-btn--success' {{bind-attr disabled=working}}>
{{#if working}}
Registering..
{{else}}
Sign up for DayJot for free
{{/if}}
</button>
<ul class='d-links'>
<li>{{#link-to 'login'}}Login to existing account{{/link-to}}</li>
</ul>
</form>
The important parts of environment.js are:
'simple-auth': {
crossOriginWhitelist: ['http://localhost:3000','http://localhost:4202','https://api.dayjot.com'],
authorizer: 'simple-auth-authorizer:devise',
authenticationRoute: 'index'
}
and
ENV['simple-auth-devise'] = {
serverTokenEndpoint: ENV.APP.API_HOST+'/users/sign_in',
identificationAttributeName: 'email'
}
Checkout the README - Ember Simple Auth Devise expects the token to be returned as token, you're using user_token however. Thus, the session will never actually be authenticated in Ember and the token won't be included in requests which leads to the 401 response.