Browse Source

stpper in register form

amenpunk 3 years ago
parent
commit
da8a83ce09
5 changed files with 139 additions and 114 deletions
  1. 4 4
      src/Auth/AuthProvider.js
  2. 16 31
      src/Components/Register/RegisterForm.jsx
  3. 5 9
      src/Pages/Login.jsx
  4. 81 12
      src/Pages/Register.jsx
  5. 33 58
      src/Utils/HTTP.js

+ 4 - 4
src/Auth/AuthProvider.js

17
                 console.log('Login Error >> ', e)
17
                 console.log('Login Error >> ', e)
18
                 Cookies.set('token', undefined)
18
                 Cookies.set('token', undefined)
19
             }
19
             }
20
-
21
         },
20
         },
22
         logout : () => {
21
         logout : () => {
23
             Cookies.set('token', undefined)
22
             Cookies.set('token', undefined)
29
                 if(!CookiesUser || CookiesUser === 'undefined'){
28
                 if(!CookiesUser || CookiesUser === 'undefined'){
30
                     return false
29
                     return false
31
                 }
30
                 }
32
-                // let current = JSON.parse(CookiesUser);
33
-                console.log("token >> ", CookiesUser)
34
-                let logged = CookiesUser.length > 5 //Object.keys(current).includes('email')
31
+                // TODO   
32
+                // add an method implmentation for 
33
+                // check if cockie jwt is valid
34
+                let logged = CookiesUser.length > 5 
35
                 console.log("is login? >>", logged)
35
                 console.log("is login? >>", logged)
36
                 return logged
36
                 return logged
37
 
37
 

+ 16 - 31
src/Components/Register/RegisterForm.jsx

2
 import * as Yup from 'yup';
2
 import * as Yup from 'yup';
3
 import { useState } from 'react';
3
 import { useState } from 'react';
4
 import { useFormik, Form, FormikProvider } from 'formik';
4
 import { useFormik, Form, FormikProvider } from 'formik';
5
-import { Service } from '../../Utils/HTTP'
6
 import { useNavigate } from 'react-router-dom';
5
 import { useNavigate } from 'react-router-dom';
7
 import { Icon } from '@iconify/react';
6
 import { Icon } from '@iconify/react';
8
 
7
 
9
-import { Stack, TextField, IconButton, InputAdornment, Button, Backdrop, CircularProgress } from '@mui/material';
8
+import { 
9
+    Stack, TextField, IconButton, InputAdornment, 
10
+    Button, Backdrop, CircularProgress,
11
+} from '@mui/material';
12
+
10
 import eyeFill from '@iconify/icons-eva/eye-fill';
13
 import eyeFill from '@iconify/icons-eva/eye-fill';
11
 import eyeOffFill from '@iconify/icons-eva/eye-off-fill';
14
 import eyeOffFill from '@iconify/icons-eva/eye-off-fill';
12
 import toast, { Toaster } from 'react-hot-toast';
15
 import toast, { Toaster } from 'react-hot-toast';
16
+import { V1, V2 } from '../../Utils/HTTP'
13
 
17
 
14
-// import { Visibility as eyeFill ,VisibilityOff as eyeOffFill } from '@mui/icons-material/';
15
-// ----------------------------------------------------------------------
16
 export function RegisterForm() {
18
 export function RegisterForm() {
17
 
19
 
18
     // const navigate = useNavigate();
20
     // const navigate = useNavigate();
36
     });
38
     });
37
 
39
 
38
     const formik = useFormik({
40
     const formik = useFormik({
41
+
39
         initialValues: {
42
         initialValues: {
40
             firstName: '',
43
             firstName: '',
41
             lastName: '',
44
             lastName: '',
44
             password_confirm: ''
47
             password_confirm: ''
45
         },
48
         },
46
         validationSchema: RegisterSchema,
49
         validationSchema: RegisterSchema,
47
-        onSubmit: (values) => {
48
-            console.log("values > " ,values)
49
-            setOpen(true);
50
+        onSubmit: async (values) => {
51
+            // setOpen(true);
50
             let body = {
52
             let body = {
51
                 nombre : values.firstName,
53
                 nombre : values.firstName,
52
                 apelidos : values.lastName,
54
                 apelidos : values.lastName,
59
                 "fechacumple": "2021-01-01",
61
                 "fechacumple": "2021-01-01",
60
                 "telefono" : "45435345",
62
                 "telefono" : "45435345",
61
             }
63
             }
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
 
64
 
65
+            let url = 'http://204.48.25.93:8081/registro'
66
+            // let url = 'http://psicoadmin.ditca.org:8081/registro'
67
+            V1(url, body);
68
+            // V2(url, body);
69
+            setOpen(false)
70
+            //
87
         }
71
         }
72
+
88
     });
73
     });
