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

Auth #10

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Auth #10

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 48 additions & 38 deletions lib/utils/auth.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import React, { useState, useEffect, useContext, createContext } from 'react';
import { useMutation, useLazyQuery } from '@apollo/client';
import { useLazyQuery } from '@apollo/client';
import { useRouter } from 'next/router';
import { useCookies } from 'react-cookie';
import axios from 'axios';
import jwtDecode from 'jwt-decode';

import { GET_USER_QUERY, LOGIN_MUTATION, LOGOUT_MUTATION } from './queries';
import { GET_USER_QUERY } from './queries';

export const AuthContext = createContext();

Expand All @@ -14,11 +16,17 @@ export const useAuth = () => {
export const AuthProvider = ({ children }) => {
const [authErrors, setAuthErrors] = useState(null);
const [userInfo, setUserInfo] = useState(null);
const isSignedIn = userInfo?.getUser.id;

const [userToken, setUserToken] = useState(null);

const [cookies, setCookie, removeCookie] = useCookies(['user']);
const router = useRouter();
const [queryCurrentUser] = useLazyQuery(GET_USER_QUERY, {
variables: {
token: cookies?.user?.user.token,
context: {
headers: {
Authorization: userToken ? userToken : cookies?.user,
},
},
onCompleted: data => {
setUserInfo(data);
Expand All @@ -28,59 +36,61 @@ export const AuthProvider = ({ children }) => {
},
});

const [userLogin] = useMutation(LOGIN_MUTATION, {
onError: err => {
console.log(err);
},
});
const [userLogout] = useMutation(LOGOUT_MUTATION, {
onError: err => {
console.log(err);
},
});

useEffect(() => {
if (cookies?.user?.user.token) {
queryCurrentUser();
if (cookies?.user) {
const token = jwtDecode(cookies?.user);
queryCurrentUser({ variables: { id: token.sub } });
}
}, []);

const userToken = cookies?.user?.token ?? null;
const isSignedIn = userInfo?.getUser.token;
useEffect(() => {
if (userToken) {
const token = jwtDecode(userToken);
queryCurrentUser({ variables: { id: token.sub } });
}
}, [userToken]);

const signOut = async () => {
try {
await userLogout();
await axios.delete(process.env.NEXT_PUBLIC_API_AUTH_URL + '/sign_out', {
headers: {
authorization: cookies?.user,
},
});
removeCookie('user');
setUserInfo(null);
router.push('/recipes');
} catch (e) {
console.log(e);
router.push('/session');
} catch {
e => setAuthErrors(e);
}
};

const signIn = async ({ email, password }) => {
const result = await userLogin({ variables: { email, password } });
const signIn = ({ email, password }) => {
axios
.post(process.env.NEXT_PUBLIC_API_AUTH_URL + '/sign_in', {
user: {
email: email,
password: password,
},
})
.then(response => {
const token = response?.headers?.authorization;

const loginData = result?.data?.signInMutation;
if (loginData?.token) {
queryCurrentUser();
setCookie('user', JSON.stringify(loginData), {
path: '/',
maxAge: 86400, // Expires after 24hr
sameSite: true,
});
router.push('/favorites');
} else {
setAuthErrors(result?.data?.signInMutation?.errors);
}
setCookie('user', token, {
path: '/',
maxAge: 604800, // Expires after 1wk
sameSite: true,
});
setUserToken(response?.headers?.authorization);
router.push('/favorites');
})
.catch(e => setAuthErrors(e));
};

return (
<AuthContext.Provider
value={{
authErrors,
userToken,
signIn,
signOut,
userInfo,
Expand Down
4 changes: 0 additions & 4 deletions lib/utils/config.ts

This file was deleted.

39 changes: 6 additions & 33 deletions lib/utils/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const GET_ALL_RECIPES = gql`
`;

export const GET_RECIPE = gql`
query getRecipe($id: String!) {
query getRecipe($id: ID!) {
getRecipe(id: $id) {
id
title
Expand Down Expand Up @@ -65,8 +65,8 @@ export const GET_RANDOM_RECIPES = gql`
`;

export const GET_RANDOM_RECIPE = gql`
query getRandomRecipes($id: String!) {
getRandomRecipe(id: $id) {
query getSpoonacularRecipe($spoonacularId: ID!) {
getSpoonacularRecipe(spoonacularId: $spoonacularId) {
id
title
summary
Expand All @@ -83,9 +83,9 @@ export const GET_RANDOM_RECIPE = gql`
`;

export const GET_USER_QUERY = gql`
query getUser($token: String!) {
getUser(token: $token) {
token
query getUser($id: ID!) {
getUser(id: $id) {
id
email
recipes {
id
Expand All @@ -96,30 +96,3 @@ export const GET_USER_QUERY = gql`
}
}
`;

export const LOGIN_MUTATION = gql`
mutation SignMeIn($email: String!, $password: String!) {
signInMutation(email: $email, password: $password) {
token
success
errors {
message
}
user {
id
token
}
}
}
`;

export const LOGOUT_MUTATION = gql`
mutation SignMeOut {
signOutMutation {
success
errors {
message
}
}
}
`;
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@
"@svgr/webpack": "^5.5.0",
"apollo-boost": "^0.4.9",
"apollo-upload-client": "^14.1.3",
"axios": "^0.21.1",
"cookie": "^0.4.1",
"formik": "^2.2.6",
"graphql": "^15.5.0",
"jwt-decode": "^3.1.2",
"next": "10.2.0",
"next-with-apollo": "^5.1.1",
"postcss-cli": "^8.3.1",
Expand Down
41 changes: 17 additions & 24 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import { CookiesProvider } from 'react-cookie';
import { ApolloProvider, ApolloClient } from '@apollo/client';
import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import { ApolloProvider, ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

import Page from '../components/Page';
import { AuthProvider } from '../lib/utils/auth.js';
Expand All @@ -18,29 +18,22 @@ interface Props {
const MyApp: React.FC<Props> = ({ Component, pageProps }) => {
const [cookies] = useCookies(['user']);

const client = new ApolloClient({
const httpLink = createHttpLink({
uri: process.env.NEXT_PUBLIC_API_URL,
// @ts-expect-error
cache: new InMemoryCache({
fragmentMatcher: new IntrospectionFragmentMatcher({
introspectionQueryResultData: {
__schema: {
types: [],
},
},
}),
}),
request: (operation: {
setContext: (arg0: { headers: { authorization: string } }) => void;
}) => {
if (cookies?.user?.token) {
operation.setContext({
headers: {
authorization: `Bearer ${cookies?.token}`,
},
});
}
},
});

const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
Authorization: cookies?.user ? cookies?.user : headers.Authorization,
},
};
});

const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});

return (
Expand Down
17 changes: 17 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2452,6 +2452,13 @@ available-typed-arrays@^1.0.2:
dependencies:
array-filter "^1.0.0"

axios@^0.21.1:
version "0.21.1"
resolved "https://registry.yarnpkg.com/axios/-/axios-0.21.1.tgz#22563481962f4d6bde9a76d516ef0e5d3c09b2b8"
integrity sha512-dKQiRHxGD9PPRIUNIWvZhPTPpl1rf/OxTYKsqKUDjBwYylTvV7SjSHJb9ratfyzM6wCdLCOYLzs73qpg5c4iGA==
dependencies:
follow-redirects "^1.10.0"

babel-jest@^27.0.5:
version "27.0.5"
resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-27.0.5.tgz#cd34c033ada05d1362211e5152391fd7a88080c8"
Expand Down Expand Up @@ -3991,6 +3998,11 @@ flatted@^3.1.0:
resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.1.1.tgz#c4b489e80096d9df1dfc97c79871aea7c617c469"
integrity sha512-zAoAQiudy+r5SvnSw3KJy5os/oRJYHzrzja/tBDqrZtNhUw8bt6y8OBzMWcjWr+8liV8Eb6yOhw8WZ7VFZ5ZzA==

follow-redirects@^1.10.0:
version "1.14.2"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.2.tgz#cecb825047c00f5e66b142f90fed4f515dec789b"
integrity sha512-yLR6WaE2lbF0x4K2qE2p9PEXKLDjUjnR/xmjS3wHAYxtlsI9MLLBJUZirAHKzUZDGLxje7w/cXR49WOUo4rbsA==

foreach@^2.0.5:
version "2.0.5"
resolved "https://registry.yarnpkg.com/foreach/-/foreach-2.0.5.tgz#0bee005018aeb260d0a3af3ae658dd0136ec1b99"
Expand Down Expand Up @@ -5295,6 +5307,11 @@ jsonfile@^6.0.1:
array-includes "^3.1.2"
object.assign "^4.1.2"

jwt-decode@^3.1.2:
version "3.1.2"
resolved "https://registry.yarnpkg.com/jwt-decode/-/jwt-decode-3.1.2.tgz#3fb319f3675a2df0c2895c8f5e9fa4b67b04ed59"
integrity sha512-UfpWE/VZn0iP50d8cz9NrZLM9lSWhcJ+0Gt/nm4by88UL+J1SiKN8/5dkjMmbEzwL2CAe+67GsegCbIKtbp75A==

kleur@^3.0.3:
version "3.0.3"
resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e"
Expand Down