Giter VIP home page Giter VIP logo

aws-amplify-react-custom-ui's Introduction

aws-amplify-react-custom-ui

NPM JavaScript Style Guide

Install

npm install --save aws-amplify-react-custom-ui

Usage

This lib help you override existing ui for amplify-react

Online Example

https://stackblitz.com/github/ysfmag/aws-amplify-react-custom-ui-example

github link : https://github.com/ysfmag/aws-amplify-react-custom-ui-example

Configuration

Somewhere in your app, preferably at the root level, configure AmplifyCustomUi .

import React from "react";
import ReactDOM from "react-dom";

// amplify config
import Amplify from "aws-amplify";
import awsconfig from "./aws-exports";

// amplify-Custom-ui config
import * as aws_amplify_react from "aws-amplify-react";
import AmplifyCustomUi from "aws-amplify-react-custom-ui";

Amplify.configure(awsconfig);
AmplifyCustomUi.configure(aws_amplify_react);

ReactDOM.render(<App />, document.getElementById("root"));

Example

You can provide custom SignIn component by using , setSignIn:

import SignIn from "./SignIn";
import AmplifyCustomUi from "aws-amplify-react-custom-ui";
AmplifyCustomUi.setSignIn(SignIn);

params

withAuthenticator(Component, federated = null, theme = null) : component renders your App component after a successful user signed in, and it prevents non-sign-in uses to interact with your app. In this case, we need to display a sign-out button to trigger the related process.

configure(configuration) : configure the lib "aws-amplify-react-custom-ui" .

setSignIn(component) : to override the signIn page .

setForgotPassword(component) : to override the ForgotPassword page .

setConfirmSignUp(component) .

setVerifyContact(component) .

setSignUp(component) .

setRequireNewPassword(component) .

setConfirmSignIn(component) .

setTOTPSetup(component) .

the lib provide tow function authError , changeAuthState as props to the component , you need to use these function to notify that the authentication state had been changed , example .

App.js

import React, { Component } from "react";
import SignIn from "./SignIn";
import amplifyCustomUi from "aws-amplify-react-custom-ui";
import SecureApp from "./SecureApp";

class App extends Component {
  componentWillMount() {
    amplifyCustomUi.setSignIn(SignIn);
  }

  render() {
    return <SecureApp />;
  }
}

export default App;

SecureApp

import React, { Component } from "react";
import amplifyCustomUi from "aws-amplify-react-custom-ui";
import { Auth } from "aws-amplify";

const styes = {
  container: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center"
  },
  button: { width: "200px", height: "60px", backgroundColor: "red" }
};
class SecureApp extends Component {
  signOut = () => {
    const { onStateChange } = this.props;
    Auth.signOut().then(() => {
      onStateChange("signIn");
    });
  };
  render() {
    return (
      <div style={styes.container}>
        <h1> hello world </h1>
        <button onClick={this.signOut} style={styes.button}>
          sign Out
        </button>
      </div>
    );
  }
}

export default amplifyCustomUi.withAuthenticator(SecureApp);

SignIn

import React, { Component } from "react";
import { Auth } from "aws-amplify";
const styles = {
  container: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center"
  },
  input: {
    width: "100%",
    padding: "12px 20px",
    margin: "8px 0",
    display: "inline-block",
    border: "1px solid #ccc",
    borderRadius: "4px",
    boxSizing: "border-box"
  },
  submit: {
    width: "100%",
    backgroundColor: "#4CAF50",
    color: "white",
    padding: "14px 20px",
    margin: "8px 0",
    border: "none",
    borderRadius: "4px",
    cursor: "pointer"
  }
};

const updateByPropertyName = (propertyName, value) => () => ({
  [propertyName]: value
});

const INITIAL_STATE = {
  email: "",
  password: "",
  error: null
};

class SignIn extends Component {
  constructor(props) {
    super(props);

    this.state = { ...INITIAL_STATE };
  }

