feat: align auth api with front convention (#370)

* feat: align auth api with front convention

* fix: email password auth

* fix: proper file naming

* Fix login

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
This commit is contained in:
Jérémy M
2023-06-24 07:43:54 +02:00
committed by GitHub
parent c6708b2c1f
commit 31145c5518
23 changed files with 222 additions and 293 deletions

View File

@ -0,0 +1,57 @@
import { useEffect, useMemo, useRef } from 'react';
import { InMemoryCache, NormalizedCacheObject } from '@apollo/client';
import { useRecoilState } from 'recoil';
import { tokenPairState } from '@/auth/states/tokenPairState';
import { CommentThreadTarget } from '~/generated/graphql';
import { ApolloFactory } from '../services/apollo.factory';
export function useApolloFactory() {
const apolloRef = useRef<ApolloFactory<NormalizedCacheObject> | null>(null);
const [tokenPair, setTokenPair] = useRecoilState(tokenPairState);
const apolloClient = useMemo(() => {
apolloRef.current = new ApolloFactory({
uri: `${process.env.REACT_APP_API_URL}`,
cache: new InMemoryCache({
typePolicies: {
CommentThread: {
fields: {
commentThreadTargets: {
merge(
existing: CommentThreadTarget[] = [],
incoming: CommentThreadTarget[],
) {
return [...incoming];
},
},
},
},
},
}),
defaultOptions: {
query: {
fetchPolicy: 'cache-first',
},
},
onTokenPairChange(tokenPair) {
setTokenPair(tokenPair);
},
onUnauthenticatedError() {
setTokenPair(null);
},
});
return apolloRef.current.getClient();
}, [setTokenPair]);
useEffect(() => {
if (apolloRef.current) {
apolloRef.current.updateTokenPair(tokenPair);
}
}, [tokenPair]);
return apolloClient;
}

View File

@ -0,0 +1,44 @@
import { useMemo } from 'react';
import {
ApolloClient,
ApolloLink,
createHttpLink,
from,
InMemoryCache,
} from '@apollo/client';
import { mockedCompaniesData } from '~/testing/mock-data/companies';
import { mockedUsersData } from '~/testing/mock-data/users';
export default function useApolloMocked() {
const mockedClient = useMemo(() => {
const apiLink = createHttpLink({
uri: `${process.env.REACT_APP_API_URL}`,
});
const mockLink = new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
if (operation.operationName === 'GetCompanies') {
return { data: { companies: mockedCompaniesData } };
}
if (operation.operationName === 'GetCurrentUser') {
return { data: { users: [mockedUsersData[0]] } };
}
return response;
});
});
return new ApolloClient({
link: from([mockLink, apiLink]),
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: 'cache-first',
},
},
});
}, []);
return mockedClient;
}

View File

@ -0,0 +1,8 @@
import { ApolloClient } from '@apollo/client';
import { AuthTokenPair } from '~/generated/graphql';
export interface ApolloManager<TCacheShape> {
getClient(): ApolloClient<TCacheShape>;
updateTokenPair(tokenPair: AuthTokenPair | null): void;
}

View File

