Skip to content

Instantly share code, notes, and snippets.

@chidindu-ogbonna
Last active September 4, 2021 21:21
Show Gist options
  • Save chidindu-ogbonna/95fbbbb36aa2c683ab92a320fdabec8f to your computer and use it in GitHub Desktop.
Save chidindu-ogbonna/95fbbbb36aa2c683ab92a320fdabec8f to your computer and use it in GitHub Desktop.
A useUser context for Nextjs using AWS Amplify
import { Auth } from "@aws-amplify/auth";
import Router from "next/router";
import { createContext, useContext, useEffect, useState } from "react";
import { createUser, getUser } from "../utils/api";
const AuthContext = createContext();
export const useAuthContext = () => useContext(AuthContext);
export const AuthProvider = (props) => {
const [user, setUser] = useState(null);
const [authenticatingUser, setAuthenticatingUser] = useState(null);
const login = async (email, password) => {
const user = await Auth.signIn(email, password);
const { challengeName } = user;
if (challengeName === "NEW_PASSWORD_REQUIRED") {
setAuthenticatingUser(user);
return { challengeName };
}
const response = await getUser({ id: user.username });
user.data = response.data.user;
setUser(user);
return { challengeName: null };
};
const signUp = async (data) => {
const user = await Auth.currentAuthenticatedUser();
data.user_id = user.username;
data.email = user.attributes.email;
const response = await createUser(data);
user.data = response.data.user;
return setUser(user);
};
const signOut = async () => {
await Auth.signOut();
setUser(null);
Router.push("/login");
};
const completeNewPassword = async (newPassword) => {
return Auth.completeNewPassword(authenticatingUser, newPassword);
};
const forgotPassword = (username) => Auth.forgotPassword(username);
const completeForgotPassword = async (username, code, password) => {
return Auth.forgotPasswordSubmit(username, code, password);
};
useEffect(() => {
console.log("====== useUser getCurrentAuthenticatedUser() Effect");
const getCurrentAuthenticatedUser = async () => {
try {
const user = await Auth.currentAuthenticatedUser();
console.log("====== Gotten User data: ", user);
const response = await getUser({ id: user.username });
user.data = response.data.user;
setUser(user);
if (Router.pathname === "/login") {
console.log("UseUser Context: Push route:");
Router.push("/");
}
} catch (error) {
console.log(error);
Router.push("/login");
}
};
getCurrentAuthenticatedUser();
}, []);
return (
<AuthContext.Provider
value={[
{
user,
login,
signUp,
signOut,
completeNewPassword,
forgotPassword,
completeForgotPassword,
},
setUser,
]}
{...props}
/>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment