Am I looking for help about i118 express node.js? - node.js

When i choose some language, i get error message . that err msg is .translation is not defined.
example :
http://localhost:5000/?clang=en
Can I achieve my goal with just these 23 files or do I have to use other methods as well?
my app.js code is
// Imports
const express = require('express')
const expressLayouts = require('express-ejs-layouts')
const app = express()
const port = 5000
// import Router file
var session = require('express-session');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var i18n=require("i18n-express"); // <-- require the module
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
app.use(i18n({
translationsPath: path.join(__dirname, 'i18n'), // <--- use here. Specify translations files path.
siteLangs: ["es", "en", "de", "ru", "it"],
textsVarName: 'translation'
}));
// Static Files
app.use(express.static('public'))
app.use('/css', express.static(__dirname + 'public/css'))
app.use('/images', express.static(__dirname + 'public/images'))
// Set Templating Engine
app.use(expressLayouts)
app.set('layout', './layouts/full-width')
app.set('view engine', 'ejs')
// Routes
app.get('', (req, res) => {
res.render('index', { title: 'Home Page'})
})
app.get('/about', (req, res) => {
res.render('about', { title: 'About Page', layout: './layouts/sidebar' })
})
// Listen on Port 5000
app.listen(port, () => console.info(`App listening on port ${port}`))
and my i have follow json file