@ -0,0 +1,172 @@
/* eslint-disable no-loop-func */
import {
ApolloClient,
ApolloClientOptions,
ApolloLink,
createHttpLink,
ServerError,
ServerParseError,
} from '@apollo/client';
import { GraphQLErrors } from '@apollo/client/errors';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
import { RetryLink } from '@apollo/client/link/retry';
import { Observable } from '@apollo/client/utilities';
import { renewToken } from '@/auth/services/AuthService';
import { AuthTokenPair } from '~/generated/graphql';
import { loggerLink } from '../../utils/apollo-logger';
import { assertNotNull } from '../../utils/assert';
import { promiseToObservable } from '../../utils/promise-to-observable';
import { ApolloManager } from '../interfaces/apolloManager.interface';
const logger = loggerLink(() => 'Twenty');
let isRefreshing = false;
let pendingRequests: (() => void)[] = [];
const resolvePendingRequests = () => {
pendingRequests.map((callback) => callback());
pendingRequests = [];
};
export interface Options<TCacheShape> extends ApolloClientOptions<TCacheShape> {
onError?: (err: GraphQLErrors | undefined) => void;
onNetworkError?: (err: Error | ServerParseError | ServerError) => void;
onTokenPairChange?: (tokenPair: AuthTokenPair) => void;
onUnauthenticatedError?: () => void;
}
export class ApolloFactory<TCacheShape> implements ApolloManager<TCacheShape> {
private client: ApolloClient<TCacheShape>;
private tokenPair: AuthTokenPair | null = null;
constructor(opts: Options<TCacheShape>) {
const {
uri,
onError: onErrorCb,
onNetworkError,
onTokenPairChange,
onUnauthenticatedError,
...options
} = opts;
const buildApolloLink = (): ApolloLink => {
const httpLink = createHttpLink({
uri,
});
const authLink = setContext(async (_, { headers }) => {
return {
headers: {
...headers,
authorization: this.tokenPair?.accessToken.token
? `Bearer ${this.tokenPair?.accessToken.token}`
: '',
},
};
});
const retryLink = new RetryLink({
delay: {
initial: 100,
},
attempts: {
max: 2,
retryIf: (error) => !!error,
},
});
const errorLink = onError(
({ graphQLErrors, networkError, forward, operation }) => {
if (graphQLErrors) {
onErrorCb?.(graphQLErrors);
for (const graphQLError of graphQLErrors) {
switch (graphQLError?.extensions?.code) {
case 'UNAUTHENTICATED': {
// error code is set to UNAUTHENTICATED
// when AuthenticationError thrown in resolver
let forward$: Observable<boolean>;
if (!isRefreshing) {
isRefreshing = true;
forward$ = promiseToObservable(
renewToken(uri, this.tokenPair)
.then((tokens) => {
onTokenPairChange?.(tokens);
resolvePendingRequests();
return true;
})
.catch(() => {
pendingRequests = [];
onUnauthenticatedError?.();
return false;
})
.finally(() => {
isRefreshing = false;
}),
).filter((value) => Boolean(value));
} else {
// Will only emit once the Promise is resolved
forward$ = promiseToObservable(
new Promise<boolean>((resolve) => {
pendingRequests.push(() => resolve(true));
}),
);
}
return forward$.flatMap(() => forward(operation));
}
default:
if (process.env.NODE_ENV === 'development') {
console.warn(
`[GraphQL error]: Message: ${
graphQLError.message
}, Location: ${
graphQLError.locations
? JSON.stringify(graphQLError.locations)
: graphQLError.locations
}, Path: ${graphQLError.path}`,
);
}
}
}
}
if (networkError) {
if (process.env.NODE_ENV === 'development') {
console.warn(`[Network error]: ${networkError}`);
}
onNetworkError?.(networkError);
}
},
);
return ApolloLink.from(
[
errorLink,
authLink,
// Only show logger in dev mode
process.env.NODE_ENV !== 'production' ? logger : null,
retryLink,
httpLink,
].filter(assertNotNull),
);
};
this.client = new ApolloClient({
...options,
link: buildApolloLink(),
});
}
updateTokenPair(tokenPair: AuthTokenPair | null) {
this.tokenPair = tokenPair;
}
getClient() {
return this.client;
}
}

View File