89
 
74
 
90
     const { errors, touched, handleSubmit, getFieldProps } = formik;
75
     const { errors, touched, handleSubmit, getFieldProps } = formik;

+ 5 - 9
src/Pages/Login.jsx

1
 import * as React from 'react';
1
 import * as React from 'react';
2
 import toast, { Toaster } from 'react-hot-toast';
2
 import toast, { Toaster } from 'react-hot-toast';
3
-// import jwt_decode from "jwt-decode";
3
+import jwt_decode from "jwt-decode";
4
 
4
 
5
 import { 
5
 import { 
6
     Paper, Box, Grid, Checkbox, FormControlLabel, Typography,
6
     Paper, Box, Grid, Checkbox, FormControlLabel, Typography,
7
     TextField, CssBaseline, Button, Avatar,
7
     TextField, CssBaseline, Button, Avatar,
8
-    Backdrop, CircularProgress
8
+    Backdrop, CircularProgress,
9
 } from '@mui/material'
9
 } from '@mui/material'
10
 
10
 
11
 import { createTheme, ThemeProvider } from '@mui/material/styles';
11
 import { createTheme, ThemeProvider } from '@mui/material/styles';
57
             setOpen(true)
57
             setOpen(true)
58
 
58
 
59
             let request = new Service(`/user?user=${email}&password=${password}`)
59
             let request = new Service(`/user?user=${email}&password=${password}`)
60
-
61
             request
60
             request
62
-            .post_({})
61
+            .post({})
63
             .then( response => {
62
             .then( response => {
64
-                console.log(response);
65
-
66
                 let { token, nombre, apelidos } = response;
63
                 let { token, nombre, apelidos } = response;
67
                 toast.success(`Bienvenido ${nombre} ${apelidos}!!`)
64
                 toast.success(`Bienvenido ${nombre} ${apelidos}!!`)
68
                 token = token.replace("Bearer ", "")
65
                 token = token.replace("Bearer ", "")
69
-                // token = jwt_decode(token);
70
-                console.log("TOKEN >> ", token)
71
-
66
+                let user_permissions = jwt_decode(token);
67
+                console.log("TOKEN >> ", token, 'decrypt', user_permissions )
72
                 setTimeout( () => {
68
                 setTimeout( () => {
73
                     setOpen(false)
69
                     setOpen(false)
74
                     auth.login(token)
70
                     auth.login(token)

+ 81 - 12
src/Pages/Register.jsx

2
 import { Link as RouterLink } from 'react-router-dom';
2
 import { Link as RouterLink } from 'react-router-dom';
3
 
3
 
4
 import { styled } from '@mui/material/styles';
4
 import { styled } from '@mui/material/styles';
5
-import { Box, Card, Link, Container, Typography } from '@mui/material';
5
+import { 
6
+    Box, Card, Link, Container, Typography,
7
+    StepLabel,Step,Stepper, Button,Paper, StepContent
8
+} from '@mui/material';
6
 import AuthLayout from '../Components/Register/AuthLayout';
9
 import AuthLayout from '../Components/Register/AuthLayout';
7
 
10
 
8
 import Page from '../Components/Register/Page';
11
 import Page from '../Components/Register/Page';
37
     padding: theme.spacing(12, 0)
40
     padding: theme.spacing(12, 0)
38
 }));
41
 }));
39
 
42
 
40
-// ----------------------------------------------------------------------
43
+const steps = [
44
+    {
45
+        label: 'Información de tu cuenta',
46
+        description: <RegisterForm/>
47
+    },
48
+    {
49
+        label: 'Datos Personales',
50
+        description:
51
+        'An ad group contains one or more ads which target a shared set of keywords.',
52
+    },
53
+];
41
 
54
 
42
 export function Register() {
55
 export function Register() {
43
 
56
 
50
         }    
63
         }    
51
     }, [auth,navigate])
64
     }, [auth,navigate])
52
 
65
 
66
+    const [activeStep, setActiveStep] = React.useState(0);
67
+
68
+    const handleNext = () => {
69
+        setActiveStep((prevActiveStep) => prevActiveStep + 1);
70
+    };
71
+
72
+    const handleBack = () => {
73
+        setActiveStep((prevActiveStep) => prevActiveStep - 1);
74
+    };
75
+
76
+    const handleReset = () => {
77
+        setActiveStep(0);
78
+    };
53
 
79
 