look at my codes
import i18nMiddleware from "i18next-express-middleware";
import { default as i18n } from "i18next";
import Backend from "i18next-node-fs-backend";
i18n
.use(Backend)
.use(LanguageDetector)
.init({
lng: "en",
whitelist: ["en", "fa"],
fallbackLng: "en",
// have a common namespace used around the full app
ns: ["translation"],
debug: false,
backend: {
loadPath: path.join(__dirname + "/locales/{{lng}}/{{ns}}.json")
// jsonIndent: 2
},
preload: ["en", "fa"]
});
this.app.use(i18nMiddleware.handle(i18n));
path locals/en/translate.js
{
"api": {
"events": {
"email": "email",
"fileMimiType": "File mimi type is not allowed",
"fileSize": "File size Can not greater then "
}
}
call it
i18n.t('api.events.email')

Related

How to enable policy enforcing in keycloak for node.js application?

I have to integrate node.js application with keycloak.The application is in express.But the policies are not enforcing.It grants permission for all the users to access all the api.
For /test api:
Only users with 'chief' role has the access.I have given those policies in keycloak admin console.But those are not reflecting.Why?
User without 'chief' role is also accessing /test
app.js:
'use strict';
const Keycloak = require('keycloak-connect');
const express = require('express');
const session = require('express-session');
const expressHbs = require('express-handlebars');
const app = express();
app.engine('hbs', expressHbs({extname:'hbs',
defaultLayout:'layout.hbs',
relativeTo: __dirname}));
app.set('view engine', 'hbs');
var memoryStore = new session.MemoryStore();
var keycloak = new Keycloak({ store: memoryStore });
app.use(session({
secret:'thisShouldBeLongAndSecret',
resave: false,
saveUninitialized: true,
store: memoryStore
}));
app.use(keycloak.middleware());
app.get('/*', keycloak.protect('user'), function(req, res){
res.send("User has base permission");
});
app.get('/test', keycloak.protect(), function(req, res){
res.send("access granted");
});
app.get('/',function(req,res){
res.send("hello world");
});
app.use( keycloak.middleware( { logout: '/'} ));
app.listen(3000, function () {
console.log('Listening at http://localhost:3000');
});
keycloak.json:
{
"realm": "nodejs-example",
"auth-server-url": "http://localhost:8180/auth",
"ssl-required": "external",
"resource": "nodejs-connect",
"credentials": {
"secret": "451317a2-09a1-48b8-b036-e578051687dd"
},
"use-resource-role-mappings": true,
"confidential-port": 0,
"policy-enforcer": {
"enforcement-mode":"PERMISSIVE",
}
}
You have enforcement-mode in your keycloak.json set to PERMISSIVE, this should be ENCFORCE I believe.
Add the following line in json
"verify-token-audience": true
var Keycloak = require('keycloak-connect');
var hogan = require('hogan-express');
var express = require('express');
var session = require('express-session');
const app = express();
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
app.set('view engine', 'html');
app.set('views', require('path').join(__dirname, '/view'));
app.engine('html', hogan);
var memoryStore = new session.MemoryStore();
var keycloak = new Keycloak({
store: memoryStore });
// session
app.use(session({
secret:'thisShouldBeLongAndSecret',
resave: false,
saveUninitialized: true,
store: memoryStore
}));
app.use(keycloak.middleware({
admin: '/',
protected: '/protected/resourcea'
}));
app.get('/leads/assign',keycloak.enforcer(['leads:assign'],{
claims: function(request){
return {
"location":["chennai"]
}
}
} ), function (req, res) {
res.send("granted");
});

How to render route before rendering static files in node js?

I want to render app.use('/', callback function) before rendering the static files from public folder.
Basically I am doing the authentication before accessing the website, so once it gets authenticated it should load the index.html (static file) from the public folder.
How should i do it?
I am using W3ID from IBM to authenticate the site.
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const WebAppStrategy = require("ibmcloud-appid").WebAppStrategy;
const CALLBACK_URL = "public/index.html";
var path = require('path');
var bodyParser = require('body-parser');
var port = process.env.VCAP_APP_PORT || 8080;
var mongoose = require('mongoose');
//var MongoStore = require('connect-mongo')(session);
const app = express();
// mongodb connection
mongoose.connect("mongodb://admin:admin123#ds261430.mlab.com:61430/events");
var db = mongoose.connection;
// mongo error
db.on('error', console.error.bind(console, 'connection error:'));
// parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
// Set view engine as EJS
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// include routes
app.use(session({
secret: "123456",
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new WebAppStrategy({
tenantId: "73585f35-8d9c-4f6f-9ab2-d07ca0c1d371",
clientId: "863fce57-a717-4586-b8a2-0bf221ef4e68",
secret: "MzkxMTMxMWMtNmYxNi00ZjNhLWFiNzctZjFlM2NkMDM1ZTkz",
oauthServerUrl: "https://appid-oauth.eu-gb.bluemix.net/oauth/v3/73585f35-8d9c-4f6f-9ab2-d07ca0c1d371",
redirectUri: "https://csi.eu-gb.mybluemix.net/" + CALLBACK_URL
}));
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
app.get(CALLBACK_URL, passport.authenticate(WebAppStrategy.STRATEGY_NAME));
app.use('/',passport.authenticate(WebAppStrategy.STRATEGY_NAME), function(req, res) {`enter code here`
// do your authentication
});
// listen on port 8080
app.listen(port);
You can do this by just putting your app.use('/',...) above the app.use('/',express.static('...')).
Or
You can do this by passing option {index:false} to express.static like
app.use('/',express.static('path here',{index:false}));
This option will set express.static to not send the index.html by default.

Using i18n with hbs and express

I am trying to properly use i18n with hbs, but haven't had any success.
Here is my server.js code:
var express = require('express');
var server = express();
var hbs = require('hbs');
var i18n = require('i18n');
var cookieParser = require('cookie-parser');
i18n.configure({
locales: ['en', 'fr'],
cookie: 'locale',
directory: __dirname + "/locales"
});
hbs.registerPartials(__dirname + '/views');
server.set('view engine', 'hbs');
server.engine('hbs', hbs.__express);
server.use(cookieParser());
server.use(i18n.init);
hbs.registerHelper('__', function () {
return i18n.__.apply(this, arguments);
});
hbs.registerHelper('__n', function () {
return i18n.__n.apply(this, arguments);
});
server.get('/', function(req, res) {
res.render('index');
});
And my HTML code :
<ul class="nav navbar-nav navbar-right">
<li>{{__ 'HOME'}}</li>
<li>{{__ 'TEAM'}}</li>
<li>{{__ 'SERVICES'}}</li>
<li>{{{__ 'LEL'}}}</li>
</ul>
And one of my Json files :
{
"HOME": "HOME",
"TEAM": "TEAM",
"SERVICES": "SERVICES",
"LEL": "CONTACT"
}
I can't see what I am doing wrong, if someone could help me bit it would be really helpful! Thank you!
Edit : It seems that my helpers are recognized, but i18n is not translating words..
Édit : Ok I changed my template engine and it worked !
I did it like this
const express = require('express');
const path = require('path');
const handlebars = require('handlebars');
const app = express();
const i18n = require('i18n');
// Language
i18n.configure({
locales: ['es', 'en'],
directory: path.join(__dirname, 'locales'),
defaultLocale: 'es',
queryParameter: 'lang',
});
app.engine('.hbs', exphbs({
defaultLayout: 'index',
layoutsDir: path.join(app.get('views'), 'layouts'),
partialsDir: path.join(app.get('views'), 'partials'),
extname: '.hbs',
handlebars: allowInsecurePrototypeAccess(handlebars),
helpers: {
i18n: function(){
return i18n.__.apply(this,arguments);
},
__n: function(){
return i18n.__n.apply(this, arguments);
},
}
}));
app.set('view engine', 'hbs');
app.use(i18n.init);
and in any .hbs file
<h1>{{i18n 'Hello'}}<h1>

express.io with express router returns error

When I try to emit the 'ready' event from client on express.io, it shows an error that
{ route: [Function], broadcast: [Function] } 'req.io.route'
TypeError: Object # has no method 'ready
I am using express version express#4.12.4.
app.js is as shown below
var routes = require('./routes/index');
var users = require('./routes/users');
var app = require('express.io')();
app.http().io();
//var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
and the index.js file is as below
app = require('express.io')()
app.http().io()
var router = app.Router();
/* GET home page. */
router.all('/', function(req, res, next) {
res.render('index', { title: 'Express' });
req.io.route('ready', function(res) {
console.log('tested..........');
})
});
module.exports = router;
client side code is as below
<script>
var socket;
$(document).ready(function(){
socket=io.connect(window.location.hostname);
socket.emit('ready');
});
</script>
</html>
please help me regarding this...
The router isn't a method on the return value of the constructor, it's exported with the module.
var express = require('express.io');
var app = express();
app.http().io()
var router = express.Router();
Also app.http().io() only needs to be called once, so remove it from your routes file.
Try
/* GET home page. */
router.all('/', function(req, res, next) {
app.io.route('ready', function(res) { //not req.io...
console.log('tested..........');
})
res.render('index', { title: 'Express' });
});

Node.js + express: specify routes

In my understanding, the way to serve views is to do the following:
app.set('view engine', 'ejs'); // or jade or whatever
app.set('views', __dirname + '/views'); // specify where to find the view files e.g. index.ejs
app.get("/", function(req, res) { res.render('index') });
However, when I check the code here https://github.com/jedireza/drywall/ , which is a boilerplate for node user management, I don't see any routes defined in app.js. But it works fine and if I type the url /signup in browser it will render signup.jade.
Which part, or which middleware is doing the magic of routing?
app.js content:
'use strict';
//dependencies
var config = require('./config'),
express = require('express'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
mongoStore = require('connect-mongo')(session),
http = require('http'),
path = require('path'),
passport = require('passport'),
mongoose = require('mongoose'),
helmet = require('helmet'),
csrf = require('csurf');
//create express app
var app = express();
//keep reference to config
app.config = config;
//setup the web server
app.server = http.createServer(app);
//setup mongoose
app.db = mongoose.createConnection(config.mongodb.uri);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function () {
//and... we have a data store
});
//config data models
require('./models')(app, mongoose);
//settings
app.disable('x-powered-by');
app.set('port', config.port);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//middleware
app.use(require('morgan')('dev'));
app.use(require('compression')());
app.use(require('serve-static')(path.join(__dirname, 'public')));
app.use(require('method-override')());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.cryptoKey));
app.use(session({
resave: true,
saveUninitialized: true,
secret: config.cryptoKey,
store: new mongoStore({ url: config.mongodb.uri })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(csrf({ cookie: { signed: true } }));
helmet(app);
//response locals
app.use(function(req, res, next) {
res.cookie('_csrfToken', req.csrfToken());
res.locals.user = {};
res.locals.user.defaultReturnUrl = req.user && req.user.defaultReturnUrl();
res.locals.user.username = req.user && req.user.username;
next();
});
//global locals
app.locals.projectName = app.config.projectName;
app.locals.copyrightYear = new Date().getFullYear();
app.locals.copyrightName = app.config.companyName;
app.locals.cacheBreaker = 'br34k-01';
//setup passport
require('./passport')(app, passport);
//setup routes
require('./routes')(app, passport);
//custom (friendly) error handler
app.use(require('./views/http/index').http500);
//setup utilities
app.utility = {};
app.utility.sendmail = require('./util/sendmail');
app.utility.slugify = require('./util/slugify');
app.utility.workflow = require('./util/workflow');
//listen up
app.server.listen(app.config.port, function(){
//and... we're live
});
The routes are being added here:
//setup routes
require('./routes')(app, passport);

Resources