Nodejs User security - node.js

I want to check if the user accessing the web page is part of a domain.
How can I do this with nodesjs?
Pseudo code like this:
Server.on(request){
if(getDomainOf(user) === 'thisdomain.local') // User is a member of the domain
// Handle request
else
// show error (Access denied)
}

Related

firebase onAuthStateChanged infinite loop node js

I'm using firebase to sign in my users on my node js app. I would like to see if the user is authentificated or not and after it redirect to the page I want (login if it not logged or dashboard).
But when I redirect user (if it not logged previously or session expires) it's looping on the same page (send redirect of the login page everytime when I'm on login page).
My function that I use actually :
function authenficated (req, res, next) {
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log("connected" + " " + user.uid);
next()
} else {
console.log("disconnected")
res.redirect('/') //loop on / page
next()
}
});
}
I would like a function that provides if my user is logged or not, if it logged my node backend return to /dashboard or other pages that I want and if not it cannot access to dashboard and it return automatically to / or /login
I specify I don't use React or Vue, I use simply EJS to display my pages
Thanks for all
This function/sdk is meant for frontend applications and not backend apps. You need to the admin sdk for that. You can use cookies and the admin sdk provides a function to create cookies. After a signin you attach the cookie to the headers and it will be send by the browser on every request. If the cookie header is empty than you know the user isn't signed in. To logout a user you can add a head method to clear the cookie.
To use backend function you need to use the admin sdk. This function is a front end function (web sdk ).
You can use onAuthStateChanged on the front end and redirect them from the front end. Remember onAuthStateChanged will fire on every page load.
OR implement cookies like the previous comments.
OR
Send the id token from the client via http request (fetch or axios) and verify server side using the admin sdk. Here is the specific link. This solution would require you to load something on the front end though and then send a http request to the backend, verify, then send protected resources after.
Cookies on the other hand are sent to the backend with every request, so if no cookie is present on the page load request then obviously there is no user. Or if the below function fails then server wont send protected resources. (this is explained in the link above for cookies)
getAuth().verifySessionCookie(sessionCookie, true /** checkRevoked */)

Stop users from accessing guest pages after login in Laravel 7

Is there any way to stop the users from accessing guest pages after they've logged in? I tried using the guest middleware bt nothing happens. I have two sets of guards: RESTAURANT and CUSTOMERS. Once the customer has logged in I don't want them to access the guest pages before log out.
Route::group(['middleware' => 'guest'], function () {
Route::get('/home', 'HomeController#index')
->name('home'); // This is a guest page
});
My customer pages are protected with a customer guard as well.
Route::name('customer.')->middleware(['auth:customer', 'verified'])
->group(function () {
Route::get('/logout', 'Auth\CustomerLoginController#logout')->name('logout');
});
First, I logged in with the customer guard. After then when I type '/home', the home page is loading. I want to stop logged in users from accessing the guest pages.
Create a middleware and perform following code in it.
if (Auth::user()){
// if user HAS authenticated already,
// redirect him to somewhere or die(),
// or any other appropriate action
}
Apply middleware on route
Route::group(['middleware' => ['guest','middlewareName']], function () {
Route::get('/home', 'HomeController#index')
->name('home'); // This is a guest page
});
It will work
Why not just use the Auth::user() check on a Guest page:
if (Auth::user()){
// if user HAS authenticated already,
// redirect him to somewhere or die(),
// or any other appropriate action
}

Angular 2 (4/5) check if user authenticated, best practices

I am new to Angular and implementing authentication for users.
Most of suggestions on the web propose to save session/username in local storage and when user is back to the app, check local storage in order to display proper navigation (in my navbar I have different nav buttons for private and public views).
However, I found this solution having some drawbacks. For example, if session on server expired, or local storage was manually added, then when app will be initialising, it will show wrong buttons in navbar.
After that I came to solution - to use service before showing navbar buttons, to send request to server to verify if user from local storage with his session is currently active. And only after that I will display nav buttons.
Here comes a question: is it the most efficient way to proof check if user from local storage is logged in and session is active?
There is another way, which I was thinking, but didn't find solution.
Since my angular webapp and nodejs server are located in two different places, is it possible for the webapp to check authentication status (make a request from webapp server to my nodejs server) when index.html is requested and respond with pre-rendered navbar and user status (logged in or not)?
Thanks.
P.S. I am using PassportJS and Express on server side.
The best practise is to use AuthGuard and implement CanActivate to check whether user can view a particular part of the application. Also an authentication service is used normally to let the user login to system and gain an access token.
This access token is then used as Authorisation-Header on each request to server (this is where they will be in sync).
You will need to check for JWT/or any other type token on load which contains user information plus session time out.
If the token is invalid you simply redirect the user to login, otherwise it will allow user to go where they wanted to.
A practical example can be found here.
To have navbar showing different elements for authenticated and non-authenticated users, one of possible solutions will be
To use some "/auth-check" request in authentication.service.ts, which will have trigger every time an event of the result of checking authorisation of current user
...
interface ShareObj { [id: string]: any; }
...
currentUserId: ShareObj = {};
currentUserUsername: ShareObj = {};
public authenticatedBehavior = new ReplaySubject(1);
authCheck(): any {
return this.http.get('/api/auth-check')
.map((resp: any) => {
if (resp.authanticated) {
this.currentUserId['global'] = resp.user.id;
this.currentUserUsername['global'] = resp.user.username;
this.authenticatedBehavior.next(true);
} else {
this.authenticatedBehavior.next(false);
this.currentUserId['global'] = null;
this.currentUserUsername['global'] = null;
}
return resp;
})
.catch(e => {
this.authenticatedBehavior.next(false);
this.currentUserId['global'] = null;
this.currentUserUsername['global'] = null;
});
}
So, in navbar.component.ts there should be a listener for this event:
ngOnInit() {
this.authService.authenticatedBehavior
.subscribe(
data => {
// do change of UI of navbar depending if user logged in or not
}
);
}
To have error-iterceptor.ts file, where you should "catch" all failed requests and check them for Unauthorised response (401). If you catch such response, do authCheck() in authentication.service.ts to make sure that session of current user expired and notify all components which listen for authenticatedBehavior