54
     return (
80
     return (
55
         <RootStyle title="Register | Minimal-UI">
81
         <RootStyle title="Register | Minimal-UI">
80
                     </Box>
106
                     </Box>
81
 
107
 
82
 
108
 
83
-                    <RegisterForm />
84
-
85
-                    <Typography variant="body2" align="center" sx={{ color: 'text.secondary', mt: 3 }}>
86
-                        Estoy de acuerdo con las {" "}
87
-                        <Link underline="always" sx={{ color: "#d32f2f" }}>
88
-                            Condiciones de servicio
89
-                        </Link>
90
-                        {" "}y{" "}
91
-                        <Link underline="always" sx={{ color: "#d32f2f" }}>
92
-                            Política de privacidad
109
+                    <Stepper activeStep={activeStep} orientation="vertical">
110
+    {steps.map((step, index) => (
111
+          <Step key={step.label}>
112
+            <StepLabel
113
+              optional={
114
+                index === 2 ? (
115
+                  <Typography variant="caption">Last step</Typography>
116
+                ) : null
117
+              }
118
+            >
119
+              {step.label}
120
+            </StepLabel>
121
+            <StepContent>
122
+              {step.description}
123
+              <Box sx={{ mb: 2 }}>
124
+                <div>
125
+                  <Button
126
+                    variant="contained"
127
+                    onClick={handleNext}
128
+                    sx={{ mt: 1, mr: 1 }}
129
+                  >
130
+                    {index === steps.length - 1 ? 'Finish' : 'Continue'}
131
+                  </Button>
132
+                  <Button
133
+                    disabled={index === 0}
134
+                    onClick={handleBack}
135
+                    sx={{ mt: 1, mr: 1 }}
136
+                  >
137
+                    Back
138
+                  </Button>
139
+                </div>
140
+              </Box>
141
+            </StepContent>
142
+          </Step>
143
+        ))}                    
144
+                    </Stepper>
145
+ {activeStep === steps.length && (
146
+        <Paper square elevation={0} sx={{ p: 3 }}>
147
+          <Typography>All steps completed - you&apos;re finished</Typography>
148
+          <Button onClick={handleReset} sx={{ mt: 1, mr: 1 }}>
149
+            Reset
150
+          </Button>
151
+        </Paper>
152
+      )}
153
+
154
+        <Typography variant="body2" align="center" sx={{ color: 'text.secondary', mt: 3 }}>
155
+        Estoy de acuerdo con las {" "}
156
+        <Link underline="always" sx={{ color: "#d32f2f" }}>
157
+        Condiciones de servicio
158
+        </Link>
159
+        {" "}y{" "}
160
+        <Link underline="always" sx={{ color: "#d32f2f" }}>
161
+        Política de privacidad
93
                         </Link>
162
                         </Link>
94
                         .
163
                         .
95
                     </Typography>
164
                     </Typography>

+ 33 - 58
src/Utils/HTTP.js

1
+import $ from 'jquery'
2
+
3
+export const V2 = (url, data) => {
4
+    $.ajax({ 
5
+        type:"POST",
6
+        url:url,
7
+        data: JSON.stringify(data), 
8
+        contentType: 'application/json',
9
+        success: function(res) {
10
+            console.log('jquery resp',res);
11
+            console.log("Added");
12
+        },
13
+        error: function(xhr, status, err) {
14
+            console.error(xhr, status, err.toString());
15
+        }
16
+    })  
17
+}
18
+
19
+export const V1 =  async (url, body)  => {
20
+    let response = await fetch(url, {
21
+        method: 'POST',
22
+        headers: {
23
+            'Accept': 'application/json',
24
+            'Content-Type': 'application/json'
25
+        },
26
+        body : JSON.stringify(body)
27
+    })
28
+
29
+    let req =  await response.json(); 
30
+    console.log('register request',req )
31
+}
32
+
1
 export class Service {
33
 export class Service {
2
 
34
 
3
     constructor(path){
35
     constructor(path){
7
         // this.api =  'http://psicoadmin.ditca.org:8081/user?user=patrik&password=12345'
39
         // this.api =  'http://psicoadmin.ditca.org:8081/user?user=patrik&password=12345'
8
     }
40
     }
9
 
41
 
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){
42
+    async post(body){
30
         console.log('body >> ', body)
43
         console.log('body >> ', body)
31
         let response = await fetch(this.url, {
44
         let response = await fetch(this.url, {
32
             method: "POST",
45
             method: "POST",
35
         return await response.json(); 
48
         return await response.json(); 
36
     }
49
     }
37
     
50
     
38
-    async post(body){
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
-    }
76
 }
51
 }
77
 
52