Browse Source

test cors register

amenpunk 3 years ago
parent
commit
471f726773
4 changed files with 168 additions and 42 deletions
  1. 82 25
      src/Components/Register/RegisterForm.jsx
  2. 1 1
      src/Pages/Login.jsx
  3. 25 14
      src/Pages/Register.jsx
  4. 60 2
      src/Utils/HTTP.js

+ 82 - 25
src/Components/Register/RegisterForm.jsx

@@ -1,29 +1,38 @@
1
+import React from 'react'
1 2
 import * as Yup from 'yup';
2 3
 import { useState } from 'react';
3 4
 import { useFormik, Form, FormikProvider } from 'formik';
5
+import { Service } from '../../Utils/HTTP'
4 6
 import { useNavigate } from 'react-router-dom';
5 7
 import { Icon } from '@iconify/react';
6
-// material
7
-import { Stack, TextField, IconButton, InputAdornment } from '@mui/material';
8
+
9
+import { Stack, TextField, IconButton, InputAdornment, Button, Backdrop, CircularProgress } from '@mui/material';
8 10
 import eyeFill from '@iconify/icons-eva/eye-fill';
9 11
 import eyeOffFill from '@iconify/icons-eva/eye-off-fill';
10
-import Button from '@mui/material/Button';
12
+import toast, { Toaster } from 'react-hot-toast';
11 13
 
12 14
 // import { Visibility as eyeFill ,VisibilityOff as eyeOffFill } from '@mui/icons-material/';
13 15
 // ----------------------------------------------------------------------