Firebase: Does the auth.uid stay active across page tabs?

Tools: Firebase 2.3.1
Problem Type : Setting Security Rules for user currently in a session
Authentication Method: authWithPassword()
I know that currently the user is logged into the app in a browser. I set up my rules with the expectation that once a user has opened a session they can access all the room data in any tab on that browser.
Yet if I try fetching this URL below in a different tab in the same browser..
https://myfirebaseurl.firebaseio.com/rooms.json
..I will get back
{
"error" : "Permission denied"
}
Which is weird because that URL is working just fine in my program in any tab I open my app or if I refresh the page
For instance this isn't throwing any errors:
var firebaseRoomsRef = new Firebase("https://myfirebaseurl.firebaseio.com/rooms")//fetch just fine
Here is what the rules look like:
{
"rules": {
"rooms": {
".read": "root.child('users/'+auth.uid).exists()",
}
}
So my main question:
Is the error only happening because I'm trying to call the URL json directly like that? Or is my app doing something differently that is giving it permission to access messages?
A side question:
Firebase is automatically storing "auth" as a token or cookie in my program when I call authWithPassword() successfully right?
Yes, the error is only happening because you're trying to open the URL directly. When you open that URL directly in your browser, there's no auth data sent unless you append an auth query parameter.
https://myfirebaseurl.firebaseio.com/rooms.json?auth=CREDENTIAL
When you authenticate within your app, Firebase is automatically storing auth as a token in localStorage only for the domain hosting that app so that a returning user will retain their session.

Express JS routing based authentication

I have created node js app using express framework.
I have created middleware for restricting access to some routes.
Middleware actually works fine. but i have difficulties in displaying data.
Suppose In My app i have created route for display list of countries('/country/master')i.e html page which is using internally different/default route ('/country/') to get data from mongoDB.
In this case user will not able to see data cause i have not given permission to "/" routes. but i want to display data but not allow him to make use of "/" route to check data.
How can i deal with this case ????
The answer depends on your authentication strategy i.e. are you using session identifiers, access tokens, etc.
In either case I suggest that you break out the credential exchange (aka login) from the authentication. They should be separate middleware functions. Below is an example of what this looks like.
While this answers your question, specific to ExpressJS, it does leave out a lot of other details that matter when you are building an authentication system (like how to securely store passwords). I work at Stormpath, we provide user management as an API so that you don't have to worry about all the security details! It's very easy to integrate our API into your application, using the express-stormpath module. You'll have a fully featured user database in minutes, without having to setup mongo or a user table.
All that said, here's the example:
/* pseudo example of building your own authentication middleware */
function usernamePasswordExchange(req,res,next){
var username = req.body.username;
var password = req.body.password;
callToAuthService(username,password,function(err,user){
if(err){
next(err); // bad password, user doesn’t exist, etc
}else{
/*
this part depends on your application. do you use
sessions or access tokens? you need to send the user
something that they can use for authentication on
subsequent requests
*/
res.end(/* send something */);
}
});
}
function authenticate(req,res,next){
/*
read the cookie, access token, etc.
verify that it is legit and then find
the user that it’s associated with
*/
validateRequestAndGetUser(req,function(err,user){
if(err){
next(err); // session expired, tampered, revoked
}else{
req.user = user;
next();
}
});
}
app.post('/login',usernamePasswordExchange);
app.get('/protected-resource',authenticate,function(req,res,next){
/*
If we are here we know the user is authenticated and we
can know who the user is by referencing req.user
*/
});
You can positioning of middleware in you app.for example:-
app.get('/country/master',function(req,res){
})
app.use(function(req,res){
your middle ware for providing authentication
})
// other routes where authentication should be enabled
app.get('other urls')

Resources