Does React block users from finding components behind login? - javascript

I'm new to React and am working on an app that requires user authentication. I have my authentication working fine, basically with redux keeping track of an isSignedIn piece of state, which defaults to false. If false, the user is shown a login form, and if true, the user is shown whatever else they need to see. The login form uses axios to send a post to a server-side authentication script, which responds with a JSON object that includes whether the user is valid or not, and the reducer sets isSignedIn accordingly.
I'm curious though, since the entire app is client-side javascript, can't a nefarious user somehow un-pack the script and modify it locally so they can see the components that normally don't render unless logged in?
Some relevant code snippets from the main App component...
render:
render(){
return (
<div className="ui container">
{
this.props.isSignedIn &&
<Navigation pathname={this.props.pathname} />
}
{
!this.props.isSignedIn &&
<Login />
}
</div>
);
}
mapStateToProps:
const mapStateToProps = (state) => {
return {
isSignedIn: state.isSignedIn
};
};

Related

React - correct way to wait for page load?

In React JS, what is the correct way to wait for a page to load before firing any code?
Scenario:
A login service authenticates a user then redirects them (with a cookie), to a React App.
The React App then straight away searches for a cookie and validates it against an endpoint.
But the problem I am getting is when user is authenticated at login service, then forwarded to React App, the App is loading so quick before cookie is even loaded.
What is the right way to fire the code? I tried wrapping in a componentDidMount(), didnt work!
I would suggest you to use a state in the Main component of your application (usually App.jsx) which will control loading. When you start the app the state will be true and only after checking all you need to check it will beacome false. If state is loading you will show a spinner or whatever you want and when it is not loading, the website:
class App extends Component {
constructor(props) {
super(props);
this.state = { loading: true }
}
componentDidMount () {
checkToken()
.then(() => this.setState({ loading: false });
}
if (loading) {
return <Spinner /> // or whatever you want to show if the app is loading
}
return (
...rest of you app
)
}
If any doubt just let me know.
you can use Suspense and lazy :)
import React, { Suspense } from 'react';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}

How do I integrate the cognito hosted UI into a react app?

