How do i set a cookie on different node js routes? - javascript

I'm developing a user based project, using node ( express, mongoose etc. )
I currently use JWT and the token has the user id in it, I know how to send a cookie when someone logs in, but I don't know how to make the cookie work on all routes, like basically when a user is logged in and goes on route /test the cookie is still there.
I think what I'm trying to achieve is called "session/cookie based authentication", could be wrong idk.

Once you set a cookie, from within any route, with
const myCookieValue = 'whatever'
res.cookie('myCookieName', myCookieValue, {
maxAge: 3600*1000, /* one hour */
httpOnly: true
})
you can retrieve its value, from within any route, with
const myCookieValue = req.cookies.myCookieName || 'yo! no cookie! something is wrong!'
The cookie-parser package makes this possible, handling the gnarliness of the the HTTP header for you.

Related

How to prevent feathers.js from returning all users in the users route

I have been using feathers.js for sometime now and there's something I can't find after looking around. How do you prevent authenticated users from seeing all the users?
when I do a GET with postman on my /users route, if I'm authenticated, I will receive all the users registered on the app. How do I prevent this. I have tried returning my own custom responses, but this seems to block the /authentication route.
Any help will be appreciated as feathers is really nice to work with.
Currently feathers-authentication-hooks is the best way to limit queries, most commonly used to associate the current user. So in order to limit all requests to the currently authenticated user you would do this:
const { authenticate } = require('#feathersjs/authentication');
const { setField } = require('feathers-authentication-hooks');
app.service('users').hooks({
before: {
all: [
authenticate('jwt'),
setField({
from: 'params.user.id',
as: 'params.query.id'
})
]
}
})
You can use limit and skip parameters. So when you do the FIND (GET) request, send also limit: 5, skip: 0. This is a way to do a pagination in feathersjs.
You can check it here: https://docs.feathersjs.com/api/databases/common.html#pagination
Or, if you want to set default values for pagination of the certain service, you can do it in the initialization phase, like this:
app.use('/users', service({
paginate: {
default: 5,
max: 25
}
}));

Keep user logged in in app even after the app closed using Async Storage

I am trying to maintain a user as logged in, in an app even after the app closed, which means the user will no longer need to re-enter his/her userID and password again everytime he/she opens the app.
I want to achieve this using AsyncStorage (other than redux), my question is: is it possible to do so using AsyncStorage? I found sources online on how to persist data using Async but U could not connect those with what I wanted to do.
You should do it this way:
User opens the app, may be do this in you splash screen's didMount i prefer these kind of things to be done before hand in the splashsreen only. Check a flag in AsyncStorage say isLoggedIn if thats true, fetch
user credentials from the AsyncStorage and fed them to your login
request and the rest of the app flow continues.
If isLoggedIn is false (or null), show login screen to the user and upon successful login, save the credentials to AsyncStorage and on success must save the isLoggedIn flag to true and rest of the app flow continues.
For point 1, the code should look like:
AsyncStorage.getItem('isLoggedIn').then((value) => {
if(value && value === 'YES') {
//hit login api using the saved credentials and take user inside the application.
} else {
//Take user to login page and progress with point 2.
}
});
and below is the code that should work for point 2 upon success of login.
const encrypted_username = myFancyEncrptionFunction(username);
const encrypted_password = myFancyEncrptionFunction(username);
AsyncStorage.setItem('username', encrypted_username).then(()=>{
AsyncStorage.setItem('password', encrypted_username).then(()=>{
AsyncStorage.setItem('isLoggedIn', 'YES');
});
});
Its totally upto you how you want your user's credentials to be saved in AsyncStorage i.e. with or without encryption. But its always recommended to keep such things encrypted.

Session cookies not working in Electron

I'm looking at implementing a login system in an Electron[0] application which I'm building but getting stuck on the part of handling the session. Basically I want to store the users session so it is persisted between application restarts (if "Remember me" is enabled).
I have to make use of an existing back-end which works with cookie authentication and I'm not able to change anything there.
From the Electron documentation on the Session object[1] I gathered that I should be using a partition like f.e. persist:someName in order to have a persistent storage, but this is not persisted between application restarts as it seems.
The way I currently set the cookie is as follows:
// main-process/login.js
const session = require('electron').session;
const currentSession = session.fromPartition('persist:someName').cookies;
currentSession.set({
name: 'myCookie',
url: 'https://www.example.com',
value: 'loggedin=1',
expirationDate: 1531036000
}, function(error) {
console.log('Cookie set');
if (error) {
console.dir(error);
}
});
After running this, I see the Cookie set output, but when restarting the app and running the following code:
// main.js
const session = require('electron').session;
const currentSession = session.fromPartition('persist:someName').cookies;
currentSession.get({}, function(error, cookies) {
console.dir(cookies);
if (error) {
console.dir(error);
}
});
The output returned is [].
Any pointers as to what I'm doing wrong or need to do differently would be highly appreciated!
[0] http://electron.atom.io
[1] http://electron.atom.io/docs/api/session/
An alternative might be to take a look at electron-json-storage. Using this plugin, you can write JSON to a system file throughout the user experience and then recall that file on the application load to replace the user "state".

Node & Express + jQuery: After authenticating save for session

I managed to make the user able to authenticate using name/pass. What I'm trying to achieve is, a disabled dropdown, when he authenticates, it gets enabled, then he can access files through the dropdown list. All of that I managed to make, one thing I'm puzzled with is how can I check if he already authenticated or not? So no one would inspect the html code and get access to the files.
I need a way to identify if a client (jQuery) has authenticated or not, something like session variables that ends with closing the page.
EDIT: I need it to be secured, I want to store a boolean that will allow the client to view all the log files.
Store this boolean in an Express session, and select which page to send to the client.
// enable session support
app.use(express.cookieParser());
app.use(express.session({
secret: 'secret key for signed cookies'
}));
app.get('/foo', function(req, res) {
req.session.authenticated = true;
});
app.get('/bar', function(req, res) {
if (req.session.authenticated) {
// send page with files
} else {
// send page without files
}
});

Firebase & Backbone: Application Authentication

Currently I'm building an application using firebase and backbone.marionette and I'm trying to implement secure sessions. Previously, I was able to simply bypass the login page by typing in a specific route in the URL bar, but to fix this I added an initializer to the app to check if a user is logged in or not, like so:
#addInitializer((options) =>
# Instantiate firebase
#firebase = new Firebase("https://*******.firebaseIO.com/")
#authClient = new FirebaseAuthClient #firebase,
(error, user) =>
if (error)
console.log(error)
else if (user)
console.log('User ID: ' + user.id + ', Provider: ' + user.provider)
#logged = true
#trigger('logged_in')
#router.navigate('home', {trigger: true})
else
#logged = false
#trigger('logged_out')
#router.navigate('login', {trigger: true})
)
And now before I render a page in routes.coffee I check if #logged is true or not.
But I feel like this is sketchy security at best. Couldn't someone just fire up the console and set the flag to true themselves?
Does anyone know the proper way to do sessions with backbone and firebase?
There's fundamentally no way to guarantee security on the client side. A smart hacker can always get around any restrictions you place on the GUI (such as setting #logged to true).
Instead, you need to set up security rules on the Firebase side so that non-authenticated users can't change data they're not supposed. This way, even if a hacker messes with your GUI they can't actually access or change anything they're not supposed to.
There's an overview of Firebase auth and security rules here:
https://www.firebase.com/docs/security-quickstart.html

Categories