Disabling default sails.js routes - javascript

I'm setting up a basic Sails.js app, and I'm trying to disable the default routing system in sails.js. The documentation here seems to indicate it can be disabled in the /config/blueprints.js file, by setting module.exports.blueprints = { actions: false };
However, when I do sails lift, I'm still able to access my default controller at /foo
Edit: This is using Sails v0.10.5, with no changes other than the two files below.
/** /api/controllers/FooController.js **/
module.exports = {
index: function(req, res) {
return res.send("blah blah blah");
}
};
/** /config/blueprints.js **/
module.exports.blueprints = {
actions: false,
rest: false,
shortcuts: false,
prefix: '',
pluralize: false,
populate: false,
autoWatch: true,
defaultLimit: 30
};
Additionally, the issue continues to occur if I disable blueprints on a per-controller basis:
/** /api/controllers/FooController.js **/
module.exports = {
_config: { actions: false, shortcuts: false, rest: false },
index: function(req, res) {
return res.send("blah blah blah");
}
};
The controller is still accessible at /foo

The problem is a little bit tricky. You are trying to open Controller.index method.
At the same time you are disabled routing for all actions.
But actually Sails.js in 0.10.5 has additional configuration that disables index route from controller.
Its name: index.
So you disabled auto routing for all actions except index..
To disable all auto routes you have to set:
_config: {
actions: false,
shortcuts: false,
rest: false,
index: false
}
Seems that somebody just forgot to add this into docs.

You can do this by using policies under the config folder.
module.exports.policies = {
YourControllerName: {
'find': true,
'*': false
}
}

To disable the default rest routes generated for models you should set rest: false
in file /config/blueprints.js
This solution is for sails V1.x
/***************************************************************************
* *
* Automatically expose RESTful routes for your models? *
* *
***************************************************************************/
rest: false,

Related

How to fetch i18next translations from REST endpoint?

We are using i18next in a react project to translate labels in our frontend. Currently the translations are placed in a public/locales/en/common.json file which is working fine.
We need to obtain the translations from a REST Api.
There's i18next-http-backend which seems to do what I'm looking for. I don't get it to work however.
The i18n initialization is done using appWithTranslation HOC and the config looks as following.
export default appWithTranslation(MyApp, {
i18n: {
locales: ['de', 'en'],
defaultLocale: 'en',
},
fallbackLng: {
default: ['en'],
},
nonExplicitSupportedLngs: true,
lowerCaseLng: true,
debug: true,
backend: {
loadPath: '/api/translations/{{lng}}/{{ns}}',
allowMultiLoading: false,
parse: (data: any) => {
console.log('parse is called')
return data
},
request: () => {
console.log('request');
},
},
use: [I18NextHttpBackend],
});
I expected this config to trigger a http request to the configured API but that's not happening. Neither console.log is being called.
Anyone with experience using i18next-http-backend?

Defining Auth strategy using Glue

I am using glue to spin up the hapi server so I gave the json object with connection and registration details.
I have 10 routes and i need to use authentication strategy for all the 10 routes, So followed the below steps
1) I have registered the xyz custom auth plugin
2) Defined the strategy server.auth.strategy('xyz', 'xyz', { });
3) At every route level I am enabling auth strategy
auth: {
strategies: ['xyz'],
}
How can I give below line to glue configuration object itself.
server.auth.strategy('xyz', 'xyz', { });
Glue.compose(ServerConfig, { relativeTo: baseDir }, (err, server) => {
internals.server = server;
})
One more question here is, in this line server.auth.strategy('xyz', 'xyz', { from json file}); I am reading the JSON data from a config file. When I change the data in this JSON file I dont want to restart the server manually to load the modified data. Is there any plugin or custom code to achieve this?
I figured out a general workaround for when you want to do setup that Glue does not directly support (AFAIK) and you also don't want to keep adding to index.js.
Create a plugins folder where your manifest.js is located.
Create a file plugins/auth.js (in this case). Here you will have a register callback with access to the server object and you can make setup calls that go beyond what Glue does declaratively.
Add a plugin item to manifest.js pointing to your plugin file.
in manifest.js:
register: {
plugins: [
{
plugin: './plugins/auth',
},
]
}
in plugins/auth.js:
module.exports = {
name: 'auth',
async register (server) {
await server.register([
require('#hapi/cookie'),
]);
server.auth.strategy('session', 'cookie', {
cookie: {
name: 'sid-example',
password: '!wsYhFA*C2U6nz=Bu^%A#^F#SF3&kSR6',
isSecure: false
},
redirectTo: '/login',
validateFunc: async (request, session) => {
const account = await users.find(
(user) => (user.id === session.id)
);
if (!account) {
return { valid: false };
}
return { valid: true, credentials: account };
}
});
server.auth.default('session');
},
};
(auth setup code is from the Hapi docs at enter link description here)
This is the way I have found where I can call things like server.auth.strategy() sort-of from manifest.js.
Note: Auth is not a great example for this technique as there is a special folder for auth strategies in lib/auth/strategies.

How to change the default configuration of Sails JS middleware

