Voiced by Amazon Polly |
Overview
In my previous blog, we learned how to verify the user in the Cognito user pool and how to log in the user in our application using ‘amazon-cognito-identity-js’. In this blog, we will learn how to manage the state or session of a logged-in user and how to log out the user from the application using the ‘amazon-cognito-identity-js’ library.
Customized Cloud Solutions to Drive your Business Success
- Cloud Migration
- Devops
- AIML & IoT
Introduction to 'amazon-cognito-identity-js'
‘amazon-cognito-identity-js’ is the SDK that allows a JavaScript-enabled application to authenticate the users, view user details, delete users, update users and register the users. It also allows password change for authenticated users and forgot password functionality.
Steps to Create a Component
Step 1: Create an Account.js file in src/Components directory and follow the code snippet in the file.
This code snippet is for Central session management. We can use it in every component. In this component, we will get the current session information using getCurrentUser method in getSession function. And in authenticating function, we will authenticate the user. And Logout function is to log out the user from the application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
import { AuthenticationDetails, CognitoUser } from 'amazon-cognito-identity-js'; import { createContext } from 'react'; import UserPool from '../UserPool'; const AccountContext = createContext(); const Account = (props) => { const getSession = async () => { await new Promise((resolve, reject) => { const user = UserPool.getCurrentUser(); if (user) { user.getSession((err, session) => { if (err) { reject(err); } else { resolve(session); } }); } else { reject(); } }); }; const authenticate = async (Username, Password) => { await new Promise((resolve, reject) => { const user = new CognitoUser({ Username, Pool: UserPool, }); const authDetails = new AuthenticationDetails({ Username, Password, }); user.authenticateUser(authDetails, { onSuccess: (result) => { console.log('login success', result); resolve(result); }, onFailure: (err) => { console.log('login failure', err); reject(err); }, newPasswordRequired: (data) => { console.log('new password required', data); resolve(data); }, }); }); }; const logout = () => { const user = UserPool.getCurrentUser(); user.signOut(); window.location.href = '/'; }; return ( <AccountContext.Provider value={{ authenticate, getSession, logout }}> {props.children} </AccountContext.Provider> ); }; export { Account, AccountContext }; |
Step 2: Create a ‘Status.js’ file in src/components directory
This code snippet is to get the user’s current session using the getSession function which we created in the last step. And on the UI, we are displaying the current status of the user using HTML code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import { useContext, useEffect, useState } from 'react'; import { AccountContext } from './Account'; const Status = () => { const [status, setStatus] = useState(false); const { getSession, logout } = useContext(AccountContext); useEffect(() => { getSession() .then((session) => { console.log('Session: ', session); setStatus(true); }) .catch((err) => { console.log('Session: ', err); setStatus(false); }); }, [status]); return ( <div> {status ? ( <div> {' '} You are logged in. <button onClick={logout}>Logout</button> </div> ) : ( 'Please Login' )} </div> ); }; export default Status; |
Step 3: Modify the App.js
This code snippet is for wrapping the whole application with the Account component to use all the function of the Account component in every component of the application.
<Status /> is to display the current stage of the user whether it is logged in or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import { BrowserRouter, Route, Routes } from 'react-router-dom'; import './App.css'; import { Account } from './Components/Account'; import Login from './Components/Login'; import Register from './Components/Register'; import Status from './Components/Status'; function App() { return ( <Account> <Status /> <BrowserRouter> <Routes> <Route path="/" element={<Login />} /> <Route path="/register" element={<Register />} /> <Route path="/login" element={<Login />} /> </Routes> </BrowserRouter> </Account> ); } export default App; |
Step 4: Modify the Login.js file
In this step, we are modifying the login page and will call authenticate method of the Account component to log in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import { useContext, useState } from 'react'; import { AccountContext } from './Account'; function Login() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const { authenticate } = useContext(AccountContext); const onSubmit = (e) => { e.preventDefault(); authenticate(username, password) .then((data) => { console.log(data); alert('login success'); window.location.reload(); }) .catch((err) => { console.log(err); alert('login failure'); }); }; return ( <div> <form onSubmit={onSubmit}> Username: <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} /> <br /> Password: <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <br /> <button type="submit">Login</button> </form> </div> ); } export default Login; |
Conclusion
In this blog, we learn how to manage the state or session of logged in users and how to log out the user from the application using the ‘amazon-cognito-identity-js’ library.
In my next blog, we will see how to implement change password functionality in our application.
Get your new hires billable within 1-60 days. Experience our Capability Development Framework today.
- Cloud Training
- Customized Training
- Experiential Learning
About CloudThat
CloudThat is also the official AWS (Amazon Web Services) Advanced Consulting Partner and Training partner and Microsoft gold partner, helping people develop knowledge of the cloud and help their businesses aim for higher goals using best in industry cloud computing practices and expertise. We are on a mission to build a robust cloud computing ecosystem by disseminating knowledge on technological intricacies within the cloud space. Our blogs, webinars, case studies, and white papers enable all the stakeholders in the cloud computing sphere.
Drop a query if you have any questions regarding AWS Cognito User Pool, React JS and I will get back to you quickly.
To get started, go through our Consultancy page and Managed Services Package that is CloudThat’s offerings.
FAQs
1. Can we display the logged-in user’s username or email?
ANS: – Yes, we can display the user information on the page. Once the user is logged in, we will get the user information as a JSON object from the AWS Cognito User Pool. by parsing the JSON object, we can display the user information on the page.
2. Can we redirect the user to login page after logout?
ANS: – Yes, we can redirect the user to the login page once the user is logged out from the application. We can use navigate or normal javascript method (window.location.href)
WRITTEN BY Mayur Patel
Click to Comment