@eficens/cognito
v1.0.1
Published
An AWS Cognito wrapper for React
Downloads
9
Readme
ef-cognito
ef-cognito
is an npm package that simplifies AWS Cognito authentication in React applications. It provides an easy-to-use plug-and-play service that can be integrated using environment variables for AWS Cognito User Pool credentials.
Features
- AWS Cognito User Sign-Up
- AWS Cognito User Sign-In
- Session Management (Get current session)
- User Sign-Out
- Simple
.env
configuration for AWS Cognito credentials
Installation
To install ef-cognito
, run the following command:
npm install ef-cognito
Environment Variables
Create a .env
file in the root of your React project and add the following AWS Cognito-related keys:
REACT_APP_COGNITO_USER_POOL_ID=your-cognito-user-pool-id
REACT_APP_COGNITO_CLIENT_ID=your-cognito-client-id
REACT_APP_AWS_REGION=your-aws-region
Example .env
file:
REACT_APP_COGNITO_USER_POOL_ID=us-east-1_123456789
REACT_APP_COGNITO_CLIENT_ID=1a2b3c4d5e6f7g8h9i0j
REACT_APP_AWS_REGION=us-east-1
Usage in a React Application
Here is a step-by-step guide on how to integrate ef-cognito
into your React application.
1. Import and Initialize AuthService
First, import the AuthService
class from the ef-cognito
package and create an instance.
import { AuthService } from 'ef-cognito';
const authService = new AuthService();
2. Implement Sign-Up
The signUp
method allows you to sign up a new user to AWS Cognito by providing a username, password, and email address.
authService.signUp(username, password, email)
.then(user => {
console.log(`User ${user.getUsername()} signed up successfully.`);
})
.catch(error => {
console.error('Sign-up failed:', error.message);
});
3. Implement Sign-In
The signIn
method authenticates an existing user with a username and password.
authService.signIn(username, password)
.then(session => {
console.log('User signed in successfully:', session);
})
.catch(error => {
console.error('Sign-in failed:', error.message);
});
4. Get Current Session
The getSession
method retrieves the current authenticated session if available.
authService.getSession()
.then(session => {
console.log('Current session:', session);
})
.catch(error => {
console.error('Failed to retrieve session:', error.message);
});
5. Sign-Out
The signOut
method allows the user to sign out.
authService.signOut();
console.log('User signed out successfully.');
Example React Component
Here’s how you can create a basic authentication component in React using ef-cognito
:
import React, { useState } from 'react';
import { AuthService } from 'ef-cognito';
const authService = new AuthService();
const AuthComponent = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const handleSignUp = async () => {
try {
const user = await authService.signUp(username, password, email);
setMessage(`User ${user.getUsername()} signed up successfully.`);
} catch (error) {
setMessage(`Sign-up failed: ${error.message}`);
}
};
const handleSignIn = async () => {
try {
const session = await authService.signIn(username, password);
setMessage('Sign-in successful!');
} catch (error) {
setMessage(`Sign-in failed: ${error.message}`);
}
};
const handleSignOut = () => {
authService.signOut();
setMessage('User signed out successfully.');
};
return (
<div>
<h2>Sign Up</h2>
<input
type="text"
placeholder="Username"
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
/>
<input
type="email"
placeholder="Email"
onChange={(e) => setEmail(e.target.value)}
/>
<button onClick={handleSignUp}>Sign Up</button>
<h2>Sign In</h2>
<input
type="text"
placeholder="Username"
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={handleSignIn}>Sign In</button>
<button onClick={handleSignOut}>Sign Out</button>
<p>{message}</p>
</div>
);
};
export default AuthComponent;
Notes
- Make sure to set up the
.env
file in your React project with the correct AWS Cognito values. - You can extend this package to handle additional AWS Cognito features, such as password reset, MFA, and user attribute management.
Running Tests
To run the tests for the package:
npm test
To generate a coverage report:
npm test -- --coverage
Contributing
We welcome contributions! If you find a bug or have a suggestion, feel free to create an issue or submit a pull request.
License
This project is licensed under the MIT License. See the LICENSE file for details.