2024-07-18 20:57:59 +03:00

102 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,
ERROR_TELEGRAM_SEND_MESSAGE,
} from '@/constants/errors';
import { FormStateContext } from '@/context/form-state';
import type { LdapUser } from '@/types/user';
import axios 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: 'login-success',
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-notification',
},
type: 'set-step',
});
})
.catch(() =>
dispatch({
payload: { error: ERROR_TELEGRAM_SEND_MESSAGE },
type: 'set-error',
})
);
}
return { handleTelegramLogin };
}
export function useTelegramConfirm() {
const {
dispatch,
state: { step },
} = useContext(FormStateContext);
const { socket } = useSocket();
useEffect(() => {
if (step === 'telegram-notification') {
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',
})
);
});
socket.on('auth-deny', () => {
socket.off('connect');
window.location.reload();
});
}
return () => {
socket.off('connect');
};
}, [dispatch, socket, step]);
}