  changeState(type, event) {
    const { changeAuthState } = this.props;
    changeAuthState(type, event);
  }

  onSubmit = event => {
    const { email, password } = this.state;

    Auth.signIn(email, password)
      .then(user => {
        this.setState(() => ({ ...INITIAL_STATE }));
        if (
          user.challengeName === "SMS_MFA" ||
          user.challengeName === "SOFTWARE_TOKEN_MFA"
        ) {
          this.changeState("confirmSignIn", user);
        } else if (user.challengeName === "NEW_PASSWORD_REQUIRED") {
          this.changeState("requireNewPassword", user);
        } else if (user.challengeName === "MFA_SETUP") {
          this.changeState("TOTPSetup", user);
        } else {
          this.changeState("signedIn", user);
        }
      })
      .catch(err => {
        const { authError } = this.props;
        if (err.code === "UserNotConfirmedException") {
          this.changeState("confirmSignUp");
        } else if (err.code === "PasswordResetRequiredException") {
          this.changeState("requireNewPassword");
        } else {
          authError(err);
        }
        this.setState(updateByPropertyName("error", err));
      });

    event.preventDefault();
  };

  render() {
    const { email, password, error } = this.state;

    const isInvalid = password === "" || email === "";

    return (
      <div>
        <div style={styles.container}>
          <h1>SignIn</h1>
          <form onSubmit={this.onSubmit}>
            <input
              style={styles.input}
              value={email}
              onChange={event =>
                this.setState(updateByPropertyName("email", event.target.value))
              }
              type="text"
              placeholder="Email Address"
            />
            <input
              style={styles.input}
              value={password}
              onChange={event =>
                this.setState(
                  updateByPropertyName("password", event.target.value)
                )
              }
              type="password"
              placeholder="Password"
            />
            <button style={styles.submit} disabled={isInvalid} type="submit">
              Sign In
            </button>

            {error && <p>{error.message}</p>}
          </form>
          <div>
            <p> No account? </p>
            <button
              style={styles.submit}
              onClick={() => this.changeState("signUp")}
            >
              Create account
            </button>
          </div>
        </div>
      </div>
    );
  }
}

export default SignIn;

License

MIT © youssef maghzaz

aws-amplify-react-custom-ui's People

Contributors

dependabot[bot] avatar howyi avatar melbarch avatar ymaghzaz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

aws-amplify-react-custom-ui's Issues

ConfirmSignUp custom UI does not keep the user signed in

Hello. I am using your library to create a custom ConfirmSignUp. It works great for SignIn and SignUp but when I want to confirm the Sign Up it renders a blank page, and if I refresh it takes me back to sign in.
Here is my function :
onSubmit = (event) => {
const { username, verificationCode } = this.state;

    Auth.confirmSignUp(username, verificationCode)
        .then((user) => {
            this.changeState("signedUp", user);
        })
        .catch(err => {
            this.setState(updateByPropertyName("error", err));
        });
    event.preventDefault();

};

Thank you

How can I pass authData between components?

First of all, thanks for such a great package, the UI is looking great thanks to this customisation.

I have created 2 class components, one for SigIn, another for NewPassword, i.e. overriding the auto-generated password when an admin creates a new account in Cognito.

The components are successfully loaded like this

AmplifyCustomUi.setSignIn(SignIn);
AmplifyCustomUi.setRequireNewPassword(NewPassword);

The SignIn component is able to create a Cognito session and returns the payload in the user result object.

const user = await Auth.signIn(username, password);

if (!user.challengeName) {
  this.changeState("signedIn", user);
  return true;
}

if (user.challengeName === "NEW_PASSWORD_REQUIRED") {
  this.changeState("requireNewPassword", user);
}
return false;

The problem is that the NewPassword component does not receive the user content via props.
Could you provide an example of how could I retrieve the user, so that I can invoke the following Amplify function to set the initial password?

const result = await Auth.completeNewPassword(user, password, {});

thanks very much,

Jaume

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.