14
-
15 16
 export function RegisterForm() {
16
-    const navigate = useNavigate();
17
+
18
+    // const navigate = useNavigate();
17 19
     const [showPassword, setShowPassword] = useState(false);
20
+    const [open, setOpen] = React.useState(false);
21
+    const handleClose = () => {
22
+        setOpen(false);
23
+    };
24
+    
25
+    let navigate = useNavigate()
18 26
 
19 27
     const RegisterSchema = Yup.object().shape({
20 28
         firstName: Yup.string()
21
-        .min(2, 'Too Short!')
22
-        .max(50, 'Too Long!')
23
-        .required('First name required'),
24
-        lastName: Yup.string().min(2, 'Too Short!').max(50, 'Too Long!').required('Last name required'),
25
-        email: Yup.string().email('Email must be a valid email address').required('Email is required'),
26
-        password: Yup.string().required('Password is required')
29
+        .min(2, 'Demasiado corto!')
30
+        .max(50, 'Demasiado largo!')
31
+        .required('Tu nombre es requerido'),
32
+        lastName: Yup.string().min(2, 'Demasiado corto!').max(50, 'Demasiado Largo!').required('El apellido es requerido'),
33
+        email: Yup.string().email('El correo no es valido').required('Email es requerido'),
34
+        password: Yup.string().min(5, 'La contraseña debe contener mínimo 5 caracteres').required('la contraseña es requerida'),
35
+        password_confirm: Yup.string().required('Las contraseñas no coincidien').oneOf([Yup.ref('password'), null], 'Las contraseñas no coincidien')
27 36
     });
28 37
 
29 38
     const formik = useFormik({
@@ -31,11 +40,50 @@ export function RegisterForm() {
31 40
             firstName: '',
32 41
             lastName: '',
33 42
             email: '',
34
-            password: ''
43
+            password: '',
44
+            password_confirm: ''
35 45
         },
36 46
         validationSchema: RegisterSchema,
37
-        onSubmit: () => {
38
-            navigate('/dashboard', { replace: true });
47
+        onSubmit: (values) => {
48
+            console.log("values > " ,values)
49
+            setOpen(true);
50
+            let body = {
51
+                nombre : values.firstName,
52
+                apelidos : values.lastName,
53
+                email : values.email,
54
+                username : values.email,
55
+                pwd : values.password,
56
+                "nit": "5345435",
57
+                "cui": "555555",
58
+                "direccio": "4 calle zona 1",
59
+                "fechacumple": "2021-01-01",
60
+                "telefono" : "45435345",
61
+            }
62
+            // navigate('/dashboard', { replace: true });
63
+            let request = new Service('/registro');
64
+            request
65
+                .post(body)
66
+                .then( response => {
67
+                    console.log(response);
68
+                    let { status } = response;
69
+                    if(status !== 200){
70
+                        setOpen(false)
71
+                        return toast.error("Ups! verifica tus datos")
72
+                    }
73
+
74
+                    toast.success(`Bienvenido, ingresa tus credenciales`)
75
+                    setTimeout( () => {
76
+                        setOpen(false)
77
+                        navigate('/login')
78
+                        // auth.login(token)
79
+                    }, 5000)
80
+                }) 
81
+                .catch( err => {
82
+                    setOpen(false)
83
+                    toast.error("Solicitud incorrecta")
84
+                    console.log("ERROR ", err)
85
+                })
86
+
39 87
         }
40 88
     });
41 89
 
@@ -47,16 +95,16 @@ export function RegisterForm() {
47 95
                 <Stack spacing={3}>
48 96
                     <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
49 97
                         <TextField
98
+                            label="Nombre"
50 99
                             fullWidth
51
-                            label="First name"
52 100
                             {...getFieldProps('firstName')}
53 101
                             error={Boolean(touched.firstName && errors.firstName)}
54 102
                             helperText={touched.firstName && errors.firstName}
55 103
                         />
56 104
 
57 105
                         <TextField
106
+                            label="Apellidos"
58 107
                             fullWidth
59
-                            label="Last name"
60 108
                             {...getFieldProps('lastName')}
61 109
                             error={Boolean(touched.lastName && errors.lastName)}
62 110
                             helperText={touched.lastName && errors.lastName}
@@ -67,19 +115,17 @@ export function RegisterForm() {
67 115
                         fullWidth
68 116
                         autoComplete="username"
69 117
                         type="email"
70
-                        label="Email address"
118
+                        label="Correo Electrónico"
71 119
                         {...getFieldProps('email')}
72 120
                         error={Boolean(touched.email && errors.email)}
73 121
                         helperText={touched.email && errors.email}
74 122
                     />
75 123
 
76
-
77
-
78 124
                     <TextField
79 125
                         fullWidth
80 126
                         autoComplete="current-password"
81 127
                         type={showPassword ? 'text' : 'password'}
82
-                        label="Password"
128
+                        label="Contraseña"
83 129
                         {...getFieldProps('password')}
84 130
                         InputProps={{
85 131
                             endAdornment: (
@@ -96,10 +142,9 @@ export function RegisterForm() {
96 142
 
97 143
                     <TextField
98 144
                         fullWidth
99
-                        autoComplete="current-password"
100 145
                         type={showPassword ? 'text' : 'password'}
101
-                        label="Password"
102
-                        {...getFieldProps('password')}
146
+                        label="Confirma contraseña"
147
+                        {...getFieldProps('password_confirm')}
103 148
                         InputProps={{
104 149
                             endAdornment: (
105 150
                                 <InputAdornment position="end">
@@ -109,11 +154,12 @@ export function RegisterForm() {
109 154
                                 </InputAdornment>
110 155
                             )
111 156
                         }}
112
-                        error={Boolean(touched.password && errors.password)}
113
-                        helperText={touched.password && errors.password}
157
+                        error={Boolean(touched.password_confirm && errors.password_confirm)}
158
+                        helperText={touched.password_confirm && errors.password_confirm}
114 159
                     />
115 160
 
116 161
                     <Button 
162
+                        type="submit"
117 163
                         size="large"
118 164
                         style={{ backgroundColor : '#d32f2f'}}
119 165
                         variant="contained" >
@@ -122,6 +168,17 @@ export function RegisterForm() {
122 168
 
123 169
                 </Stack>
124 170
             </Form>
171
+            <Toaster
172
+                position="top-left"
173
+                reverseOrder={false}
174
+            />
175
+            <Backdrop
176
+                sx={{ color: '#fd4b4b', zIndex: (theme) => theme.zIndex.drawer + 1 }}
177
+                open={open}
178
+                onClick={handleClose}
179
+            >
180
+                <CircularProgress color="inherit" />
181
+            </Backdrop>
125 182
         </FormikProvider>
126 183
     );
127 184
 }

+ 1 - 1
src/Pages/Login.jsx

@@ -59,7 +59,7 @@ export function Login() {
59 59
             let request = new Service(`/user?user=${email}&password=${password}`)
60 60
 
61 61
             request
62
-            .post({})
62
+            .post_({})
63 63
             .then( response => {
64 64
                 console.log(response);
65 65
 

+ 25 - 14
src/Pages/Register.jsx

@@ -3,15 +3,14 @@ import { Link as RouterLink } from 'react-router-dom';
3 3
 
4 4
 import { styled } from '@mui/material/styles';
5 5
 import { Box, Card, Link, Container, Typography } from '@mui/material';
6
-
7
-// import AuthLayout from '../layouts/AuthLayout';
8 6
 import AuthLayout from '../Components/Register/AuthLayout';
9 7
 
10 8
 import Page from '../Components/Register/Page';
11 9
 import { RegisterForm } from '../Components/Register/RegisterForm';
12
-// import MHidden from '../Components/Register/MHidden';
13 10
 
14 11
 import Mock from  '../Images/register_mok.png'
12
+import useAuth from '../Auth/useAuth';
13
+import { useNavigate } from 'react-router-dom'
15 14
 
16 15
 const RootStyle = styled(Page)(({ theme }) => ({
17 16
     [theme.breakpoints.up('md')]: {
@@ -41,12 +40,24 @@ const ContentStyle = styled('div')(({ theme }) => ({
41 40
 // ----------------------------------------------------------------------
42 41
 
43 42
 export function Register() {
43
+
44
+    let auth = useAuth();
45
+    let navigate = useNavigate()
46
+
47
+    React.useEffect(() => {
48
+        if(auth.isLogged()){
49
+            return navigate('/dashboard/home')
50
+        }    
51
+    }, [auth,navigate])
52
+
53
+
44 54
     return (
45 55
         <RootStyle title="Register | Minimal-UI">
56
+
46 57
             <AuthLayout>
47
-                Already have an account? &nbsp;
48
-                <Link underline="none" variant="subtitle2" component={RouterLink} to="/login">
49
-                    Login
58
+                Ya tiene una cuenta?&nbsp;
59
+                <Link to="/login" component={RouterLink}>
60
+                    Ingresa
50 61
                 </Link>
51 62
             </AuthLayout>
52 63
 
@@ -72,22 +83,22 @@ export function Register() {
72 83
                     <RegisterForm />
73 84
 
74 85
                     <Typography variant="body2" align="center" sx={{ color: 'text.secondary', mt: 3 }}>
75
-                        By registering, I agree to Minimal&nbsp;
76
-                        <Link underline="always" sx={{ color: 'text.primary' }}>
77
-                            Terms of Service
86
+                        Estoy de acuerdo con las {" "}
87
+                        <Link underline="always" sx={{ color: "#d32f2f" }}>
88
+                            Condiciones de servicio
78 89
                         </Link>
79
-                        &nbsp;and&nbsp;
80
-                        <Link underline="always" sx={{ color: 'text.primary' }}>
81
-                            Privacy Policy
90
+                        {" "}y{" "}
91
+                        <Link underline="always" sx={{ color: "#d32f2f" }}>
92
+                            Política de privacidad
82 93
                         </Link>
83 94
                         .
84 95
                     </Typography>
85 96
 
86 97
                     <div>
87 98
                         <Typography variant="subtitle2" sx={{ mt: 3, textAlign: 'center' }}>
88
-                            Already have an account?&nbsp;
99
+                            Ya tiene una cuenta?&nbsp;
89 100
                             <Link to="/login" component={RouterLink}>
90
-                                Login
101
+                                Ingresa
91 102
                             </Link>
92 103
                         </Typography>
93 104
                     </div>

+ 60 - 2
src/Utils/HTTP.js

@@ -7,13 +7,71 @@ export class Service {
7 7
         // this.api =  'http://psicoadmin.ditca.org:8081/user?user=patrik&password=12345'
8 8
     }
9 9
 
10
-    async post(body){
10
+
11
+    async browser(){
12
+        fetch("http://psicoadmin.ditca.org:8081/registro", {
13
+            "headers": {
14
+                "accept": "*/*",
15
+                "accept-language": "en-US,en;q=0.9,es;q=0.8",
16
+                "cache-control": "no-cache",
17
+                "pragma": "no-cache",
18
+                "sec-gpc": "1"
19
+            },
20
+            "referrer": "http://localhost:3000/",
21
+            "referrerPolicy": "strict-origin-when-cross-origin",
22
+            "body": null,
23
+            "method": "POST",
24
+            "mode": "cors",
25
+            "credentials": "omit"
26
+        });
27
+    }
28
+
29
+    async post_(body){
30
+        console.log('body >> ', body)
11 31
         let response = await fetch(this.url, {
12 32
             method: "POST",
13
-            data : body
33
+            body : JSON.stringify(body)
14 34
         })
15 35
         return await response.json(); 
16 36
     }
37
+    
38
+    async post(body){
17 39
 
40
+        let headers ={
41
+
42
+            "Accept-Encoding" : "gzip, deflate, br",
43
+            "accept": "*/*",
44
+            "accept-language": "en-US,en;q=0.9,es;q=0.8",
45
+            "cache-control": "no-cache",
46
+            "content-type": "text/plain;charset=UTF-8",
47
+            "pragma": "no-cache",
48
+            "sec-gpc": "1",
49
+            'Accept': 'application/json',
50
+            'Content-Type': 'application/json',
51
+            // "Content-Length": body.Length
52
+        }
53
+
54
+        headers = {
55
+            // 'Accept': '*/*',
56
+            'Accept': 'application/json',
57
+            'Content-Type': 'application/json',
58
+            "accept-language": "en-US,en;q=0.9,es;q=0.8",
59
+            "cache-control": "no-cache",
60
+            "pragma": "no-cache",
61
+            "sec-gpc": "1"
62
+        }
63
+
64
+        let response = await fetch("http://psicoadmin.ditca.org:8081/registro", {
65
+            // "headers": new Headers( headers ), 
66
+            "headers": new Headers( headers ),
67
+            "referrer": "http://localhost:3000/",
68
+            "referrerPolicy": "strict-origin-when-cross-origin",
69
+            "body": JSON.stringify(body),
70
+            "method": "POST",
71
+            "mode": "cors",
72
+        });    
73
+        console.log(response);
74
+        return await response.json();
75
+    }
18 76
 }
19 77