No authorizer was configured for Ember-Simple-Auth issue (or bug) - ember-cli

After following the Ember-Simple-Auth-Devise installation guide, I came across the following notice on the console:
No authorizer was configured for Ember Simple Auth - specify one if
backend requests need to be authorized.
simple-auth.amd.js:1339
However, I do have the authorizer on the environment which makes me wonder if the culprit is where I placed the code... Also, somehow the Login/Logout on the Ember side is working without any issues.
Original Syntax found on the guide:
//config/environment.js
ENV['simple-auth'] = {
authorizer: 'simple-auth-authorizer:devise'
}
My project environment file:
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'frontend',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'simple-auth') {
authorizer: 'simple-auth-authorizer:devise'
store: 'simple-auth-session-store:local-storage'
}
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
Version Information:
DEBUG: Ember : 1.12.0
DEBUG: Ember Data : 1.0.0-beta.18
DEBUG: jQuery : 1.11.3
DEBUG: Ember Simple Auth : 0.8.0
DEBUG: Ember Simple Auth Devise : 0.8.0

Code placement was the issue as I previously misunderstood the guides... By adding the original syntax just before return ENV the issue has been resolved. This is how my environment file looks now:
...
if (environment === 'production') {
}
ENV['simple-auth'] = {
authorizer: 'simple-auth-authorizer:devise'
}
return ENV;
};

Related

Redirect Strapi admin index to admin login

I am currently looking for way to create a permanent 301 redirect from the default Strapi admin index route (ie strapidomain.com) to the configured admin route (ie strapidomain.com/admin).
I have explored utilizing a custom middleware by configuring the admin package:
Path: ./admin/middlewares/redirect/index.js
const path = require('path');
module.exports = strapi => {
return {
initialize: function(cb) {
strapi.router.get('/', (ctx) => {
ctx.redirect(strapi.config.get('server.admin.url', '/admin'))
});
}
};
};
I then activated the custom middleware with:
Path: ./admin/config/middleware.js
module.exports = {
settings: {
redirect: {
enabled: true
}
}
}
Unfortunately I can still hit the admin panel route without being redirected. Based on everything I have read, this should be possible however I have not been able to get this working.
Thoughts?
for newer version v4+
src/middlewares/redirector.js
module.exports = (config, {strapi}) => {
return async (ctx, next) => {
if (ctx.path === '/') {
ctx.redirect(strapi.config.get('server.admin.url', '/admin'));
return
}
await next()
};
};
config/middlewares.js
module.exports = [
{name: 'global::redirector'},
//...
]
The only issue here is that you just placed the redirect middleware within a admin folder which was absolutely not required. The middlewares folder should directly reside at the root of your project.
Correct the path from:
./admin/middlewares/redirect/index.js
To this:
./middlewares/redirect/index.js
I can show you what I've tried personally, below:
My implementation:
1. Create a directory in the root of your project
$ mkdir -p ./middlewares/redirector/
2. Create a index.js file in ./middlewares/redirector/ with the content as:
module.exports = () => {
return {
initialize() {
strapi.router.get('/', (ctx) => {
ctx.redirect(strapi.config.get('server.admin.url', '/admin'));
});
},
};
};
3. Finally enable the redirector middleware in the config/middleware.js file:
module.exports = {
settings: {
redirector: {
enabled: true,
},
},
};

NextJS PWA Service worker map 404 in Production

I am trying to build a PWA with NextJS and this https://www.npmjs.com/package/next-pwa
It have been working fine in development, but know i try to build and run it in production.
It seems like the files below only is being build when i run it as dev and is thereby missing in the prod build.
enter image description here
Is this an error in my config?
module.exports = withImages(
withPWA({
pwa: {
dest: 'public'
},
env: {
apiUrl: process.env.API_URL
},
webpack: (config, { isServer }) => {
if (!isServer) {
config.node = {
fs: 'empty'
}
}
return config
}
})
)
Please help!

"Unable to connect to the Parse API" using Parse Server on Heroku