I am creating a react app - using create-react-app and amplify - and I am trying to set up authentication. I don't seem to be able to handle the federated logins using the hosted UI.
There are some pages which require no authentication to reach and then some which require a user to be logged in. I would like to use the hosted UI since that's prebuilt. I have been following the getting started docs here: https://aws-amplify.github.io/docs/js/authentication
For background I have the following components:
- Amplify - an amplify client which wraps calls in methods like doSignIn doSignOut etc. The idea is to keep all this code in one place. This is a plain javascript class
- Session - provides an authentication context as a React context. This context is set using the amplify client. It has HOC's for using the context
- Pages - some wrapped in the session HOC withAuthentication which only renders the page if the user has logged in
This structure is actually taken from a Firebase tutorial: https://www.robinwieruch.de/complete-firebase-authentication-react-tutorial/
Maybe this is just not feasible with Amplify? Though the seem similar enough to me that it should work. The basic idea is that the Session provides a single auth context which can be subscribed to by using the withAuthentication HOC. That way any component that requires a user will be rendered as soon as a user has logged in.
Originally I wrapped the entire App component in the withAuthenticator HOC provided by amplify as described in the docs. However this means that no pages are accessible without being authenticated - home page needs to be accessible without an account.
Next I tried calling to the hosted UI with a sign in button and then handling the response. The problem is when the hosted UI has logged a user in then it redirects back to the app causing it to reload - which is not ideal for a single page app.
Then I tried checking if the user is authenticated every time the app starts - to deal with the redirect - but this becomes messy as I need to move a lot of the amplify client code to the Session context so that it can initialise correctly. The only way I can see to get this is using the Hub module: https://aws-amplify.github.io/docs/js/hub#listening-authentication-events The downside is that after logging in, the app refreshes and there's still a moment when you are logged out which makes the user experience weird.
I would have thought that there would be a way to not cause an application refresh. Maybe that's just not possible with the hosted UI. The confusing thing to me is that the documentation doesn't mention it anywhere. In actual fact there is documentation around handling the callback from the hosted UI which as far as I can see never happens because the entire page refreshes and so the callback can never run.
I've tried to trim this down to just what's needed. I can provide more on request.
Amplify:
import Amplify, { Auth } from 'aws-amplify';
import awsconfig from '../../aws-exports';
import { AuthUserContext } from '../Session';
class AmplifyClient {
constructor() {
Amplify.configure(awsconfig);
this.authUserChangeListeners = [];
}
authUserChangeHandler(listener) {
this.authUserChangeListeners.push(listener);
}
doSignIn() {
Auth.federatedSignIn()
.then(user => {
this.authUserChangeListeners.forEach(listener => listener(user))
})
}
doSignOut() {
Auth.signOut()
.then(() => {
this.authUserChangeListeners.forEach(listener => listener(null))
});
}
}
const withAmplify = Component => props => (
<AmplifyContext.Consumer>
{amplifyClient => <Component {...props} amplifyClient={amplifyClient} />}
</AmplifyContext.Consumer>
);
Session:
const provideAuthentication = Component => {
class WithAuthentication extends React.Component {
constructor(props) {
super(props);
this.state = {
authUser: null,
};
}
componentDidMount() {
this.props.amplifyClient.authUserChangeHandler((user) => {
this.setState({authUser: user});
});
}
render() {
return (
<AuthUserContext.Provider value={this.state.authUser}>
<Component {...this.props} />
</AuthUserContext.Provider>
);
}
}
return withAmplify(WithAuthentication);
};
const withAuthentication = Component => {
class WithAuthentication extends React.Component {
render() {
return (
<AuthUserContext.Consumer>
{user =>
!!user ? <Component {...this.props} /> : <h2>You must log in</h2>
}
</AuthUserContext.Consumer>
);
}
}
return withAmplify(WithAuthentication);
};
The auth context is provided once at the top level:
export default provideAuthentication(App);
Then pages that require authentication can consume it:
export default withAuthentication(MyPage);
What I would like to happen is that after the user signs in then I can set the AuthUserContext which in turn updates all the listeners. But due to the redirect causing the whole app to refresh the promise from Auth.federatedSignIn() can't resolve. This causes the user to be displayed with You must log in even though they just did.
Is there a way to block this redirect whilst still using the hosted UI? Maybe launch it in another tab or in a popup which doesn't close my app? Or am I going about this the wrong way? It just doesn't feel very 'Reacty' to cause full page refreshes.
Any help will be greatly appreciated. I can provide more details on request.
Instead of chaining onto the Auth's promise, you can use Amplify's build-in messaging system to listen to events. Here is how I do it in a custom hook and how I handle what gets rendered in Redux.
import { Auth, Hub } from 'aws-amplify';
import { useEffect } from 'react';
function useAuth({ setUser, clearUser, fetchQuestions, stopLoading }) {
useEffect(() => {
Hub.listen('auth', ({ payload: { event, data } }) => {
if (event === 'signIn') {
setUser(data);
fetchQuestions();
stopLoading();
}
if (event === 'signOut') {
clearUser();
stopLoading();
}
});
checkUser({ fetchQuestions, setUser, stopLoading });
}, [clearUser, fetchQuestions, setUser, stopLoading]);
}
async function checkUser({ fetchQuestions, setUser, stopLoading }) {
try {
const user = await Auth.currentAuthenticatedUser();
setUser(user);
fetchQuestions();
} catch (error) {
console.log(error);
} finally {
stopLoading();
}
}

React Application and User Roles

Is there a "built in" way to scope with different user roles in React Application? I want certain tabs, menus and links (routes) to be available only for certain users and not for others. Also, the content and options of many views will vary depending on the role. I know how to manage roles in the back end and retrieve them during the authentication in the JWT token, but what is the best way to parametrize the client-side state and representation based on the roles? Is the Redux and render logic conditions way to go, or is there a more streamlined solution, which necessarily doesn't demand the client browser to know all possible states for different roles prior to authentication?
I can suggest write a higher order component which takes roles who can see the feature.
const AuthorizeOnly = ({ children, allowedRoles, user }) => (
allowedRoles.includes(user.role)
&& (
<React.Fragment>
{children}
</React.Fragment>
)
);
// some component
loggedInUser = {
name:'john',
role:'admin'
}
render(){
<div>
<AuthorizedOnly allowedRoles={['admin']} user={loggedInUser}>
<p>only admin can see this.</p>
</AuthorizedOnly>
</div>
}
You can tweak the logic inside AuthorizedOnly component based on your business logic.
For Router you can use the similar component which returns a Route based on your condition