I am trying to alter the settings of a Sails JS app and am having a bit of bother passing a parameter to the body-Parser in order to change the default settings.
I previously had the issue described here: Posting larger files
I believe this problem has been answered correctly by changing the default 'limit' option, as a 100kb default size minus the 33% overhead from the formData object is pretty consistent with what size of file I can/can't send. So the solution proposed was this:
var bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded( { limit: 1048576 } ));
but am unable to implement the solution in my Sails app. I have read through the Sails Documentation on changing the middleware settings, and tried the following in my config/http.js file...
First attempt - wrapper
/**
* HTTP Server Settings
* (sails.config.http)
*/
module.exports.http = {
middleware: {
order: [
'startRequestTimer',
'cookieParser',
'session',
'refreshSessionCookie',
'bodyParserInit',
'bodyParser',
'handleBodyParserError',
'compress',
'methodOverride',
'poweredBy',
'$custom',
'requestLogger',
'router',
'www',
'favicon',
'404',
'500'
],
bodyParserInit : (function (){
let bodyParser = require('body-parser');
return bodyParser( { extended: true, limit: 1073741824 } )
})(),
)
},
// cache: 31557600000
};
Second attempt - overwrite
/**
* HTTP Server Settings
* (sails.config.http)
*/
module.exports.http = {
middleware: {
order: [
'startRequestTimer',
'cookieParser',
'session',
'refreshSessionCookie',
//'bodyParserInit',
'bodyParser',
'handleBodyParserError',
'compress',
'methodOverride',
'poweredBy',
'$custom',
'requestLogger',
'router',
'www',
'favicon',
'404',
'500'
],
bodyParser: (function _configureBodyParser(){
let skipper = require('skipper');
let middlewareFn = skipper({
limit: 1073741824,
});
return middlewareFn;
})(),
)
},
// cache: 31557600000
};
However, neither attempt solved my issue as the limit still appears to be set 100kb regardless of anything I've done. How do I implement this correctly, so that the body parser accepts files of up to 50kb? I presume either I am not configuring this correctly or something else is overwriting what I've done.
EDIT: I'm using Sails version > 12.0.X
If you are using Sails > v0.12.x:
module.exports.http = {
middleware: {
// ... options
bodyParser: require('skipper')({ limit: 1073741824 })
}
};
For sails < v0.12.x:
module.exports.http = {
middleware: {
order: [
// ... options
// 'bodyParser', <- remove bodyParser
'skipper', // <-- add skipper
],
skipper: require('skipper')({ limit: 1073741824 })
}
};
Here's the link to the documentation.
Just wondering if you have looked at this Sails GitHubIssue
Seems very much related and from what it seems few people have made it work.

Ember app see hash in localhost URL

In my Ember app (based on engines), I do not see hash in the localhost URL
I did try changing locationType in environment.js
locationType: 'hash'
Though the routing & everything is working fine, I am just wondering how do I get the # in the address bar URL.
Below is my complete environment.js
/*jshint node:true*/
'use strict';
module.exports = function(environment, appConfig) {
console.log(environment);
var ENV = {
modulePrefix: 'myapp-ui',
environment: environment,
rootURL: '/myapp/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
TRACKING_ENABLED: true,
LOG_TRACKING_ENABLED: false,
ROUTE_TRANSITION_TRACKING_ENABLED: false,
LOG_ERROR_TRACKING: true,
ANALYTICS_URL:"X",
ANALYTICS_SITE_ID:0,
STUB_MODE : false,
SET_LOCALE : true
};
if (environment && environment !== 'development') {
ENV.rootURL = "";
}
return ENV;
};
Update your config/environment.js's locationType config option to hash and restart your Ember server.
locationType: 'hash', // inside ENV
Quote from Ember guies,
You can change this option in config/environment.js under ENV.locationType.
https://guides.emberjs.com/v2.2.0/configuring-ember/specifying-url-type/
In your 'Router.js' file in the root of your app, you add these lines of code:
Router.reopen({
location: 'hash'
});
More info on hash here: HASHLOCATION ember
Then go to localhost:4200/#/

Meteor upgrade issue: forgotPwd route configured but showForgotPasswordLink set to false

I am facing issue with my meteor project after upgrading 1.0 to 1.2.1. The issue says forgotPwd route configured but showForgotPasswordLink set to false. But the value of showForgotPasswordLink is true itself when i checked in AccountsTemplates.configure(packages\telescope-core\lib\config.js).
Anybody have idea on this issue?
Thanks in advance
I assume you have the following code in your Telescope/packages/telescope-core/lib/config.js file:
//Routes
AccountsTemplates.configureRoute('signIn');
AccountsTemplates.configureRoute('signUp', {
path: '/register'
});
AccountsTemplates.configureRoute('forgotPwd');
AccountsTemplates.configureRoute('resetPwd');
AccountsTemplates.configureRoute('changePwd');
//AccountsTemplates.configureRoute('enrollAccount');
//AccountsTemplates.configureRoute('verifyEmail');
// Options
AccountsTemplates.configure({
enablePasswordChange: true,
showForgotPasswordLink: true,
confirmPassword: false,
overrideLoginErrors: true,
lowercaseUsername: true,
negativeFeedback: false,
positiveFeedback: false,
negativeValidation: true,
positiveValidation: true
});
You receive the error forgotPwd route configured but showForgotPasswordLink set to false because the execution order is wrong.
From the Iron Router add-on for User Accounts documentation:
NOTE: some routes need other useraccounts' regular options to be set
in advance. Please make sure to have your calls to
AccountsTemplates.configureRoute be executed after your calls to the
regular AccountsTemplates.configure
As a result, you need to place your AccountsTemplates.configureRoute after AccountsTemplates.configure.
// Options
AccountsTemplates.configure({
enablePasswordChange: true,
showForgotPasswordLink: true,
confirmPassword: false,
overrideLoginErrors: true,
lowercaseUsername: true,
negativeFeedback: false,
positiveFeedback: false,
negativeValidation: true,
positiveValidation: true
});
//Routes
AccountsTemplates.configureRoute('signIn');
AccountsTemplates.configureRoute('signUp', {
path: '/register'
});
AccountsTemplates.configureRoute('forgotPwd');
AccountsTemplates.configureRoute('resetPwd');
AccountsTemplates.configureRoute('changePwd');
//AccountsTemplates.configureRoute('enrollAccount');
//AccountsTemplates.configureRoute('verifyEmail');

Categories