Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Auth to React context using Provider pattern #551

Closed
VicStor opened this issue Apr 14, 2019 · 15 comments
Closed

Add Auth to React context using Provider pattern #551

VicStor opened this issue Apr 14, 2019 · 15 comments
Labels
Authenticator An issue or a feature-request for an Authenticator UI Component feature-request Request a new feature

Comments

@VicStor
Copy link

VicStor commented Apr 14, 2019

Is your feature request related to a problem? Please describe.
A pattern used for Authenticator (withAuthenticator) React component is hardly extensible.
Prev feature request
Describe the solution you'd like
Use Provider pattern to track authentication state.

Describe alternatives you've considered
Here is very basic implementation

import React, { useEffect, useState } from 'react'
import createReactContext from 'create-react-context'
import { Hub, Auth } from 'aws-amplify'
const { Consumer: AuthConsumer, Provider } = createReactContext()

const AUTHENTICATOR_AUTHSTATE = 'amplify-authenticator-authState'

const AuthProvider = props => {
	const [auth, setAuth] = useState({})
	useEffect(() => {
		Auth.currentAuthenticatedUser()
			.then(user => {
				console.log('Current user: ', user)
				localStorage.setItem(AUTHENTICATOR_AUTHSTATE, 'signedIn')
				setAuth({ state: 'signIn', user })
			})
			.catch(err => localStorage.getItem(AUTHENTICATOR_AUTHSTATE))
			.then(cachedAuthState => cachedAuthState === 'signedIn' && Auth.signOut())
	}, [])
	useEffect(() => {
		Hub.listen('auth', ({ payload }) => {
			const { event, data } = payload
			if (event === 'signOut') {
				setAuth({ state: event, user: null })
				localStorage.deleteItem(AUTHENTICATOR_AUTHSTATE)
				return
			}
			localStorage.setItem(AUTHENTICATOR_AUTHSTATE, 'signedIn')
			setAuth({ state: event, user: data })
		})
	}, [])
	return <Provider value={auth}>{props.children}</Provider>
}

export { AuthConsumer, AuthProvider }

Wrap app in AuthProvider

<AuthProvider>
    <App />
</AuthProvider>

Use auth context where you need it

<AuthConsumer>
  {auth=>
    auth.user
    ? (
        <Button
            onClick={_ => Auth.signOut()/*...*/}
           children='Log Out'
        />
    ) : (
        <Button
            onClick={_ => Auth.signIn(/*...*/)/*...*/}
           children='Log Out'
        />
    )
  }
</AuthConsumer>

Additional context
Let me know you not mind to add this. I could implement it quite easily.

@jordanranz
Copy link

This seems like a necessary improvement. Definitely open to reviewing a PR.

I am currently working on an RFC to introduce web components with StencilJS. With this project we would ideally implement a similar design using Stencil's state tunnel. These components could then be used in any framework including the major ones we support.

@stale
Copy link

stale bot commented Jun 15, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

1 similar comment
@stale
Copy link

stale bot commented Jul 17, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale
Copy link

stale bot commented Jul 24, 2019

This issue has been automatically closed because of inactivity. Please open a new issue if are still encountering problems.

@stale stale bot closed this as completed Jul 24, 2019
@kjellski
Copy link

Did this ever really make it into the package? I can't find it...

@matt-d-webb
Copy link

I'd love to know this too? I can't find any other references.

@brendonparker
Copy link

Bump

@lebull
Copy link

lebull commented Jan 10, 2021

@VicStor Thanks a ton for the example implementation for this, using it in my codebase for now.

Why in the world does this still not come with the amplify react library? This should be a no-brainer.

@undefobj undefobj reopened this Jan 10, 2021
@undefobj
Copy link

Reopening cc @ericclemmons @sammartinez

@akeithly
Copy link

This would be particularly handy for those of us not using the UI Components. They already have the onAuthUIStateChange to work with but many of need to build custom login components.

@Ajit-Singh-Brar
Copy link

Ajit-Singh-Brar commented Oct 21, 2021

I was following the same template for the Provider pattern for AuthProvider. The following commented line:

useEffect(() => {
		Hub.listen('auth', ({ payload }) => {
			const { event, data } = payload
			if (event === 'signOut') {
				setAuth({ state: event, user: null })
				localStorage.deleteItem(AUTHENTICATOR_AUTHSTATE)
				return
			}
			localStorage.setItem(AUTHENTICATOR_AUTHSTATE, 'signedIn')
			setAuth({ state: event, user: data })    //     when this statement gets executed it is causing problem at my forgotPassword component which never shows me the ResetPassword component when the user receives the confirmation code.  
		})
	}, [])
That statement with comment, if it is actually commented then it is affecting the authState. When I am trying to perform the signIn. It gets authenticated but doesn't redirects to the page . Once refreshed it, it shows the actual page, until unless not. How can I solve this issue

@ericclemmons ericclemmons transferred this issue from aws-amplify/amplify-js Oct 21, 2021
@ericclemmons ericclemmons added Authenticator An issue or a feature-request for an Authenticator UI Component feature-request Request a new feature labels Oct 21, 2021
@Ajit-Singh-Brar
Copy link

Hi @ericclemmons , can you help me with this issue to solve the problem which is happening on the Sign In and ForgotPassword component. If I am commenting the "setAuth" statement, the ForgotPassword works properly, but authentication on Sign IN, afetr signing In doesn't redirects to the actual page after login.

It will be very kind, if you help me out on this

@ericclemmons
Copy link
Contributor

ericclemmons commented Oct 21, 2021

@Ajit-Singh-Brar So I understand, you'd like a hook or provider for the Auth category that you can use on its own?

(This sounds related to #254)

The @next release introduces an Authenticator.Provider & useAuthenticator() hook for a truly customized experience (see: #532).

Until then, I've personally used the following useAuth() hook in my code:

import { Auth, Hub } from 'aws-amplify';

import { useEffect, useState } from 'react';

export default function useAuth() {
  const [isLoading, setIsLoading] = useState(true);
  const [user, setUser] = useState();

  const handleAuth = ({ payload }) => {
    switch (payload.event) {
      case 'signIn':
        return setUser(payload.data);
      case 'signOut':
        return setUser();
      default:
    }
  };

  useEffect(() => {
    Auth.currentAuthenticatedUser()
      .then(setUser)
      .catch(console.error)
      .then(() => setIsLoading(false));

    Hub.listen('auth', handleAuth);

    return () => Hub.remove('auth', handleAuth);
  }, []);

  return {
    Auth,
    isLoading,
    owner: user ? user.username : null,
    user
  };
}

It doesn't require a provider, so you would be able to use it like:

function App() {
  const { isLoading, user } = useAuth()

  if (isLoading) return "Loading..."

  if (user) {
    return <h1>Welcome {user.username}!</h1>
  }

  return <MyCustomSignInScreen />
}

@Ajit-Singh-Brar
Copy link

Thanks. It has solved my problem.

@ericclemmons
Copy link
Contributor

That's great to hear! In the meantime, I'll close this as resolved via #532 and we'll get the documentation added for useAuthenticator as part of #552.

thaddmt added a commit that referenced this issue Apr 7, 2023
…client

chore: update client-rekognitionstreaming to turn on frame signing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Authenticator An issue or a feature-request for an Authenticator UI Component feature-request Request a new feature
Projects
None yet
Development

No branches or pull requests

10 participants