React POST to Node Server and handle JSON response

I am new to React so I am trying to understand how all this works together.
Is there a way to change the component that is rendering for another component after getting a status 200 from a node server?
For Example. I am doing a POST http request from a signup pageto my node with express server. The server response with a json object to my front end. Which Now I want the the profile component/page to render rather than staying at the signup page. This allows me to use the Json data and render it on the profile page. Is this possible? If you have another alternative I am open for suggestions too.
Thanks everyon.
Note:
I am using react router to control the different routes.
My node server is setup with passport to handle the singup.
You basically need to manage the state of your application (the user is connected / not connected). Then you can wrap your page inside a component managing the fact that user is connected or not.
Suppose you set user_is_logged as true if the login is successful. You can do something like :
var PageWrapper = React.createClass({
render : function() {
// user_is_logged is true if user is correctly logged
// LoginPage is the authentication form
var pageContent = user_is_logged ? this.props.children : <LoginPage />;
return (
<div>
<Menu />
<div className="container">
{pageContent}
</div>
</div>
);
},
});
var MyPage = React.createClass({
render : function() {
return (
<PageWrapper>
<div>content of page...</div>
</PageWrapper>
);
},
});
And re-render the page in the ajax callback :
ReactDOM.render (<MyPage />, document.getElementById('my-app'));
It works also with React router.
Please, take a look at Redux Architecture available at http://redux.js.org/
Understanding its concepts will make it clear to you the matter.
Then, go to the Advanced Topics of Redux and you will understand how asynchronous requests interact with Redux Components - (http://redux.js.org/docs/advanced/
Hope this helps.

React JS component renders multiple times in Meteor

I using Meteor 1.3 for this application together with react js and Tracker React.
I have a page to view all available users in the application. This page require user to login to view the data. If user not logged in, it will shows the login form and once logged-in the component will render the user's data.
Main component for the logic.
export default class MainLayout extends TrackerReact(React.Component) {
isLogin() {
return Meteor.userId() ? true : false
}
render() {
if(!this.isLogin()){
return (<Login />)
}else{
return (
<div className="container">
<AllUserdata />
</div>
)
}
}
}
And in the AllUserdata component:
export default class Users extends TrackerReact(React.Component) {
constructor() {
super();
this.state ={
subscription: {
Allusers : Meteor.subscribe("AllUsers")
}
}
}
componentWillUnmount(){
this.state.subscription.Allusers.stop();
}
allusers() {
return Meteor.users.find().fetch();
}
render() {
console.log('User objects ' + this.allusers());
return (
<div className="row">
{
this.allusers().map( (user, index)=> {
return <UserSinlge key={user._id} user={user} index={index + 1}/>
})
}
</div>
)
}
};
The problem is when logged in, it only shows the current user's data. All other user objects are not rendered. If I check on the console, console.log('User objects ' + this.allusers()); show objects being rendered 3 times: the first render only shows the current user's data, the second one renders data for all users (the desired result), and the third one again renders only the current user's data.
If I refresh the page, the user data will be rendered properly.
Any idea why?
React calls the render() method of components many times when it's running. If you're experiencing unexpected calls, it's usually the case that something is triggering changes to your component and initiating a re-render. It seems like something might be overwriting the call to Meteor.users.find().fetch(), which is probably happening because you're calling that function on each render. Try inspecting the value outside of the render method or, better yet, rely on tests to ensure that your component is doing what it should be :)
From https://facebook.github.io/react/docs/component-specs.html#render
The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using setTimeout). If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes server rendering more practical and makes components easier to think about.
See also:
https://facebook.github.io/react/docs/advanced-performance.html
https://facebook.github.io/react/docs/top-level-api.html#reactdom
https://ifelse.io/2016/04/04/testing-react-components-with-enzyme-and-mocha/

Categories

Resources