npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@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

  1. Make sure to set up the .env file in your React project with the correct AWS Cognito values.
  2. 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.