Rename Unintuitive Function Names in Authentication Flow (#9706)

Resolves #9623

## Description

This PR renames the following functions to better reflect their purpose.

- Backend:
  - Verify → GetAuthTokensFromLoginToken
  - Challenge → GetLoginTokenFromCredentials

- Frontend:
  - challenge → getLoginTokenFromCredentials
  - verify → getAuthTokensFromLoginToken

## Testing
_Sign in works as expected:_


https://github.com/user-attachments/assets/7e8f73c7-2c7d-4cd2-9965-5ad9f5334cd3

_Sign up works as expected:_
  

https://github.com/user-attachments/assets/d1794ee4-8b59-4934-84df-d819eabd5224

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
This commit is contained in:
Samyak Piya
2025-01-24 13:19:14 -05:00
committed by GitHub
parent 570b2e3530
commit 55be726105
19 changed files with 300 additions and 259 deletions

View File

@ -10,6 +10,7 @@ module.exports = {
'./src/modules/**/*.tsx',
'./src/modules/**/*.ts',
'!./src/**/*.test.tsx',
'!./src/**/*.stories.tsx',
'!./src/**/__mocks__/*.ts',
'!./src/modules/users/graphql/queries/getCurrentUserAndViews.ts',
],

View File

@ -463,6 +463,7 @@ export enum FeatureFlagKey {
IsJsonFilterEnabled = 'IsJsonFilterEnabled',
IsLocalizationEnabled = 'IsLocalizationEnabled',
IsMicrosoftSyncEnabled = 'IsMicrosoftSyncEnabled',
IsNewRelationEnabled = 'IsNewRelationEnabled',
IsPostgreSQLIntegrationEnabled = 'IsPostgreSQLIntegrationEnabled',
IsStripeIntegrationEnabled = 'IsStripeIntegrationEnabled',
IsUniqueIndexesEnabled = 'IsUniqueIndexesEnabled',
@ -629,7 +630,6 @@ export type Mutation = {
activateWorkflowVersion: Scalars['Boolean']['output'];
activateWorkspace: Workspace;
authorizeApp: AuthorizeApp;
challenge: LoginToken;
checkoutSession: BillingSessionOutput;
computeStepOutputSchema: Scalars['JSON']['output'];
createDraftFromWorkflowVersion: WorkflowVersion;
@ -660,7 +660,9 @@ export type Mutation = {
executeOneServerlessFunction: ServerlessFunctionExecutionResult;
generateApiKeyToken: ApiKeyToken;
generateTransientToken: TransientToken;
getAuthTokensFromLoginToken: AuthTokens;
getAuthorizationUrl: GetAuthorizationUrlOutput;
getLoginTokenFromCredentials: LoginToken;
getLoginTokenFromEmailVerificationToken: LoginToken;
impersonate: ImpersonateOutput;
publishServerlessFunction: ServerlessFunction;
@ -690,7 +692,6 @@ export type Mutation = {
uploadProfilePicture: Scalars['String']['output'];
uploadWorkspaceLogo: Scalars['String']['output'];
userLookupAdminPanel: UserLookup;
verify: AuthTokens;
};
@ -711,13 +712,6 @@ export type MutationAuthorizeAppArgs = {
};
export type MutationChallengeArgs = {
captchaToken?: InputMaybe<Scalars['String']['input']>;
email: Scalars['String']['input'];
password: Scalars['String']['input'];
};
export type MutationCheckoutSessionArgs = {
plan?: BillingPlanKey;
recurringInterval: SubscriptionInterval;
@ -847,11 +841,23 @@ export type MutationGenerateApiKeyTokenArgs = {
};
export type MutationGetAuthTokensFromLoginTokenArgs = {
loginToken: Scalars['String']['input'];
};
export type MutationGetAuthorizationUrlArgs = {
input: GetAuthorizationUrlInput;
};
export type MutationGetLoginTokenFromCredentialsArgs = {
captchaToken?: InputMaybe<Scalars['String']['input']>;
email: Scalars['String']['input'];
password: Scalars['String']['input'];
};
export type MutationGetLoginTokenFromEmailVerificationTokenArgs = {
captchaToken?: InputMaybe<Scalars['String']['input']>;
emailVerificationToken: Scalars['String']['input'];
@ -999,11 +1005,6 @@ export type MutationUserLookupAdminPanelArgs = {
userIdentifier: Scalars['String']['input'];
};
export type MutationVerifyArgs = {
loginToken: Scalars['String']['input'];
};
export type ObjectConnection = {
__typename?: 'ObjectConnection';
/** Array of edges. */
@ -1300,6 +1301,13 @@ export enum RelationMetadataType {
ONE_TO_ONE = 'ONE_TO_ONE'
}
/** Relation type */
export enum RelationType {
MANY_TO_ONE = 'MANY_TO_ONE',
ONE_TO_MANY = 'ONE_TO_MANY',
ONE_TO_ONE = 'ONE_TO_ONE'
}
export type RemoteServer = {
__typename?: 'RemoteServer';
createdAt: Scalars['DateTime']['output'];
@ -1898,6 +1906,7 @@ export type Field = {
name: Scalars['String']['output'];
object?: Maybe<Object>;
options?: Maybe<Scalars['JSON']['output']>;
relation?: Maybe<Relation>;
relationDefinition?: Maybe<RelationDefinition>;
settings?: Maybe<Scalars['JSON']['output']>;
toRelationMetadata?: Maybe<Relation>;

View File

@ -1,5 +1,5 @@
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
import { gql } from '@apollo/client';
export type Maybe<T> = T | null;
export type InputMaybe<T> = Maybe<T>;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
@ -395,6 +395,7 @@ export enum FeatureFlagKey {
IsJsonFilterEnabled = 'IsJsonFilterEnabled',
IsLocalizationEnabled = 'IsLocalizationEnabled',
IsMicrosoftSyncEnabled = 'IsMicrosoftSyncEnabled',
IsNewRelationEnabled = 'IsNewRelationEnabled',
IsPostgreSQLIntegrationEnabled = 'IsPostgreSQLIntegrationEnabled',
IsStripeIntegrationEnabled = 'IsStripeIntegrationEnabled',
IsUniqueIndexesEnabled = 'IsUniqueIndexesEnabled',
@ -554,7 +555,6 @@ export type Mutation = {
activateWorkflowVersion: Scalars['Boolean'];
activateWorkspace: Workspace;
authorizeApp: AuthorizeApp;
challenge: LoginToken;
checkoutSession: BillingSessionOutput;
computeStepOutputSchema: Scalars['JSON'];
createDraftFromWorkflowVersion: WorkflowVersion;
@ -581,7 +581,9 @@ export type Mutation = {
executeOneServerlessFunction: ServerlessFunctionExecutionResult;
generateApiKeyToken: ApiKeyToken;
generateTransientToken: TransientToken;
getAuthTokensFromLoginToken: AuthTokens;
getAuthorizationUrl: GetAuthorizationUrlOutput;
getLoginTokenFromCredentials: LoginToken;
getLoginTokenFromEmailVerificationToken: LoginToken;
impersonate: ImpersonateOutput;
publishServerlessFunction: ServerlessFunction;
@ -607,7 +609,6 @@ export type Mutation = {
uploadProfilePicture: Scalars['String'];
uploadWorkspaceLogo: Scalars['String'];
userLookupAdminPanel: UserLookup;
verify: AuthTokens;
};
@ -628,13 +629,6 @@ export type MutationAuthorizeAppArgs = {
};
export type MutationChallengeArgs = {
captchaToken?: InputMaybe<Scalars['String']>;
email: Scalars['String'];
password: Scalars['String'];
};
export type MutationCheckoutSessionArgs = {
plan?: BillingPlanKey;
recurringInterval: SubscriptionInterval;
@ -734,11 +728,23 @@ export type MutationGenerateApiKeyTokenArgs = {
};
export type MutationGetAuthTokensFromLoginTokenArgs = {
loginToken: Scalars['String'];
};
export type MutationGetAuthorizationUrlArgs = {
input: GetAuthorizationUrlInput;
};
export type MutationGetLoginTokenFromCredentialsArgs = {
captchaToken?: InputMaybe<Scalars['String']>;
email: Scalars['String'];
password: Scalars['String'];
};
export type MutationGetLoginTokenFromEmailVerificationTokenArgs = {
captchaToken?: InputMaybe<Scalars['String']>;
emailVerificationToken: Scalars['String'];
@ -866,11 +872,6 @@ export type MutationUserLookupAdminPanelArgs = {
userIdentifier: Scalars['String'];
};
export type MutationVerifyArgs = {
loginToken: Scalars['String'];
};
export type ObjectConnection = {
__typename?: 'ObjectConnection';
/** Array of edges. */
@ -1070,6 +1071,15 @@ export type QueryValidatePasswordResetTokenArgs = {
passwordResetToken: Scalars['String'];
};
export type Relation = {
__typename?: 'Relation';
sourceFieldMetadata: Field;
sourceObjectMetadata: Object;
targetFieldMetadata: Field;
targetObjectMetadata: Object;
type: RelationType;
};
export type RelationConnection = {
__typename?: 'RelationConnection';
/** Array of edges. */
@ -1104,6 +1114,13 @@ export enum RelationMetadataType {
ONE_TO_ONE = 'ONE_TO_ONE'
}
/** Relation type */
export enum RelationType {
MANY_TO_ONE = 'MANY_TO_ONE',
ONE_TO_MANY = 'ONE_TO_MANY',
ONE_TO_ONE = 'ONE_TO_ONE'
}
export type RemoteServer = {
__typename?: 'RemoteServer';
createdAt: Scalars['DateTime'];
@ -1670,6 +1687,7 @@ export type Field = {
name: Scalars['String'];
object?: Maybe<Object>;
options?: Maybe<Scalars['JSON']>;
relation?: Maybe<Relation>;
relationDefinition?: Maybe<RelationDefinition>;
settings?: Maybe<Scalars['JSON']>;
toRelationMetadata?: Maybe<Relation>;
@ -1813,20 +1831,6 @@ export type ObjectFilter = {
or?: InputMaybe<Array<ObjectFilter>>;
};
export type Relation = {
__typename?: 'relation';
createdAt: Scalars['DateTime'];
fromFieldMetadataId: Scalars['String'];
fromObjectMetadata: Object;
fromObjectMetadataId: Scalars['String'];
id: Scalars['UUID'];
relationType: RelationMetadataType;
toFieldMetadataId: Scalars['String'];
toObjectMetadata: Object;
toObjectMetadataId: Scalars['String'];
updatedAt: Scalars['DateTime'];
};
export type RelationEdge = {
__typename?: 'relationEdge';
/** Cursor for this node. */
@ -1922,15 +1926,6 @@ export type AuthorizeAppMutationVariables = Exact<{
export type AuthorizeAppMutation = { __typename?: 'Mutation', authorizeApp: { __typename?: 'AuthorizeApp', redirectUrl: string } };
export type ChallengeMutationVariables = Exact<{
email: Scalars['String'];
password: Scalars['String'];
captchaToken?: InputMaybe<Scalars['String']>;
}>;
export type ChallengeMutation = { __typename?: 'Mutation', challenge: { __typename?: 'LoginToken', loginToken: { __typename?: 'AuthToken', token: string, expiresAt: string } } };
export type EmailPasswordResetLinkMutationVariables = Exact<{
email: Scalars['String'];
}>;
@ -1951,6 +1946,13 @@ export type GenerateTransientTokenMutationVariables = Exact<{ [key: string]: nev
export type GenerateTransientTokenMutation = { __typename?: 'Mutation', generateTransientToken: { __typename?: 'TransientToken', transientToken: { __typename?: 'AuthToken', token: string } } };
export type GetAuthTokensFromLoginTokenMutationVariables = Exact<{
loginToken: Scalars['String'];
}>;
export type GetAuthTokensFromLoginTokenMutation = { __typename?: 'Mutation', getAuthTokensFromLoginToken: { __typename?: 'AuthTokens', tokens: { __typename?: 'AuthTokenPair', accessToken: { __typename?: 'AuthToken', token: string, expiresAt: string }, refreshToken: { __typename?: 'AuthToken', token: string, expiresAt: string } } } };
export type GetAuthorizationUrlMutationVariables = Exact<{
input: GetAuthorizationUrlInput;
}>;
@ -1958,6 +1960,15 @@ export type GetAuthorizationUrlMutationVariables = Exact<{
export type GetAuthorizationUrlMutation = { __typename?: 'Mutation', getAuthorizationUrl: { __typename?: 'GetAuthorizationUrlOutput', id: string, type: string, authorizationURL: string } };
export type GetLoginTokenFromCredentialsMutationVariables = Exact<{
email: Scalars['String'];
password: Scalars['String'];
captchaToken?: InputMaybe<Scalars['String']>;
}>;
export type GetLoginTokenFromCredentialsMutation = { __typename?: 'Mutation', getLoginTokenFromCredentials: { __typename?: 'LoginToken', loginToken: { __typename?: 'AuthToken', token: string, expiresAt: string } } };
export type GetLoginTokenFromEmailVerificationTokenMutationVariables = Exact<{
emailVerificationToken: Scalars['String'];
captchaToken?: InputMaybe<Scalars['String']>;
@ -2008,13 +2019,6 @@ export type UpdatePasswordViaResetTokenMutationVariables = Exact<{
export type UpdatePasswordViaResetTokenMutation = { __typename?: 'Mutation', updatePasswordViaResetToken: { __typename?: 'InvalidatePassword', success: boolean } };
export type VerifyMutationVariables = Exact<{
loginToken: Scalars['String'];
}>;
export type VerifyMutation = { __typename?: 'Mutation', verify: { __typename?: 'AuthTokens', tokens: { __typename?: 'AuthTokenPair', accessToken: { __typename?: 'AuthToken', token: string, expiresAt: string }, refreshToken: { __typename?: 'AuthToken', token: string, expiresAt: string } } } };
export type CheckUserExistsQueryVariables = Exact<{
email: Scalars['String'];
captchaToken?: InputMaybe<Scalars['String']>;
@ -2748,43 +2752,6 @@ export function useAuthorizeAppMutation(baseOptions?: Apollo.MutationHookOptions
export type AuthorizeAppMutationHookResult = ReturnType<typeof useAuthorizeAppMutation>;
export type AuthorizeAppMutationResult = Apollo.MutationResult<AuthorizeAppMutation>;
export type AuthorizeAppMutationOptions = Apollo.BaseMutationOptions<AuthorizeAppMutation, AuthorizeAppMutationVariables>;
export const ChallengeDocument = gql`
mutation Challenge($email: String!, $password: String!, $captchaToken: String) {
challenge(email: $email, password: $password, captchaToken: $captchaToken) {
loginToken {
...AuthTokenFragment
}
}
}
${AuthTokenFragmentFragmentDoc}`;
export type ChallengeMutationFn = Apollo.MutationFunction<ChallengeMutation, ChallengeMutationVariables>;
/**
* __useChallengeMutation__
*
* To run a mutation, you first call `useChallengeMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useChallengeMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [challengeMutation, { data, loading, error }] = useChallengeMutation({
* variables: {
* email: // value for 'email'
* password: // value for 'password'
* captchaToken: // value for 'captchaToken'
* },
* });
*/
export function useChallengeMutation(baseOptions?: Apollo.MutationHookOptions<ChallengeMutation, ChallengeMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useMutation<ChallengeMutation, ChallengeMutationVariables>(ChallengeDocument, options);
}
export type ChallengeMutationHookResult = ReturnType<typeof useChallengeMutation>;
export type ChallengeMutationResult = Apollo.MutationResult<ChallengeMutation>;
export type ChallengeMutationOptions = Apollo.BaseMutationOptions<ChallengeMutation, ChallengeMutationVariables>;
export const EmailPasswordResetLinkDocument = gql`
mutation EmailPasswordResetLink($email: String!) {
emailPasswordResetLink(email: $email) {
@ -2886,6 +2853,41 @@ export function useGenerateTransientTokenMutation(baseOptions?: Apollo.MutationH
export type GenerateTransientTokenMutationHookResult = ReturnType<typeof useGenerateTransientTokenMutation>;
export type GenerateTransientTokenMutationResult = Apollo.MutationResult<GenerateTransientTokenMutation>;
export type GenerateTransientTokenMutationOptions = Apollo.BaseMutationOptions<GenerateTransientTokenMutation, GenerateTransientTokenMutationVariables>;
export const GetAuthTokensFromLoginTokenDocument = gql`
mutation GetAuthTokensFromLoginToken($loginToken: String!) {
getAuthTokensFromLoginToken(loginToken: $loginToken) {
tokens {
...AuthTokensFragment
}
}
}
${AuthTokensFragmentFragmentDoc}`;
export type GetAuthTokensFromLoginTokenMutationFn = Apollo.MutationFunction<GetAuthTokensFromLoginTokenMutation, GetAuthTokensFromLoginTokenMutationVariables>;
/**
* __useGetAuthTokensFromLoginTokenMutation__
*
* To run a mutation, you first call `useGetAuthTokensFromLoginTokenMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useGetAuthTokensFromLoginTokenMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [getAuthTokensFromLoginTokenMutation, { data, loading, error }] = useGetAuthTokensFromLoginTokenMutation({
* variables: {
* loginToken: // value for 'loginToken'
* },
* });
*/
export function useGetAuthTokensFromLoginTokenMutation(baseOptions?: Apollo.MutationHookOptions<GetAuthTokensFromLoginTokenMutation, GetAuthTokensFromLoginTokenMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useMutation<GetAuthTokensFromLoginTokenMutation, GetAuthTokensFromLoginTokenMutationVariables>(GetAuthTokensFromLoginTokenDocument, options);
}
export type GetAuthTokensFromLoginTokenMutationHookResult = ReturnType<typeof useGetAuthTokensFromLoginTokenMutation>;
export type GetAuthTokensFromLoginTokenMutationResult = Apollo.MutationResult<GetAuthTokensFromLoginTokenMutation>;
export type GetAuthTokensFromLoginTokenMutationOptions = Apollo.BaseMutationOptions<GetAuthTokensFromLoginTokenMutation, GetAuthTokensFromLoginTokenMutationVariables>;
export const GetAuthorizationUrlDocument = gql`
mutation GetAuthorizationUrl($input: GetAuthorizationUrlInput!) {
getAuthorizationUrl(input: $input) {
@ -2921,6 +2923,47 @@ export function useGetAuthorizationUrlMutation(baseOptions?: Apollo.MutationHook
export type GetAuthorizationUrlMutationHookResult = ReturnType<typeof useGetAuthorizationUrlMutation>;
export type GetAuthorizationUrlMutationResult = Apollo.MutationResult<GetAuthorizationUrlMutation>;
export type GetAuthorizationUrlMutationOptions = Apollo.BaseMutationOptions<GetAuthorizationUrlMutation, GetAuthorizationUrlMutationVariables>;
export const GetLoginTokenFromCredentialsDocument = gql`
mutation GetLoginTokenFromCredentials($email: String!, $password: String!, $captchaToken: String) {
getLoginTokenFromCredentials(
email: $email
password: $password
captchaToken: $captchaToken
) {
loginToken {
...AuthTokenFragment
}
}
}
${AuthTokenFragmentFragmentDoc}`;
export type GetLoginTokenFromCredentialsMutationFn = Apollo.MutationFunction<GetLoginTokenFromCredentialsMutation, GetLoginTokenFromCredentialsMutationVariables>;
/**
* __useGetLoginTokenFromCredentialsMutation__
*
* To run a mutation, you first call `useGetLoginTokenFromCredentialsMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useGetLoginTokenFromCredentialsMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [getLoginTokenFromCredentialsMutation, { data, loading, error }] = useGetLoginTokenFromCredentialsMutation({
* variables: {
* email: // value for 'email'
* password: // value for 'password'
* captchaToken: // value for 'captchaToken'
* },
* });
*/
export function useGetLoginTokenFromCredentialsMutation(baseOptions?: Apollo.MutationHookOptions<GetLoginTokenFromCredentialsMutation, GetLoginTokenFromCredentialsMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useMutation<GetLoginTokenFromCredentialsMutation, GetLoginTokenFromCredentialsMutationVariables>(GetLoginTokenFromCredentialsDocument, options);
}
export type GetLoginTokenFromCredentialsMutationHookResult = ReturnType<typeof useGetLoginTokenFromCredentialsMutation>;
export type GetLoginTokenFromCredentialsMutationResult = Apollo.MutationResult<GetLoginTokenFromCredentialsMutation>;
export type GetLoginTokenFromCredentialsMutationOptions = Apollo.BaseMutationOptions<GetLoginTokenFromCredentialsMutation, GetLoginTokenFromCredentialsMutationVariables>;
export const GetLoginTokenFromEmailVerificationTokenDocument = gql`
mutation GetLoginTokenFromEmailVerificationToken($emailVerificationToken: String!, $captchaToken: String) {
getLoginTokenFromEmailVerificationToken(
@ -3156,41 +3199,6 @@ export function useUpdatePasswordViaResetTokenMutation(baseOptions?: Apollo.Muta
export type UpdatePasswordViaResetTokenMutationHookResult = ReturnType<typeof useUpdatePasswordViaResetTokenMutation>;
export type UpdatePasswordViaResetTokenMutationResult = Apollo.MutationResult<UpdatePasswordViaResetTokenMutation>;
export type UpdatePasswordViaResetTokenMutationOptions = Apollo.BaseMutationOptions<UpdatePasswordViaResetTokenMutation, UpdatePasswordViaResetTokenMutationVariables>;
export const VerifyDocument = gql`
mutation Verify($loginToken: String!) {
verify(loginToken: $loginToken) {
tokens {
...AuthTokensFragment
}
}
}
${AuthTokensFragmentFragmentDoc}`;
export type VerifyMutationFn = Apollo.MutationFunction<VerifyMutation, VerifyMutationVariables>;
/**
* __useVerifyMutation__
*
* To run a mutation, you first call `useVerifyMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useVerifyMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [verifyMutation, { data, loading, error }] = useVerifyMutation({
* variables: {
* loginToken: // value for 'loginToken'
* },
* });
*/
export function useVerifyMutation(baseOptions?: Apollo.MutationHookOptions<VerifyMutation, VerifyMutationVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useMutation<VerifyMutation, VerifyMutationVariables>(VerifyDocument, options);
}
export type VerifyMutationHookResult = ReturnType<typeof useVerifyMutation>;
export type VerifyMutationResult = Apollo.MutationResult<VerifyMutation>;
export type VerifyMutationOptions = Apollo.BaseMutationOptions<VerifyMutation, VerifyMutationVariables>;
export const CheckUserExistsDocument = gql`
query CheckUserExists($email: String!, $captchaToken: String) {
checkUserExists(email: $email, captchaToken: $captchaToken) {

View File

@ -21,7 +21,7 @@ export const VerifyEffect = () => {
const isLogged = useIsLogged();
const navigate = useNavigateApp();
const { verify } = useAuth();
const { getAuthTokensFromLoginToken } = useAuth();
const setIsAppWaitingForFreshObjectMetadata = useSetRecoilState(
isAppWaitingForFreshObjectMetadataState,
@ -30,14 +30,14 @@ export const VerifyEffect = () => {
useEffect(() => {
if (isDefined(errorMessage)) {
enqueueSnackBar(errorMessage, {
dedupeKey: 'verify-failed-dedupe-key',
dedupeKey: 'get-auth-tokens-from-login-token-failed-dedupe-key',
variant: SnackBarVariant.Error,
});
}
if (isDefined(loginToken)) {
setIsAppWaitingForFreshObjectMetadata(true);
verify(loginToken);
getAuthTokensFromLoginToken(loginToken);
} else if (!isLogged) {
navigate(AppPath.SignInUp);
}

View File

@ -1,15 +0,0 @@
import { gql } from '@apollo/client';
export const CHALLENGE = gql`
mutation Challenge(
$email: String!
$password: String!
$captchaToken: String
) {
challenge(email: $email, password: $password, captchaToken: $captchaToken) {
loginToken {
...AuthTokenFragment
}
}
}
`;

View File

@ -0,0 +1,11 @@
import { gql } from '@apollo/client';
export const GET_AUTH_TOKENS_FROM_LOGIN_TOKEN = gql`
mutation GetAuthTokensFromLoginToken($loginToken: String!) {
getAuthTokensFromLoginToken(loginToken: $loginToken) {
tokens {
...AuthTokensFragment
}
}
}
`;

View File

@ -0,0 +1,19 @@
import { gql } from '@apollo/client';
export const GET_LOGIN_TOKEN_FROM_CREDENTIALS = gql`
mutation GetLoginTokenFromCredentials(
$email: String!
$password: String!
$captchaToken: String
) {
getLoginTokenFromCredentials(
email: $email
password: $password
captchaToken: $captchaToken
) {
loginToken {
...AuthTokenFragment
}
}
}
`;

View File

@ -1,11 +0,0 @@
import { gql } from '@apollo/client';
export const VERIFY = gql`
mutation Verify($loginToken: String!) {
verify(loginToken: $loginToken) {
tokens {
...AuthTokensFragment
}
}
}
`;

View File

@ -1,13 +1,13 @@
import {
ChallengeDocument,
GetAuthTokensFromLoginTokenDocument,
GetCurrentUserDocument,
GetLoginTokenFromCredentialsDocument,
SignUpDocument,
VerifyDocument,
} from '~/generated/graphql';
export const queries = {
challenge: ChallengeDocument,
verify: VerifyDocument,
getLoginTokenFromCredentials: GetLoginTokenFromCredentialsDocument,
getAuthTokensFromLoginToken: GetAuthTokensFromLoginTokenDocument,
signup: SignUpDocument,
getCurrentUser: GetCurrentUserDocument,
};
@ -18,23 +18,23 @@ export const token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
export const variables = {
challenge: {
getLoginTokenFromCredentials: {
email,
password,
},
verify: { loginToken: token },
getAuthTokensFromLoginToken: { loginToken: token },
signup: {},
getCurrentUser: {},
};
export const results = {
challenge: {
getLoginTokenFromCredentials: {
loginToken: {
token,
expiresAt: '2022-01-01',
},
},
verify: {
getAuthTokensFromLoginToken: {
tokens: {
accessToken: { token, expiresAt: 'expiresAt' },
refreshToken: { token, expiresAt: 'expiresAt' },
@ -81,30 +81,30 @@ export const results = {
export const mocks = [
{
request: {
query: queries.challenge,
variables: variables.challenge,
query: queries.getLoginTokenFromCredentials,
variables: variables.getLoginTokenFromCredentials,
},
result: jest.fn(() => ({
data: {
challenge: results.challenge,
getLoginTokenFromCredentials: results.getLoginTokenFromCredentials,
},
})),
},
{
request: {
query: queries.verify,
variables: variables.verify,
query: queries.getAuthTokensFromLoginToken,
variables: variables.getAuthTokensFromLoginToken,
},
result: jest.fn(() => ({
data: {
verify: results.verify,
getAuthTokensFromLoginToken: results.getAuthTokensFromLoginToken,
},
})),
},
{
request: {
query: queries.signup,
variables: variables.challenge,
variables: variables.getLoginTokenFromCredentials,
},
result: jest.fn(() => ({
data: {

View File

@ -42,13 +42,13 @@ describe('useAuth', () => {
jest.clearAllMocks();
});
it('should return challenge object', async () => {
it('should return login token object', async () => {
const { result } = renderHooks();
await act(async () => {
expect(await result.current.challenge(email, password)).toStrictEqual(
results.challenge,
);
expect(
await result.current.getLoginTokenFromCredentials(email, password),
).toStrictEqual(results.getLoginTokenFromCredentials);
});
expect(mocks[0].result).toHaveBeenCalled();
@ -58,7 +58,7 @@ describe('useAuth', () => {
const { result } = renderHooks();
await act(async () => {
await result.current.verify(token);
await result.current.getAuthTokensFromLoginToken(token);
});
expect(mocks[1].result).toHaveBeenCalled();

View File

@ -22,12 +22,12 @@ import { supportChatState } from '@/client-config/states/supportChatState';
import { ColorScheme } from '@/workspace-member/types/WorkspaceMember';
import { REACT_APP_SERVER_BASE_URL } from '~/config';
import {
useChallengeMutation,
useCheckUserExistsLazyQuery,
useGetAuthTokensFromLoginTokenMutation,
useGetCurrentUserLazyQuery,
useGetLoginTokenFromCredentialsMutation,
useGetLoginTokenFromEmailVerificationTokenMutation,
useSignUpMutation,
useVerifyMutation,
} from '~/generated/graphql';
import { isDefined } from '~/utils/isDefined';
@ -87,9 +87,11 @@ export const useAuth = () => {
const { redirect } = useRedirect();
const { redirectToWorkspaceDomain } = useRedirectToWorkspaceDomain();
const [challenge] = useChallengeMutation();
const [getLoginTokenFromCredentials] =
useGetLoginTokenFromCredentialsMutation();
const [signUp] = useSignUpMutation();
const [verify] = useVerifyMutation();
const [getAuthTokensFromLoginToken] =
useGetAuthTokensFromLoginTokenMutation();
const [getLoginTokenFromEmailVerificationToken] =
useGetLoginTokenFromEmailVerificationTokenMutation();
const [getCurrentUser] = useGetCurrentUserLazyQuery();
@ -166,25 +168,25 @@ export const useAuth = () => {
[client, goToRecoilSnapshot, setLastAuthenticateWorkspaceDomain],
);
const handleChallenge = useCallback(
const handleGetLoginTokenFromCredentials = useCallback(
async (email: string, password: string, captchaToken?: string) => {
try {
const challengeResult = await challenge({
const getLoginTokenResult = await getLoginTokenFromCredentials({
variables: {
email,
password,
captchaToken,
},
});
if (isDefined(challengeResult.errors)) {
throw challengeResult.errors;
if (isDefined(getLoginTokenResult.errors)) {
throw getLoginTokenResult.errors;
}
if (!challengeResult.data?.challenge) {
if (!getLoginTokenResult.data?.getLoginTokenFromCredentials) {
throw new Error('No login token');
}
return challengeResult.data.challenge;
return getLoginTokenResult.data.getLoginTokenFromCredentials;
} catch (error) {
// TODO: Get intellisense for graphql error extensions code (codegen?)
if (
@ -198,7 +200,7 @@ export const useAuth = () => {
throw error;
}
},
[challenge, setSearchParams, setSignInUpStep],
[getLoginTokenFromCredentials, setSearchParams, setSignInUpStep],
);
const handleGetLoginTokenFromEmailVerificationToken = useCallback(
@ -322,41 +324,48 @@ export const useAuth = () => {
setWorkspaces,
]);
const handleVerify = useCallback(
const handleGetAuthTokensFromLoginToken = useCallback(
async (loginToken: string) => {
setIsVerifyPendingState(true);
const verifyResult = await verify({
const getAuthTokensResult = await getAuthTokensFromLoginToken({
variables: { loginToken },
});
if (isDefined(verifyResult.errors)) {
throw verifyResult.errors;
if (isDefined(getAuthTokensResult.errors)) {
throw getAuthTokensResult.errors;
}
if (!verifyResult.data?.verify) {
throw new Error('No verify result');
if (!getAuthTokensResult.data?.getAuthTokensFromLoginToken) {
throw new Error('No getAuthTokensFromLoginToken result');
}
setTokenPair(verifyResult.data?.verify.tokens);
setTokenPair(
getAuthTokensResult.data?.getAuthTokensFromLoginToken.tokens,
);
await loadCurrentUser();
setIsVerifyPendingState(false);
},
[setIsVerifyPendingState, verify, setTokenPair, loadCurrentUser],
[
setIsVerifyPendingState,
getAuthTokensFromLoginToken,
setTokenPair,
loadCurrentUser,
],
);
const handleCredentialsSignIn = useCallback(
async (email: string, password: string, captchaToken?: string) => {
const { loginToken } = await handleChallenge(
const { loginToken } = await handleGetLoginTokenFromCredentials(
email,
password,
captchaToken,
);
await handleVerify(loginToken.token);
await handleGetAuthTokensFromLoginToken(loginToken.token);
},
[handleChallenge, handleVerify],
[handleGetLoginTokenFromCredentials, handleGetAuthTokensFromLoginToken],
);
const handleSignOut = useCallback(async () => {
@ -413,14 +422,16 @@ export const useAuth = () => {
);
}
await handleVerify(signUpResult.data?.signUp.loginToken.token);
await handleGetAuthTokensFromLoginToken(
signUpResult.data?.signUp.loginToken.token,
);
},
[
setIsVerifyPendingState,
signUp,
workspacePublicData,
isMultiWorkspaceEnabled,
handleVerify,
handleGetAuthTokensFromLoginToken,
setSignInUpStep,
setSearchParams,
isEmailVerificationRequired,
@ -486,10 +497,10 @@ export const useAuth = () => {
);
return {
challenge: handleChallenge,
getLoginTokenFromCredentials: handleGetLoginTokenFromCredentials,
getLoginTokenFromEmailVerificationToken:
handleGetLoginTokenFromEmailVerificationToken,
verify: handleVerify,
getAuthTokensFromLoginToken: handleGetAuthTokensFromLoginToken,
loadCurrentUser,

View File

@ -1,13 +1,13 @@
import { useAuth } from '@/auth/hooks/useAuth';
import { currentUserState } from '@/auth/states/currentUserState';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useRedirectToWorkspaceDomain } from '@/domain-manager/hooks/useRedirectToWorkspaceDomain';
import { isAppWaitingForFreshObjectMetadataState } from '@/object-metadata/states/isAppWaitingForFreshObjectMetadataState';
import { AppPath } from '@/types/AppPath';
import { useState } from 'react';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { useImpersonateMutation } from '~/generated/graphql';
import { isDefined } from '~/utils/isDefined';
import { useRedirectToWorkspaceDomain } from '@/domain-manager/hooks/useRedirectToWorkspaceDomain';
import { useAuth } from '@/auth/hooks/useAuth';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { isAppWaitingForFreshObjectMetadataState } from '@/object-metadata/states/isAppWaitingForFreshObjectMetadataState';
export const useImpersonate = () => {
const [currentUser] = useRecoilState(currentUserState);
@ -16,7 +16,7 @@ export const useImpersonate = () => {
isAppWaitingForFreshObjectMetadataState,
);
const { verify } = useAuth();
const { getAuthTokensFromLoginToken } = useAuth();
const [impersonate] = useImpersonateMutation();
const { redirectToWorkspaceDomain } = useRedirectToWorkspaceDomain();
@ -50,7 +50,7 @@ export const useImpersonate = () => {
if (workspace.id === currentWorkspace?.id) {
setIsAppWaitingForFreshObjectMetadata(true);
await verify(loginToken.token);
await getAuthTokensFromLoginToken(loginToken.token);
setIsAppWaitingForFreshObjectMetadata(false);
return;
}

View File

@ -44,13 +44,13 @@ import { OriginHeader } from 'src/engine/decorators/auth/origin-header.decorator
import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
import { ChallengeInput } from './dto/challenge.input';
import { GetAuthTokensFromLoginTokenInput } from './dto/get-auth-tokens-from-login-token.input';
import { GetLoginTokenFromCredentialsInput } from './dto/get-login-token-from-credentials.input';
import { LoginToken } from './dto/login-token.entity';
import { SignUpInput } from './dto/sign-up.input';
import { ApiKeyToken, AuthTokens } from './dto/token.entity';
import { UserExistsOutput } from './dto/user-exists.entity';
import { CheckUserExistsInput } from './dto/user-exists.input';
import { VerifyInput } from './dto/verify.input';
import { WorkspaceInviteHashValid } from './dto/workspace-invite-hash-valid.entity';
import { WorkspaceInviteHashValidInput } from './dto/workspace-invite-hash.input';
import { AuthService } from './services/auth.service';
@ -103,8 +103,9 @@ export class AuthResolver {
@UseGuards(CaptchaGuard)
@Mutation(() => LoginToken)
async challenge(
@Args() challengeInput: ChallengeInput,
async getLoginTokenFromCredentials(
@Args()
getLoginTokenFromCredentialsInput: GetLoginTokenFromCredentialsInput,
@OriginHeader() origin: string,
): Promise<LoginToken> {
const workspace =
@ -119,7 +120,12 @@ export class AuthResolver {
AuthExceptionCode.WORKSPACE_NOT_FOUND,
),
);
const user = await this.authService.challenge(challengeInput, workspace);
const user = await this.authService.getLoginTokenFromCredentials(
getLoginTokenFromCredentialsInput,
workspace,
);
const loginToken = await this.loginTokenService.generateLoginToken(
user.email,
workspace.id,
@ -265,8 +271,8 @@ export class AuthResolver {
}
@Mutation(() => AuthTokens)
async verify(
@Args() verifyInput: VerifyInput,
async getAuthTokensFromLoginToken(
@Args() getAuthTokensFromLoginTokenInput: GetAuthTokensFromLoginTokenInput,
@OriginHeader() origin: string,
): Promise<AuthTokens> {
const workspace =
@ -277,7 +283,9 @@ export class AuthResolver {
workspaceValidator.assertIsDefinedOrThrow(workspace);
const { sub: email, workspaceId } =
await this.loginTokenService.verifyLoginToken(verifyInput.loginToken);
await this.loginTokenService.verifyLoginToken(
getAuthTokensFromLoginTokenInput.loginToken,
);
if (workspaceId !== workspace.id) {
throw new AuthException(

View File

@ -3,7 +3,7 @@ import { ArgsType, Field } from '@nestjs/graphql';
import { IsNotEmpty, IsString } from 'class-validator';
@ArgsType()
export class VerifyInput {
export class GetAuthTokensFromLoginTokenInput {
@Field(() => String)
@IsNotEmpty()
@IsString()

View File

@ -3,7 +3,7 @@ import { ArgsType, Field } from '@nestjs/graphql';
import { IsEmail, IsNotEmpty, IsOptional, IsString } from 'class-validator';
@ArgsType()
export class ChallengeInput {
export class GetLoginTokenFromCredentialsInput {
@Field(() => String)
@IsNotEmpty()
@IsEmail()

View File

@ -6,9 +6,15 @@ import bcrypt from 'bcrypt';
import { Repository } from 'typeorm';
import { AppToken } from 'src/engine/core-modules/app-token/app-token.entity';
import {
AuthException,
AuthExceptionCode,
} from 'src/engine/core-modules/auth/auth.exception';
import { SignInUpService } from 'src/engine/core-modules/auth/services/sign-in-up.service';
import { SocialSsoService } from 'src/engine/core-modules/auth/services/social-sso.service';
import { AccessTokenService } from 'src/engine/core-modules/auth/token/services/access-token.service';
import { RefreshTokenService } from 'src/engine/core-modules/auth/token/services/refresh-token.service';
import { ExistingUserOrNewUser } from 'src/engine/core-modules/auth/types/signInUp.type';
import { DomainManagerService } from 'src/engine/core-modules/domain-manager/services/domain-manager.service';
import { EmailService } from 'src/engine/core-modules/email/email.service';
import { EnvironmentService } from 'src/engine/core-modules/environment/environment.service';
@ -16,13 +22,7 @@ import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/use
import { UserService } from 'src/engine/core-modules/user/services/user.service';
import { User } from 'src/engine/core-modules/user/user.entity';
import { WorkspaceInvitationService } from 'src/engine/core-modules/workspace-invitation/services/workspace-invitation.service';
import { SocialSsoService } from 'src/engine/core-modules/auth/services/social-sso.service';
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
import { ExistingUserOrNewUser } from 'src/engine/core-modules/auth/types/signInUp.type';
import {
AuthException,
AuthExceptionCode,
} from 'src/engine/core-modules/auth/auth.exception';
import { AuthService } from './auth.service';
@ -165,7 +165,7 @@ describe('AuthService', () => {
userWorkspaceServiceCheckUserWorkspaceExistsMock.mockReturnValueOnce({});
const response = await service.challenge(
const response = await service.getLoginTokenFromCredentials(
{
email: 'email',
password: 'password',
@ -201,7 +201,7 @@ describe('AuthService', () => {
workspaceInvitationValidatePersonalInvitationMock.mockReturnValueOnce({});
userWorkspaceAddUserToWorkspaceMock.mockReturnValueOnce({});
const response = await service.challenge(
const response = await service.getLoginTokenFromCredentials(
{
email: 'email',
password: 'password',

View File

@ -26,7 +26,7 @@ import {
} from 'src/engine/core-modules/auth/auth.util';
import { AuthorizeApp } from 'src/engine/core-modules/auth/dto/authorize-app.entity';
import { AuthorizeAppInput } from 'src/engine/core-modules/auth/dto/authorize-app.input';
import { ChallengeInput } from 'src/engine/core-modules/auth/dto/challenge.input';
import { GetLoginTokenFromCredentialsInput } from 'src/engine/core-modules/auth/dto/get-login-token-from-credentials.input';
import { AuthTokens } from 'src/engine/core-modules/auth/dto/token.entity';
import { UpdatePassword } from 'src/engine/core-modules/auth/dto/update-password.entity';
import {
@ -35,26 +35,26 @@ import {
} from 'src/engine/core-modules/auth/dto/user-exists.entity';
import { WorkspaceInviteHashValid } from 'src/engine/core-modules/auth/dto/workspace-invite-hash-valid.entity';
import { SignInUpService } from 'src/engine/core-modules/auth/services/sign-in-up.service';
import { SocialSsoService } from 'src/engine/core-modules/auth/services/social-sso.service';
import { AccessTokenService } from 'src/engine/core-modules/auth/token/services/access-token.service';
import { RefreshTokenService } from 'src/engine/core-modules/auth/token/services/refresh-token.service';
import { DomainManagerService } from 'src/engine/core-modules/domain-manager/services/domain-manager.service';
import { EmailService } from 'src/engine/core-modules/email/email.service';
import { EnvironmentService } from 'src/engine/core-modules/environment/environment.service';
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
import { User } from 'src/engine/core-modules/user/user.entity';
import { userValidator } from 'src/engine/core-modules/user/user.validate';
import { WorkspaceInvitationService } from 'src/engine/core-modules/workspace-invitation/services/workspace-invitation.service';
import { WorkspaceAuthProvider } from 'src/engine/core-modules/workspace/types/workspace.type';
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
import { SocialSsoService } from 'src/engine/core-modules/auth/services/social-sso.service';
import { UserService } from 'src/engine/core-modules/user/services/user.service';
import { workspaceValidator } from 'src/engine/core-modules/workspace/workspace.validate';
import {
AuthProviderWithPasswordType,
ExistingUserOrNewUser,
SignInUpBaseParams,
SignInUpNewUserPayload,
} from 'src/engine/core-modules/auth/types/signInUp.type';
import { DomainManagerService } from 'src/engine/core-modules/domain-manager/services/domain-manager.service';
import { EmailService } from 'src/engine/core-modules/email/email.service';
import { EnvironmentService } from 'src/engine/core-modules/environment/environment.service';
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
import { UserService } from 'src/engine/core-modules/user/services/user.service';
import { User } from 'src/engine/core-modules/user/user.entity';
import { userValidator } from 'src/engine/core-modules/user/user.validate';
import { WorkspaceInvitationService } from 'src/engine/core-modules/workspace-invitation/services/workspace-invitation.service';
import { WorkspaceAuthProvider } from 'src/engine/core-modules/workspace/types/workspace.type';
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
import { workspaceValidator } from 'src/engine/core-modules/workspace/workspace.validate';
@Injectable()
// eslint-disable-next-line @nx/workspace-inject-workspace-repository
@ -113,7 +113,10 @@ export class AuthService {
);
}
async challenge(challengeInput: ChallengeInput, targetWorkspace: Workspace) {
async getLoginTokenFromCredentials(
input: GetLoginTokenFromCredentialsInput,
targetWorkspace: Workspace,
) {
if (!targetWorkspace.isPasswordAuthEnabled) {
throw new AuthException(
'Email/Password auth is not enabled for this workspace',
@ -123,7 +126,7 @@ export class AuthService {
const user = await this.userRepository.findOne({
where: {
email: challengeInput.email,
email: input.email,
},
relations: ['workspaces'],
});
@ -144,10 +147,7 @@ export class AuthService {
);
}
const isValid = await compareHash(
challengeInput.password,
user.passwordHash,
);
const isValid = await compareHash(input.password, user.passwordHash);
if (!isValid) {
throw new AuthException(

View File

@ -46,8 +46,8 @@ export class GraphQLHydrateRequestFromTokenMiddleware
'GetWorkspaceFromInviteHash',
'Track',
'CheckUserExists',
'Challenge',
'Verify',
'GetLoginTokenFromCredentials',
'GetAuthTokensFromLoginToken',
'GetLoginTokenFromEmailVerificationToken',
'ResendEmailVerificationToken',
'SignUp',

View File

@ -10,11 +10,11 @@ const auth = {
describe('AuthResolve (integration)', () => {
let loginToken: string;
it('should challenge with email and password', () => {
it('should getLoginTokenFromCredentials with email and password', () => {
const queryData = {
query: `
mutation Challenge {
challenge(email: "${auth.email}", password: "${auth.password}") {
mutation GetLoginTokenFromCredentials {
getLoginTokenFromCredentials(email: "${auth.email}", password: "${auth.password}") {
loginToken {
token
expiresAt
@ -33,7 +33,7 @@ describe('AuthResolve (integration)', () => {
expect(res.body.errors).toBeUndefined();
})
.expect((res) => {
const data = res.body.data.challenge;
const data = res.body.data.getLoginTokenFromCredentials;
expect(data).toBeDefined();
expect(data.loginToken).toBeDefined();
@ -42,11 +42,11 @@ describe('AuthResolve (integration)', () => {
});
});
it('should verify with login token', () => {
it('should getAuthTokensFromLoginToken with login token', () => {
const queryData = {
query: `
mutation Verify {
verify(loginToken: "${loginToken}") {
mutation GetAuthTokensFromLoginToken {
getAuthTokensFromLoginToken(loginToken: "${loginToken}") {
tokens {
accessToken {
token
@ -66,7 +66,7 @@ describe('AuthResolve (integration)', () => {
expect(res.body.errors).toBeUndefined();
})
.expect((res) => {
const data = res.body.data.verify;
const data = res.body.data.getAuthTokensFromLoginToken;
expect(data).toBeDefined();
expect(data.tokens).toBeDefined();