@ -3,11 +3,12 @@ import { useRecoilState } from 'recoil';
import { useChallengeMutation, useVerifyMutation } from '~/generated/graphql';
import { tokenService } from '../services/TokenService';
import { currentUserState } from '../states/currentUserState';
import { isAuthenticatingState } from '../states/isAuthenticatingState';
import { tokenPairState } from '../states/tokenPairState';
export function useAuth() {
const [, setTokenPair] = useRecoilState(tokenPairState);
const [, setCurrentUser] = useRecoilState(currentUserState);
const [, setIsAuthenticating] = useRecoilState(isAuthenticatingState);
@ -50,14 +51,14 @@ export function useAuth() {
throw new Error('No verify result');
}
tokenService.setTokenPair(verifyResult.data?.verify.tokens);
setTokenPair(verifyResult.data?.verify.tokens);
setIsAuthenticating(false);
setCurrentUser(verifyResult.data?.verify.user);
return verifyResult.data?.verify;
},
[setCurrentUser, setIsAuthenticating, verify],
[setCurrentUser, setIsAuthenticating, setTokenPair, verify],
);
const handleLogin = useCallback(
@ -70,8 +71,8 @@ export function useAuth() {
);
const handleLogout = useCallback(() => {
tokenService.removeTokenPair();
}, []);
setTokenPair(null);
}, [setTokenPair]);
return {
challenge: handleChallenge,

View File

@ -0,0 +1,26 @@
import { useEffect } from 'react';
import jwt from 'jwt-decode';
import { useRecoilState } from 'recoil';
import { useGetCurrentUserQuery } from '~/generated/graphql';
import { currentUserState } from '../states/currentUserState';
import { tokenPairState } from '../states/tokenPairState';
export function useFetchCurrentUser() {
const [, setCurrentUser] = useRecoilState(currentUserState);
const [tokenPair] = useRecoilState(tokenPairState);
const userId = tokenPair?.accessToken.token
? jwt<{ sub: string }>(tokenPair.accessToken.token).sub
: null;
const { data } = useGetCurrentUserQuery({
variables: { uuid: userId },
});
const user = data?.users?.[0];
useEffect(() => {
if (user) {
setCurrentUser(user);
}
}, [user, setCurrentUser]);
}

View File

@ -1,21 +1,9 @@
import { useEffect, useState } from 'react';
import { useRecoilState } from 'recoil';
import { cookieStorage } from '@/utils/cookie-storage';
import { tokenPairState } from '../states/tokenPairState';
export function useIsLogged(): boolean {
const [value, setValue] = useState<string | undefined>(
cookieStorage.getItem('accessToken'),
);
const [tokenPair] = useRecoilState(tokenPairState);
useEffect(() => {
const updateValue = (newValue: string | undefined) => setValue(newValue);
cookieStorage.addEventListener('accessToken', updateValue);
return () => {
cookieStorage.removeEventListener('accessToken', updateValue);
};
}, []);
return !!value;
return !!tokenPair;
}

View File

@ -5,17 +5,14 @@ import {
InMemoryCache,
UriFunction,
} from '@apollo/client';
import jwt from 'jwt-decode';
import { cookieStorage } from '@/utils/cookie-storage';
import { loggerLink } from '@/utils/apollo-logger';
import {
AuthTokenPair,
RenewTokenDocument,
RenewTokenMutation,
RenewTokenMutationVariables,
} from '~/generated/graphql';
import { loggerLink } from '~/providers/apollo/logger';
import { tokenService } from './TokenService';
const logger = loggerLink(() => 'Twenty-Refresh');
@ -60,29 +57,15 @@ const renewTokenMutation = async (
* @param uri string | UriFunction | undefined
* @returns TokenPair
*/
export const renewToken = async (uri: string | UriFunction | undefined) => {
const tokenPair = tokenService.getTokenPair();
export const renewToken = async (
uri: string | UriFunction | undefined,
tokenPair: AuthTokenPair | undefined | null,
) => {
if (!tokenPair) {
throw new Error('Refresh token is not defined');
}
const data = await renewTokenMutation(uri, tokenPair.refreshToken);
const data = await renewTokenMutation(uri, tokenPair.refreshToken.token);
tokenService.setTokenPair(data.renewToken.tokens);
return data.renewToken;
};
export const getUserIdFromToken: () => string | null = () => {
const accessToken = cookieStorage.getItem('accessToken');
if (!accessToken) {
return null;
}
try {
return jwt<{ sub: string }>(accessToken).sub;
} catch (error) {
return null;
}
return data.renewToken.tokens;
};

View File

@ -1,34 +0,0 @@
import { cookieStorage } from '@/utils/cookie-storage';
import { AuthTokenPair } from '~/generated/graphql';
export class TokenService {
getTokenPair() {
const accessToken = cookieStorage.getItem('accessToken');
const refreshToken = cookieStorage.getItem('refreshToken');
if (!accessToken || !refreshToken) {
return null;
}
return {
accessToken,
refreshToken,
};
}
setTokenPair(tokens: AuthTokenPair) {
cookieStorage.setItem('accessToken', tokens.accessToken.token, {
secure: true,
});
cookieStorage.setItem('refreshToken', tokens.refreshToken.token, {
secure: true,
});
}
removeTokenPair() {
cookieStorage.removeItem('accessToken');
cookieStorage.removeItem('refreshToken');
}
}
export const tokenService = new TokenService();

View File

@ -1,27 +0,0 @@
import { cookieStorage } from '@/utils/cookie-storage';
import { getUserIdFromToken } from '../AuthService';
it('getUserIdFromToken returns null when the token is not present', async () => {
const userId = getUserIdFromToken();
expect(userId).toBeNull();
});
it('getUserIdFromToken returns null when the token is not valid', async () => {
cookieStorage.setItem('accessToken', 'xxx-invalid-access');
const userId = getUserIdFromToken();
expect(userId).toBeNull();
});
it('getUserIdFromToken returns the right userId when the token is valid', async () => {
cookieStorage.setItem(
'accessToken',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzNzRmZTNhNS1kZjFlLTQxMTktYWZlMC0yYTYyYTJiYTQ4MWUiLCJ3b3Jrc3BhY2VJZCI6InR3ZW50eS03ZWQ5ZDIxMi0xYzI1LTRkMDItYmYyNS02YWVjY2Y3ZWE0MTkiLCJpYXQiOjE2ODY5OTI0ODgsImV4cCI6MTY4Njk5Mjc4OH0.IO7U5G14IrrQriw3JjrKVxmZgd6XKL6yUIwuNe_R55E',
);
const userId = getUserIdFromToken();
expect(userId).toBe('374fe3a5-df1e-4119-afe0-2a62a2ba481e');
});
afterEach(() => {
cookieStorage.clear();
});

View File

@ -1,43 +0,0 @@
import Cookies from 'js-cookie';
import { tokenService } from '../TokenService';
const tokenPair = {
accessToken: {
token:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzNzRmZTNhNS1kZjFlLTQxMTktYWZlMC0yYTYyYTJiYTQ4MWUiLCJ3b3Jrc3BhY2VJZCI6InR3ZW50eS03ZWQ5ZDIxMi0xYzI1LTRkMDItYmYyNS02YWVjY2Y3ZWE0MTkiLCJpYXQiOjE2ODY5OTMxODIsImV4cCI6MTY4Njk5MzQ4Mn0.F_FD6nJ5fssR_47v2XFhtzqjr-wrEQpqaWVq8iIlLJw',
expiresAt: '2023-06-17T09:18:02.942Z',
},
refreshToken: {
token:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzNzRmZTNhNS1kZjFlLTQxMTktYWZlMC0yYTYyYTJiYTQ4MWUiLCJpYXQiOjE2ODY5OTMxODIsImV4cCI6OTQ2Mjk5MzE4MiwianRpIjoiNzBmMWNhMjctOTYxYi00ZGZlLWEwOTUtMTY2OWEwOGViMTVjIn0.xEdX9dOGzrPHrPsivQYB9ipYGJH-mJ7GSIVPacmIzfY',
expiresAt: '2023-09-15T09:13:02.952Z',
},
};
it('getTokenPair is fullfiled when token is present', () => {
tokenService.setTokenPair(tokenPair);
// Otherwise the test will fail because Cookies-js seems to be async but functions aren't promises
setTimeout(() => {
expect(tokenService.getTokenPair()).toBe({
accessToken: tokenPair.accessToken,
refreshToken: tokenPair.refreshToken,
});
}, 10);
});
it('getTokenPair is null when token is not set', () => {
expect(tokenService.getTokenPair()).toBeNull();
});
it('removeTokenPair clean cookie storage', () => {
tokenService.setTokenPair(tokenPair);
tokenService.removeTokenPair();
expect(tokenService.getTokenPair()).toBeNull();
});
afterEach(() => {
Cookies.remove('accessToken');
Cookies.remove('refreshToken');
});

View File

@ -0,0 +1,29 @@
import { atom, AtomEffect } from 'recoil';
import { cookieStorage } from '@/utils/cookie-storage';
import { AuthTokenPair } from '~/generated/graphql';
const cookieStorageEffect =
(key: string): AtomEffect<AuthTokenPair | null> =>
({ setSelf, onSet }) => {
const savedValue = cookieStorage.getItem(key);
if (savedValue != null) {
setSelf(JSON.parse(savedValue));
}
onSet((newValue, _, isReset) => {
if (!newValue) {
cookieStorage.removeItem(key);
return;
}
isReset
? cookieStorage.removeItem(key)
: cookieStorage.setItem(key, JSON.stringify(newValue));
});
};
export const tokenPairState = atom<AuthTokenPair | null>({
key: 'tokenPairState',
default: null,
effects: [cookieStorageEffect('tokenPair')],
});

View File

@ -0,0 +1,45 @@
import { OperationType } from './operation-type';
const operationTypeColors = {
query: '#03A9F4',
mutation: '#61A600',
subscription: '#61A600',
error: '#F51818',
default: '#61A600',
};
const getOperationColor = (operationType: OperationType) => {
return operationTypeColors[operationType] ?? operationTypeColors.default;
};
const formatTitle = (
operationType: OperationType,
schemaName: string,
queryName: string,
time: string | number,
) => {
const headerCss = [
'color: gray; font-weight: lighter', // title
`color: ${getOperationColor(operationType)}; font-weight: bold;`, // operationType
'color: gray; font-weight: lighter;', // schemaName
'color: black; font-weight: bold;', // queryName
];
const parts = [
'%c apollo',
`%c${operationType}`,
`%c${schemaName}::%c${queryName}`,
];
if (operationType !== OperationType.Subscription) {
parts.push(`%c(in ${time} ms)`);
headerCss.push('color: gray; font-weight: lighter;'); // time
} else {
parts.push(`%c(@ ${time})`);
headerCss.push('color: gray; font-weight: lighter;'); // time
}
return [parts.join(' '), ...headerCss];
};
export default formatTitle;

View File

@ -0,0 +1,102 @@
import { ApolloLink, gql, Operation } from '@apollo/client';
import formatTitle from './format-title';
const getGroup = (collapsed: boolean) =>
collapsed
? console.groupCollapsed.bind(console)
: console.group.bind(console);
const parseQuery = (queryString: string) => {
const queryObj = gql`
${queryString}
`;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { name } = queryObj.definitions[0] as any;
return [name ? name.value : 'Generic', queryString.trim()];
};
export const loggerLink = (getSchemaName: (operation: Operation) => string) =>
new ApolloLink((operation, forward) => {
const schemaName = getSchemaName(operation);
operation.setContext({ start: Date.now() });
const { variables } = operation;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const operationType = (operation.query.definitions[0] as any).operation;
const headers = operation.getContext().headers;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const [queryName, query] = parseQuery(operation.query.loc!.source.body);
if (operationType === 'subscription') {
const date = new Date().toLocaleTimeString();
const titleArgs = formatTitle(operationType, schemaName, queryName, date);
console.groupCollapsed(...titleArgs);
if (variables && Object.keys(variables).length !== 0) {
console.log('VARIABLES', variables);
}
console.log('QUERY', query);
console.groupEnd();
return forward(operation);
}
return forward(operation).map((result) => {
const time = Date.now() - operation.getContext().start;
const errors = result.errors ?? result.data?.[queryName]?.errors;
const hasError = Boolean(errors);
try {
const titleArgs = formatTitle(
operationType,
schemaName,
queryName,
time,
);
getGroup(!hasError)(...titleArgs);
if (errors) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
errors.forEach((err: any) => {
console.log(
`%c${err.message}`,
'color: #F51818; font-weight: lighter',
);
});
}
console.log('HEADERS: ', headers);
if (variables && Object.keys(variables).length !== 0) {
console.log('VARIABLES', variables);
}
console.log('QUERY', query);
if (result.data) {
console.log('RESULT', result.data);
}
if (errors) {
console.log('ERRORS', errors);
}
console.groupEnd();
} catch {
// this may happen if console group is not supported
console.log(
`${operationType} ${schemaName}::${queryName} (in ${time} ms)`,
);
if (errors) {
console.error(errors);
}
}
return result;
});
});

View File

@ -0,0 +1,6 @@
export enum OperationType {
Query = 'query',
Mutation = 'mutation',
Subscription = 'subscription',
Error = 'error',
}

View File

@ -1,12 +1,6 @@
import Cookies, { CookieAttributes } from 'js-cookie';
type Listener = (
newValue: string | undefined,
oldValue: string | undefined,
) => void;
class CookieStorage {
private listeners: Record<string, Listener[]> = {};
private keys: Set<string> = new Set();
getItem(key: string): string | undefined {
@ -14,49 +8,18 @@ class CookieStorage {
}
setItem(key: string, value: string, attributes?: CookieAttributes): void {
const oldValue = this.getItem(key);
this.keys.add(key);
Cookies.set(key, value, attributes);
this.dispatch(key, value, oldValue);
}
removeItem(key: string): void {
const oldValue = this.getItem(key);
this.keys.delete(key);
Cookies.remove(key);
this.dispatch(key, undefined, oldValue);
}
clear(): void {
this.keys.forEach((key) => this.removeItem(key));
}
private dispatch(
key: string,
newValue: string | undefined,
oldValue: string | undefined,
): void {
if (this.listeners[key]) {
this.listeners[key].forEach((callback) => callback(newValue, oldValue));
}
}
addEventListener(key: string, callback: Listener): void {
if (!this.listeners[key]) {
this.listeners[key] = [];
}
this.listeners[key].push(callback);
}
removeEventListener(key: string, callback: Listener): void {
if (this.listeners[key]) {
this.listeners[key] = this.listeners[key].filter(
(listener) => listener !== callback,
);
}
}
}
export const cookieStorage = new CookieStorage();