Node.js + Express + i18next how manage two languages same time - javascript

in my Node.js + Express + i18next app I would like to keep separate frontend and backend languages. I already managed to keep separate the login session data, so that I can login as normal user in the frontend and as administrator in the backend at the same time and
independently:
const express = require('express');
const session = require('express-session');
const app = express();
...
app
.use('/admin', session({
...
cookie: {
path: '/admin',
},
name: 'adminSessionID',
...
}))
.use('/', session({
...
cookie: {
path: '/',
},
name: 'sessionID',
...
Now I need to do the same with i18next and languages. What can I do? I tried creating 2 i18next instances but the cookie created is always only the last one defined and, even worst, if I change language via query string, it changes both in front and backend...
Any advice could be usefull, thank you

Related

How can I setup an OpenID Connect authentication with Node Js?

here is the thing. I have my app that has separated back-end and front-end into two different project (back-end with Node-JS, and front-end with Vue-JS). I got a home page with a button that should redirect the user to the authentication server to log in.
So i made an "on-click" function in my homePage.vue that will consume a function from my api.
I've read a lot of documentation and seen some examples. But to be honest, during those past weeks, even if I tried, I still do understand nothing about how authentication works.
You can see below the js file i wrote inspired by examples that i found:
auth.js
const express = require('express');
const { auth } = require('express-openid-connect');
const app = express();
app.use(
auth({
issuerBaseURL: 'myDomainUrl',
baseURL: 'http://localhost:8080',
clientID: 'myClient_ID',
secret: 'aaaaaaaaaaaaaaaaaaaa',
idpLogout: true,
authRequired: false,
})
);
module.exports = app;
There is also the route with the function that I try to implement:
auth.route.js
module.exports = app => {
var router = require("express").Router();
router.get('', location.replace('myDomainUrl'));
app.use('/api/login', router);
};
I don't know if it's important but my back-end runs on the port 4000 and my front-end runs on the port 8080.
If someone can explain me how I can do to make my authentication work and what I have to change, it would be great.
Thanks you in advance, I hope I was clear enough about my problem. If not, do not hesitate to ask me what was not clear.

How to use socket.io across diffrent routes in node.js

I have different routes in my node js application and i have to use socket.io in every route to make my node and react js application realtime. But, i have the below structure of my node js application.
router.js
const express = require('express');
const router = express.Router();
const worksheetController = require('../controllers/worksheet')
const attendenceController = require('../controllers/attendence')
router.route('/worksheets')
.get(
worksheetController.getWorksheet
)
.post(
worksheetController.validateWorksheet,
worksheetController.addWorksheet,
attendenceController.markAttendence
)
router.route('/attendances')
.get(
attendenceController.getAttendance
)
module.exports = router;
server.js
const express = require('express');
const router = require('./router');
const app = express();
app.use('/api', router);
app.listen('5000', () => {
console.log('Listening on port');
});
module.exports = app;
So, I want to know
1) Should i need to use http module to create a server, if i need to use socket.io.
2) How can i use socket.io for diffrent routes.
I found posts that match's to my question on stackoverflow, which is this, this and this. But i don't think, that works for me. So please help me.
You can use http module or other module in document of socket.io for to use socket.io
I don't sure your idea. But when you want implement socket.io. I think you should run another node app. (Meaning you have 2 nodejs app. 1 for node http normally and 1 for socket.io app). After you can use path option when init socket.io app https://socket.io/docs/server-api/#new-Server-httpServer-options. Because when you deploy to production. You should run your socket.io app with beside of proxy serve (ex: nginx). Socket.io basically support multi transport and protocol. So if use with http restful. How about config your connection mapping from nginx to socket.io app, how you setup error handler ?.
In your case:
+ Create new file socket.js:
// socket.js
var http = require('http')
var socket_io = require('socket.io')
function init_socket(app) {
const server = http.Server(app)
const io = socket_io(server, { path: 'your-path-want-for-socket-io' }) // default: /socket.io/
}
import {init_socket} from 'socket.js'
init_socket(app)

Node.js with firebase does not save info in the Session

I am trying to use session in my app, to keep track on user log-in and more.
But...
When I tried using the simplest way, I kept getting the error :
Warning: connect.session() MemoryStore is not designed for a production environment, as it will leak memory, and will not scale past a single process.
There for, after much searching, I added the firebase-session functionality,
but now, even though I get no error, nothing is saved in the session.
This is my code:
const functions = require('firebase-functions');
const express = require('express');
const session = require('express-session');
const FirebaseStore = require('connect-session-firebase')(session);
const firebase = require('firebase-admin');
const ref = firebase.initializeApp(
functions.config().firebase
);
const app = express();
app.use(session({
store: new FirebaseStore({
database: ref.database()
}),
secret: 'asdfasgbrwewet53hnhwetynsy',
resave: true,
saveUninitialized: true
}));
app.get('/', function(req, res, next) {
console.log(req.session);
req.session.username='rakafa';
res.send('Returning with some text');
});
app.get('/bar', function(req, res, next) {
console.log(req.session);
var someAttribute = req.session.username;
res.send(`This will print the attribute I set earlier: ${someAttribute}`);
});
exports.app = functions.https.onRequest(app);
This is what I did so far:
My original example taht I used to start using session: session-express example
I took the firebase part from npm: npm firebase-session
Tried to use radis-store as a solution, didn't word: using radis-store solution
Using session-store, gave me the same worning as using nothing.. npm session-store
This question gave me the idea of using firebase-session database sessions explanations
I saw this an example with cookies, but didn't understand, and didn't find another example cookie session
Just another word, I only just started learning Node.js, so please try using simple examples, so I would understand ;)
And please forgive my starte's mistakes
Please, HELP....
=== edit ===
According to orxelm's answer, I changed my ref to this:
const ref = firebase.initializeApp({
//admin.credential.cert(serviceAccount)
credential: firebase.credential.applicationDefault(),
databaseURL: "https://*****.firebaseio.com/"
});
But still, when I run the app, there is nothing in the session once I refresh the page.
sessions in the server
^^
I can see that the app created a lot of sessions in the server.
but none of them have the information I added on the app,
and since I use only one browser, there should only one session, am I wrong?
I had this problem, when I was using firebase hosting and functions, but can be solved by simply setting name:"__session" in the session.
app.use(session({
name:"__session,
...
after adding this, saving values in the session like req.session.username='rakafa' worked fine.
Where is you firebase config?
Maybe try to initialize the firebase admin this way:
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

Universal username/password authentication in express.js or react.js

Setting up user authentication can be easily achieved in apache by setting up .htaccess and .htpasswd However I am developing an new web application and I am using express.js or react.js to create a web server. I searched user authentication online but they are long projects for email style logins like here. All I need is a single universal username and password. When a user browse to my website a pop appear for the username and password. (Same like .htaccess style)
As per my understandings you need http server authentication in nodejs.
I know one npm module. link
And it's pretty easy to setup also.
Basic example
// Authentication module.
var auth = require('http-auth');
var basic = auth.basic({
realm: "Simon Area.",
file: __dirname + "/../data/users.htpasswd"
});
// Creating new HTTP server.
http.createServer(basic, (req, res) => {
res.end(`Welcome to private area - ${req.user}!`);
}).listen(1337);
If anyone is interested to do in ES2016 then follow the following code. Set the babel etc to make it work.
import express from 'express';
import auth from 'http-auth';
// Configure basic auth
const basic = auth.basic({
realm: 'SUPER SECRET STUFF'
}, (username, password, callback) => {
callback(username == 'admin' && password == 'password');
});
// Set up express app
const app = express();
// Create middleware that can be used to protect routes with basic auth
const authMiddleware = auth.connect(basic);
// Protected route
app.get('/', authMiddleware, (request, response) => {
response.send('you made it!');
});
app.listen(3000);

Express + Passport + Redis sessions?

To date I have been using the default MemoryStore for my Express sessions. Everything has been working great, except that all session data is lost between restarts. So I am trying to get my sessions working with Redis & Connect-Redis instead.
Here is the part of my code that concerns session config with Redis:
var express = require( "express" ),
app = module.exports = express(),
passport = require( "./passport" ),
http = require( "http" ),
RedisStore = require( "connect-redis" )( express ),
redis = require( "redis" ).createClient();
app.configure(function(){
app.set( "passport", passport );
app.use( express.cookieParser());
app.use( express.session({
secret: "I can haz working sessions?",
store: new RedisStore({ client: redis })
}));
app.use( passport.initialize() );
app.use( passport.session() );
...
When I run this application, there are no errors. However when I try to login, although it performs the initial login, I just keep getting bounced back to the login screen. It is as if passport cannot set a cookie, or cannot read a cookie after it has been set.
For reference, here are the functions I use in passport to serialize / deserialize the session:
passport.serializeUser(function( user, done ) {
done( null, {
id : user.id,
type : user.type,
firstname: user.firstname,
lastname: user.lastname
});
});
passport.deserializeUser(function( user, done ) {
done( null, user );
});
Any advice on where I am going wrong? Do the passport serializeUser / deserializeUser need to be modified to work with redis? Or am I missing something else?
Thanks (in advance) for your help.
One possibility: maybe your app can't connect to Redis? I found that when my redis-server was not running, I experienced the symptom you describe (silently fails to set cookies).
Aside from checking that it's running, make sure your Node server can actually connect to it—that is, that there are no firewall rules keeping you out.
Good luck!

Categories