Created
November 25, 2019 14:44
-
-
Save groundedsage/995dc2e14845980fdc547c8ba510169c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect, createContext, useContext, ReactNode } from 'react' | |
import Amplify, { Auth, Hub } from 'aws-amplify' | |
import { CognitoUser } from '@aws-amplify/auth' | |
import { CognitoUserSession } from 'amazon-cognito-identity-js' | |
import { HubCallback } from '@aws-amplify/core/lib/Hub' | |
import IUser from '../../types/IUser' | |
interface IAuthContext { | |
user: IUser | null | |
login(username: string, password: string): Promise<CognitoUser> | |
logout(): Promise<any> | |
} | |
interface Props { | |
children?: ReactNode | |
} | |
Amplify.configure({ | |
Auth: { | |
region: process.env.REACT_APP_AWS_REGION, | |
userPoolId: process.env.REACT_APP_AWS_USER_POOL_ID, | |
userPoolWebClientId: process.env.REACT_APP_AWS_USER_POOL_WEB_CLIENT_ID | |
} | |
}); | |
const login = (username: string, password: string): Promise<CognitoUser> => Auth.signIn(username, password) | |
const logout = (): Promise<any> => Auth.signOut() | |
const getSession = (): Promise<CognitoUserSession | null> => Auth.currentSession() | |
const useCognito = () => { | |
const [user, setUser] = useState<IUser | null>(null) | |
const authListener: HubCallback = ({ payload: { event, data } }) => { | |
switch (event) { | |
case 'signIn': | |
setUser({ username: data.username, token: data.signInUserSession.accessToken }) | |
break; | |
case 'signOut': | |
setUser(null); | |
break; | |
} | |
} | |
useEffect(() => { | |
getSession().then((session) => { | |
if(session && session.isValid()) { | |
Auth.currentUserInfo().then((user: any ) => { | |
setUser({username: user.username, token: session.getAccessToken()}) | |
}) | |
} | |
}) | |
}, []) | |
useEffect(() => { | |
Hub.listen('auth', authListener) | |
return () => Hub.remove('auth', authListener) | |
}, []) | |
return { user, login, logout } | |
} | |
const AuthContext = createContext<IAuthContext>({ | |
user: null, | |
login, | |
logout | |
}) | |
export const useAuth = () => { | |
return useContext(AuthContext) | |
}; | |
export const Provider = ({ children }: Props) => { | |
const auth = useCognito() | |
return (<AuthContext.Provider value={auth}>{children}</AuthContext.Provider>) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@paulohfsantos, I share your curiosity about the IUser.
Given the information of setUser, we might intuit something like this: