100 lines
2.3 KiB
TypeScript
100 lines
2.3 KiB
TypeScript
import type { FormData } from '../lib/types';
|
|
import { useSocket } from './socket';
|
|
import { redirect } from '@/components/Form/lib/utils';
|
|
import { ERROR_INVALID_CREDENTIALS, ERROR_SERVER } from '@/constants/errors';
|
|
import { FormStateContext } from '@/context/form-state';
|
|
import type { TelegramUrlResponse } from '@/types/error';
|
|
import type { LdapUser } from '@/types/user';
|
|
import axios, { isAxiosError } from 'axios';
|
|
import { useContext, useEffect } from 'react';
|
|
|
|
export function useLogin() {
|
|
const { dispatch } = useContext(FormStateContext);
|
|
|
|
function handleLogin(data: FormData) {
|
|
axios
|
|
.post<LdapUser>('/login', data)
|
|
.then((res) => {
|
|
dispatch({
|
|
payload: {
|
|
step: 'telegram',
|
|
user: res.data,
|
|
},
|
|
type: 'set-step',
|
|
});
|
|
})
|
|
.catch(() =>
|
|
dispatch({
|
|
payload: { error: ERROR_INVALID_CREDENTIALS },
|
|
type: 'set-error',
|
|
})
|
|
);
|
|
}
|
|
|
|
return { handleLogin };
|
|
}
|
|
|
|
export function useTelegramLogin() {
|
|
const { dispatch } = useContext(FormStateContext);
|
|
|
|
function handleTelegramLogin() {
|
|
axios
|
|
.post<LdapUser>('/login-telegram')
|
|
.then(() => {
|
|
dispatch({
|
|
payload: {
|
|
step: 'telegram-login',
|
|
},
|
|
type: 'set-step',
|
|
});
|
|
})
|
|
.catch((error_) => {
|
|
let error = ERROR_SERVER;
|
|
|
|
if (isAxiosError<TelegramUrlResponse>(error_) && error_.response?.data?.message) {
|
|
error = error_.response?.data?.message;
|
|
}
|
|
|
|
return dispatch({
|
|
payload: { error },
|
|
type: 'set-error',
|
|
});
|
|
});
|
|
}
|
|
|
|
return { handleTelegramLogin };
|
|
}
|
|
|
|
export function useTelegramConfirm() {
|
|
const {
|
|
dispatch,
|
|
state: { step },
|
|
} = useContext(FormStateContext);
|
|
|
|
const { socket } = useSocket();
|
|
|
|
useEffect(() => {
|
|
if (step === 'telegram-login') {
|
|
socket.open();
|
|
socket.on('connect', () => {});
|
|
|
|
socket.on('auth-allow', () => {
|
|
socket.off('connect');
|
|
axios
|
|
.get('/login-confirm')
|
|
.then(() => redirect())
|
|
.catch(() =>
|
|
dispatch({
|
|
payload: { error: ERROR_SERVER },
|
|
type: 'set-error',
|
|
})
|
|
);
|
|
});
|
|
}
|
|
|
|
return () => {
|
|
socket.off('connect');
|
|
};
|
|
}, [dispatch, socket, step]);
|
|
}
|