summaryrefslogtreecommitdiff
path: root/src/lib/auth/hooks/useLogin.js
blob: dc9580eaa4ed79660b6d745a63161f04bc31adaf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import Link from '@/core/components/elements/Link/Link';
import { setAuth } from '@/core/utils/auth';
import { useRouter } from 'next/router';
import { useRef, useState } from 'react';
import loginApi from '../api/loginApi';
import odooApi from '@/core/api/odooApi';
import { setCookie } from 'cookies-next';
import { useSession } from 'next-auth/react';

const useLogin = () => {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [alert, setAlert] = useState(null);
  const [isValid, setIsValid] = useState(false);

  const emailRef = useRef(null);
  const passwordRef = useRef(null);

  const inputVal = () => ({
    email: emailRef.current.value,
    password: passwordRef.current.value,
  });

  const handleChangeInput = () => {
    const { email, password } = inputVal();
    const isValidInput = email && password;
    setIsValid(isValidInput);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setAlert(null);
    setIsLoading(true);
    const { email, password } = inputVal();
    const login = await loginApi({ email, password });
    setIsLoading(false);

    if (login.isAuth) {
      setAuth(login.user);
      router.push(router.query?.next || '/');
      return;
    }
    switch (login.reason) {
      case 'NOT_FOUND':
        setAlert({
          children: 'Email atau password tidak cocok',
          type: 'info',
        });
        break;
      case 'NOT_ACTIVE':
        setAlert({
          children: (
            <>
              Email belum diaktivasi,
              <Link
                className='text-gray-900'
                href={`?activation=email&email=${email}`}
              >
                aktivasi sekarang
              </Link>
            </>
          ),
          type: 'info',
        });
        break;
    }
  };

  const handleGoogleSubmit = async (session) => {
    const params = {
      access_token: session.accessToken,
    };
    const data = await odooApi('POST', '/api/v1/user/validate-sso', params);
    if (data.isAuth) {
      session.odooUser = data.user;
      setCookie('auth', JSON.stringify(session?.odooUser));
      router.push(decodeURIComponent(router?.query?.next) ?? '/');
      return;
    }
  };

  return {
    handleChangeInput,
    handleSubmit,
    isLoading,
    isValid,
    alert,
    emailRef,
    passwordRef,
    handleGoogleSubmit,
  };
};

export default useLogin;