How to get current logged in user in react js - javascript

just wondering how to access the data of a logged in authenticated user in a react js file with node js.
In the handlebar files I have I can see information like this:
{{#if user}}
I would like to know how to do things like that in a react js file so I can assign the name of the logged in user to a js variable. Something like
var name = {{# user.name }};
Thanks in advance and sorry if I've missed something out or said something a tad dense.

First of all you need to use a method for authentication, JWT is a good bet to do so. then in your main component (app.js) send a request to a specific route (like /auth/init) to check if the user is logged (means jwt is set).
you can approach this using middlewares if you are using express.js. if the user was logged in then send the user's credentials back to the client (react) and initialize your user state with the response.
To share user state between your components you have different options. based on your needs you can choose from redux, contextAPI, or just newly introduced API hooks. read this for further perspective.

Related

Angluar modfifying localStorage data to add Roles

I want to implement simple authentication and authorization in an Angular project. I want to store a JWT token, and the logged in Users data, including Roles in the Local Storage. A routing guard service would check if the currentUser in the localStorage has the Roles required for the given route.
My problem is that if the user modifies the localStorageData, he could do some things otherwise he couldn't do. I understand that he can't make any valid requests to the server, because the sent token wasn't modified.
What's the solution for this?
Example:
https://stackblitz.com/edit/angular-7-role-based-authorization-example
Instructions:
Login with: Username: user Paswword: user
Execute in
console:localStorage.setItem("currentUser",'{"id":2,"username":"user","firstName":"Normal","lastName":"User","role":"Admin","token":"fake-jwt-token.User"}')
Refresh page
You can't prevent the client from doing whatever it wants with respect to itself. As long as your server is protected that's all you can do.

Accessing react components directly from URL

I am trying to create an new react app. I have 3 components: app (with login functionality) , admin and client.
How can I render (redirect to) admin / client based on a value (user role) , after successfully login?
Is this any way to access the admin / client components directly from the URL? More specific, localhost:3000 takes me to App.js (witch makes sense, because it is defined like this in index.js). If I want to see directly the admin component (hijacking the login), can I use for example localhost:3000/admin ? how can I do that?
Thank you !
You can use react router and in particular route.push('/admin')
You need to define the '/admin' route and voilĂ .
To bypass the login, you may want to make a 'test-admin' route and a private 'admin' route. Here is how to make a private route if you happen to need it:
https://dev.to/karanpratapsingh/private-public-and-restricted-routes-in-react-42ff
You can use react-router, that allow to define some route based on URL.
When you have a login feature, then you would probably wants to have some protected route, that are only accessible when you are logged in.
Then I recommend you to read this article

Restrict access to the authentified user

I'm creating my first application using Laravel and React.
I followed a tutorial online, and I noticed that the authentification, unlike what I was used to with only Laravel, is using localStorage instead of Auth::user.
With the following line I can get the informations of the authentified user :
const user = JSON.parse(localStorage.getItem("userData"));
I can access the info of the logged user like this :
{user.id}{user.name}{user.email}
Now in my application, each profile belong to a user.
Using react and react-routes, to access a profile, the user need to provide idof the profile in the addition of the url, like this :
<Route path="/customize/:id?" component={Home} />
The current problem is that any user can view any profil. I want to limit the privilege to see/modify the profiles to ONLY those who are related to the profiles. So when the user is logged, he can only manage his own profiles, or perhaps the profiles that have the sameuser_id as his id.
I searched and I found that I have to use Middlewares I think to manage the access, but I'm not entirely sure.
You're right, you should use a middleware to verify the user is authenticated.
I don't know which way you're using to authenticate a user.
Basically if you're using laravel built in authentication you should be able to use the default auth middleware as described here: https://laravel.com/docs/8.x/authentication#protecting-routes
Otherwise you may need to create a new middleware to handle the verification, the process of making a new middleware is described here: https://laravel.com/docs/8.x/middleware
Then you can use the middleware method on the routes you'd like to protect
Route::get('/customize/{id}', function () {
// Only authenticated users may access this route...
})->middleware('auth');
Another solution I would not recommend for this use is doing a simple Auth::check() in your controller's function

Storing sensitive data in Vuex

To summarize, we are using Vue on the front-end and Hapi JS on the back-end. The front end uses MSAL.js to authenticate users and then passes an access token to the back-end. The access token is decoded with hapi-auth-jwt2 and the validate() function returns { isValid: true, credentials : { ps_ref: 12345, md_userid: asfasgsg#5874.com }}. This object is then passed to the handler function of a route which extracts authentication groups/user roles (i.e.Auids) from our DB and user data and returns that.
Imagine that the user object looks like this:
{
Auids: (4) ["user", "webadmin", "accounts"]
md_clock: 5678
md_picture: "./images/"
ps_fname1: "Test Name"
ps_surname: "Test Surname"
psname: "Test Name Test Surname"
psref: 125125
}
Now, we would like to store this object in Vuex, however, we are concerned that it will be visible to anybody who has installed the Vue Devtools in their browser or anybody who executes something like rootElementOfApp.__vue__.$store
Our questions are:
How easy it is for somebody to access the Vuex in production?
If it is easy enough to access Vuex by the public, is Vuex the best way to store this object? If we go for Vuex should we encode the user object or at least the Auids in it ?
Everything you store in the js/html/cookies is not save on it's own. But it is all related how you will manage it. Basically you can store almost everything in the front end, as long it isn't sensitive data that's usable for ethical hacking. Things like addresses, contract numbers, bank accounts etc.
Data like userIds (as long only used for programmatic reasons) or a user roles can be stored in the front end. But if you do it right you always have every client side validation also in your back-end application.
In terms of dev tools of vue they are only available in development mode not production. But a good hacker doesn't mind.

Multiple Users Issues Node.js

I am working on a budgeting application and everything works great... or at least i thought it did. Test it out at http://budgeter.pattmorter.webfactional.com/! Now you can login and add stuff and edit your profile and it works great, the only problem is that if someone else logs in after you, and you refresh your page, it'll set your session to the person that logged in after you.
I'm not really sure why it happened but it has to do with my main app.js node. I think my problem is that when the user logs in i have a currentUser variable in app.js which is passed too all of the different routing but I don't think that is correct because it is causing these errors. Anyone suggest a better way of doing this?
My app.js file is here -- https://github.com/M-Porter/bearded-wookie/blob/master/production/app.js
Basically, I don't understand how to do what i want without a variable in the app.js space. Any push in the right direction would be great.
Node.js in Action (great book) suggests using built in session middleware for things like this. It uses signed cookies so you will also need the cookieParser middleware. It should look something like:
app.use(express.cookieParser('your secret'));
app.use(express.session());
Then you have access to req.session to keep track of your current user.
Edit 1: I just looked at your code more closely. Looks like you were already on track with cookieParser and session middleware. Just try storing your current user in session. It also sounds like passport can retrieve the username on subsequent request. Check out http://passportjs.org/guide/configure/

Categories

Resources