I'm getting the error Failed to create new object, with error code: XMLHttpRequest failed: "Unable to connect to the Parse API" when i try to connect to Parse Server API. I deployed ParsePlatform/parse-server-example on Heroku. I can access to my app with a broswser with no problems.I get the error when trying to connect to Parse on Heroku with this code :
var $result=$('#results').html('Testing configuration.....');
Parse.initialize('<MY_APP_ID>', '<MY_JAVASRIPT_KEY>');
Parse.serverURL = '<MY_HEROKU_APP_NAME>.herokuapp.com/'
var ParseServerTest = Parse.Object.extend('ParseServerTest');
var _ParseServerTest = new ParseServerTest();
_ParseServerTest.set('key', 'value');
_ParseServerTest.save(null, {
success: function(_ParseServerTest) {
var txt = 'Yay, your server works! New object created with objectId: ' + _ParseServerTest.id;
$result.html('<div class="alert alert-success" role="alert">' + txt + '</div>');
},
error: function(_ParseServerTest, error) {
var txt = 'Bummer, Failed to create new object, with error code: ' + error.message;
$result.html('<div class="alert alert-danger" role="alert">' + txt + '</div>');
}
});
index.js
// Example express application adding the parse-server module to expose Parse
// compatible API routes.
var express = require('express');
var cors = require('cors');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '', //Add your master key here. Keep it secret!
serverURL: process.env.SERVER_URL || 'https://localhost:1337/parse', // Don't forget to change to https if needed
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var app = express();
app.use(cors());
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
res.status(200).send('I dream of being a website. Please star the parse-server repo on GitHub!');
});
// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
Heroku config :
I followed this post : How can I host my own Parse Server on Heroku using MongoDB? except i didn't use the "Deploy to Eroku" button, i deployed it manually.
Thank you for your help.
Finally I found a way.
I first created another user in my mongo db and change it in Heroku. Try to connect with the same js code code jsfiddle but didn't work...
Then I tried with an android client, this link helped me a lot http://www.robpercival.co.uk/parse-server-on-heroku/
StarterApplication.java
public class StarterApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("BUTYcVjD7nFz4Le")
.clientKey("XgQaeDY8Bfvw2r8vKCW")
.server("https://xxxxx-xxxx-xxxxx.herokuapp.com/parse")
.build()
);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
// defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
ParseObject test = new ParseObject("Test");
test.put("username","pedro");
test.put("age",33);
test.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Log.i("Parse", "Save Succeeded");
} else {
Log.e("Parse", "Save Failed");
}
}
});
}
I really don't know what was the problem with my first user, can't connect with it. I never could connect with the js code... but anyway my goal was to connect with Android client so...

Custom authorizer not called

I'm trying to implement a custom authorizer (using ember-cli and ember-cli-simple-auth) but the authorize method is not being called on any requests. The init function is being called and the message that appears in the console when there is no authorizer registered is no longer showing up. Here is the initializer code:
import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';
import ENV from '../config/environment';
ENV['simple-auth'] = ENV['simple-auth'] || {};
ENV['simple-auth'].authorizer = 'authorizer:custom';
ENV['simple-auth'].crossOriginWhiteList = [ENV.NET.API_ENDPOINT];
var CustomAuthorizer = Base.extend({
init: function () {
console.log('Intialize authorizer');
},
authorize: function(jqXHR, requestOptions) {
console.log('Authorize');
var token = this.get('session.token');
if(this.get('session.isAuthenticated') && !Ember.isEmpty(token)) {
authValue = "Token " + token;
jqXHR.setRequestHeader('Authorization', authValue);
}
}
});
export default {
name: 'authorization',
before: 'simple-auth',
initialize: function(container, application) {
console.log('Registered');
container.register('authorizer:custom', CustomAuthorizer);
}
};
Any help would be appreciated.
Problem here was something quite dumb: my casing of crossOriginWhitelist was incorrect.

Custom authenticator with Ember simple auth + Ember CLI

I'm trying to write a custom authenticator, similar to the one from this example in the docs. The goal is to be able to retrieve the currently logged in user via session.user.
I'm using Ember CLI, so in initializers/authentication.js I have
import Ember from 'ember';
var customAuthenticator = Ember.SimpleAuth.Authenticators.Devise.extend({
authenticate: function(credentials) {
debugger;
}
});
export default {
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.Session.reopen({
user: function() {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return container.lookup('store:main').find('user', userId);
}
}.property('userId')
});
// register the custom authenticator so the session can find it
container.register('authenticator:custom', customAuthenticator);
Ember.SimpleAuth.setup(container, application, {
routeAfterAuthentication: 'landing-pages',
authorizerFactory: 'ember-simple-auth-authorizer:devise'
});
}
};
When I try to authenticate, I get the following error:
TypeError: Cannot read property 'authenticate' of undefined
at __exports__.default.Ember.ObjectProxy.extend.authenticate
Any idea why?
As of Simple Auth 0.6.4, you can now do something like:
index.html:
window.ENV['simple-auth'] = {
authorizer: 'simple-auth-authorizer:devise',
session: 'session:withCurrentUser'
};
initializers/customize-session.js:
import Ember from 'ember';
import Session from 'simple-auth/session';
var SessionWithCurrentUser = Session.extend({
currentUser: function() {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return this.container.lookup('store:main').find('user', userId);
}
}.property('user_id')
});
export default {
name: 'customize-session',
initialize: function(container) {
container.register('session:withCurrentUser', SessionWithCurrentUser);
}
};
You would need to do something like this:
Em.SimpleAuth.Authenticators.OAuth2.reopen
serverTokenEndpoint: "http://myapp.com/token"
authenticate: (credentials) ->
new Em.RSVP.Promise (resolve, reject) =>
data =
grant_type: "password"
username: credentials.identification
password: credentials.password
#makeRequest(data).then (response) =>
# success call
, (xhr, status, error) ->
# fail call
What I think might be happening is that you are registering the authenticator with the application and not the authenticator itself?
The problem is that the AMD build does not currently automatically register the extension libraries' components (see https://github.com/simplabs/ember-simple-auth/issues/198). I'll change that in the next release and will probably also adopt the documentation to be more focussed on the AMD build instead of the browserified version. For the moment you'd have to run this in your initializer
container.register(
'ember-simple-auth-authorizer:devise',
Ember.SimpleAuth.Authorizers.Devise
);
container.register(
'ember-simple-auth-authenticator:devise',
Ember.SimpleAuth.Authenticators.Devise
);