2024-01-21 23:50:56 +11:00
|
|
|
import { createContext, useContext } from 'react';
|
2026-10-24 16:15:24 -04:00
|
|
|
import { IAuthData, MatrixError, ValidatedAuthMetadata } from 'matrix-js-sdk';
|
2024-01-21 23:50:56 +11:00
|
|
|
import { ILoginFlowsResponse } from 'matrix-js-sdk/lib/@types/auth';
|
|
|
|
|
|
|
|
|
|
export enum RegisterFlowStatus {
|
|
|
|
|
FlowRequired = 401,
|
|
|
|
|
InvalidRequest = 400,
|
|
|
|
|
RegistrationDisabled = 403,
|
|
|
|
|
RateLimited = 429,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export type RegisterFlowsResponse =
|
|
|
|
|
| {
|
|
|
|
|
status: RegisterFlowStatus.FlowRequired;
|
|
|
|
|
data: IAuthData;
|
|
|
|
|
}
|
|
|
|
|
| {
|
|
|
|
|
status: Exclude<RegisterFlowStatus, RegisterFlowStatus.FlowRequired>;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const parseRegisterErrResp = (matrixError: MatrixError): RegisterFlowsResponse => {
|
|
|
|
|
switch (matrixError.httpStatus) {
|
|
|
|
|
case RegisterFlowStatus.InvalidRequest: {
|
|
|
|
|
return { status: RegisterFlowStatus.InvalidRequest };
|
|
|
|
|
}
|
|
|
|
|
case RegisterFlowStatus.RateLimited: {
|
|
|
|
|
return { status: RegisterFlowStatus.RateLimited };
|
|
|
|
|
}
|
|
|
|
|
case RegisterFlowStatus.RegistrationDisabled: {
|
|
|
|
|
return { status: RegisterFlowStatus.RegistrationDisabled };
|
|
|
|
|
}
|
|
|
|
|
case RegisterFlowStatus.FlowRequired: {
|
|
|
|
|
return {
|
|
|
|
|
status: RegisterFlowStatus.FlowRequired,
|
|
|
|
|
data: matrixError.data as IAuthData,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
default: {
|
|
|
|
|
return { status: RegisterFlowStatus.InvalidRequest };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export type AuthFlows = {
|
|
|
|
|
loginFlows: ILoginFlowsResponse;
|
|
|
|
|
registerFlows: RegisterFlowsResponse;
|
2026-10-24 16:15:24 -04:00
|
|
|
/**
|
|
|
|
|
* The homeserver's OAuth 2.0 metadata (`/_matrix/client/v1/auth_metadata`),
|
|
|
|
|
* when it uses native OAuth (MSC3861, e.g. matrix.org via MAS). The same
|
|
|
|
|
* source the SDK uses to refresh tokens, so sign-in is only offered when
|
|
|
|
|
* refresh will work too.
|
|
|
|
|
*/
|
|
|
|
|
authMetadata?: ValidatedAuthMetadata;
|
2024-01-21 23:50:56 +11:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const AuthFlowsContext = createContext<AuthFlows | null>(null);
|
|
|
|
|
|
|
|
|
|
export const AuthFlowsProvider = AuthFlowsContext.Provider;
|
|
|
|
|
|
|
|
|
|
export const useAuthFlows = (): AuthFlows => {
|
|
|
|
|
const authFlows = useContext(AuthFlowsContext);
|
|
|
|
|
if (!authFlows) {
|
|
|
|
|
throw new Error('Auth Flow info is not loaded!');
|
|
|
|
|
}
|
|
|
|
|
return authFlows;
|
|
|
|
|
};
|