Skip to content

Commit

Permalink
add login
Browse files Browse the repository at this point in the history
  • Loading branch information
CraysCA committed Nov 15, 2023
1 parent cf8731c commit f09d369
Show file tree
Hide file tree
Showing 11 changed files with 301 additions and 145 deletions.
62 changes: 62 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
},
"dependencies": {
"@tabler/icons-react": "^2.34.0",
"buffer": "^6.0.3",
"react": "^18.2.0",
"react-cookie": "^6.1.1",
"react-dom": "^18.2.0",
Expand Down
21 changes: 21 additions & 0 deletions src/api/fetchLogin.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Buffer } from 'buffer'
export const fetchLogin = async credentials => {
try {
const { email, password } = credentials
const url = `${import.meta.env.VITE_BACKEND_API}/auth/login`
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization:
'Basic ' + Buffer.from(email + ':' + password).toString('base64'),
},
cache: 'no-store',
})
const data = await response.json()

return data.success ? data.data : null
} catch (error) {
console.log(error)
}
}
18 changes: 18 additions & 0 deletions src/api/fetchRegister.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export const fetchRegister = async credentials => {
try {
const url = `${import.meta.env.VITE_BACKEND_API}/users/`
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials),
cache: 'no-store',
})
const data = await response.json()

return data
} catch (error) {
console.log(error)
}
}
48 changes: 39 additions & 9 deletions src/components/Navbar.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Link, useLocation } from 'react-router-dom'
import { Link, useLocation, Navigate } from 'react-router-dom'
import {
IconHome,
IconTruckReturn,
Expand All @@ -8,12 +8,13 @@ import {
} from '@tabler/icons-react'
import { useContext } from 'react'
import { CartContext } from '../context/ShoppingCartContext'
import { useAuth } from '../auth/AuthProvider'

const sidebarMenu = [
{
name: 'home',
src: <IconHome width={33} height={33} />,
to: '/dashboard',
to: '/',
},
{
name: 'order',
Expand All @@ -28,6 +29,25 @@ const sidebarMenu = [
]

export const Navbar = () => {
const auth = useAuth()
const user = auth.getUser()

const checkAuth = e => {
if (!auth.isAuthenticated) {
e.preventDefault()
alert('necesitas iniciar sesión')
}
}

const validLogout = e => {
if (auth.isAuthenticated) {
e.preventDefault()
const text = 'Desea cerrar sesión?'
console.log(confirm(text))
if (confirm(text) == true) return true
}
}

const [cart, setCart] = useContext(CartContext)

const quantity = cart.reduce((acc, item) => acc + item.quantity, 0)
Expand All @@ -37,10 +57,13 @@ export const Navbar = () => {
return (
<div>
<header className="bg-white sticky left-0 top-0 h-30 w-full text-black shadow-sm">
<ul className="flex flex-row items-center justify-center gap-4 pl-4">
<h1 className="text-2xl font-bold text-center my-5 flex flex-grow basis-0 cursor-pointer text-blue-800">
VITAL<span className=" text-red-500">CLINIC</span>
</h1>
<ul className="flex flex-row items-center justify-center gap-4 pl-4 ">
<Link to="/" className="flex-grow basis-0">
<h1 className="text-2xl font-bold text-center my-5 flex flex-grow basis-0 cursor-pointer text-blue-800">
VITAL<span className=" text-red-500">CLINIC</span>
</h1>
</Link>

<form className="flex-grow basis-0">
<div className="relative">
<div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
Expand Down Expand Up @@ -70,19 +93,26 @@ export const Navbar = () => {
</form>
<nav className="flex flex-row items-center justify-center gap-2 flex-grow basis-0 ">
<Link
to="#"
className="p-3 rounded-sm hover:bg-gray-200 cursor-pointer">
//onClick={validLogout}
to={auth.isAuthenticated ? '/logout' : '/login'}
className="p-3 rounded-sm hover:bg-gray-200 cursor-pointer flex items-center gap-2">
<IconUserCircle width={28} height={28} />
{auth.isAuthenticated ? (
<p> Hola, {user.name} </p>
) : (
'Iniciar Sesión'
)}
</Link>

<Link
to="/dashboard"
to="/"
className="p-3 rounded-sm hover:bg-gray-200 cursor-pointer">
<IconShoppingBag width={28} height={28} />
</Link>

<Link
to="/shopping-cart"
onClick={checkAuth}
className="p-3 rounded-sm hover:bg-gray-200 cursor-pointer relative inline-flex items-center">
<IconShoppingCart width={28} height={28} />
{quantity === 0 ? (
Expand Down
10 changes: 5 additions & 5 deletions src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { RouterProvider, createHashRouter } from 'react-router-dom'
import './index.css'

import Login from './pages/Login'
import Dashboard from './pages/Dashboard'
import MainHub from './pages/MainHub'
import Logout from './pages/Logout'
import NotFound from './pages/NotFound'
import Register from './pages/Register'
Expand All @@ -14,6 +14,10 @@ import ShoppingCartProvider from './context/ShoppingCartContext'
import ShoppingCart from './pages/ShoppingCart'

const router = createHashRouter([
{
path: '/',
element: <MainHub />,
},
{
path: '/login',
element: <Login />,
Expand All @@ -30,10 +34,6 @@ const router = createHashRouter([
path: '/shopping-cart',
element: <ShoppingCart />,
},
{
path: '/dashboard',
element: <Dashboard />,
},
// {
// path: '/',
// element: <ProtectedRoute />,
Expand Down
30 changes: 18 additions & 12 deletions src/pages/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useState } from 'react'
import { useAuth } from '../auth/AuthProvider'
import { Navigate } from 'react-router-dom'
import GetUserData from '../auth/DecodeToken'
import { fetchLogin } from '../api/fetchLogin'

export default function Login() {
const [credentials, setCredentials] = useState({
Expand All @@ -16,26 +17,31 @@ export default function Login() {

const auth = useAuth()

if (auth.isAuthenticated) return <Navigate to="/dashboard" replace={true} />
if (auth.isAuthenticated) return <Navigate to="/" replace={true} />

const handlerChange = e => {
setCredentials({ ...credentials, [e.target.name]: e.target.value })
}

const handlerSubmit = async e => {
e.preventDefault()
const token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6ImNyaXN0IiwibGFzdG5hbWUiOiJ0ZXN0IiwiZW1haWwiOiJ0ZXN0QHRlc3QuY29tIiwidHlwZSI6MSwiY3VzdG9tZXJJZCI6bnVsbCwiaWF0IjoxNjk0MzgzMDQ2LCJleHAiOjE2OTQ0Njk0NDZ9.4GGXIzSN-tmaGyPLh0ziVxpIJ9fxXUlf7RgpZldTjbQ'
if (token) {
const user = GetUserData(token)
const userData = { token, user }

auth.saveUser(userData)
toast.promise(fetchLogin(credentials), {
loading: 'Iniciando Sesión...',
success: token => {
if (token) {
const user = GetUserData(token)
const userData = { token, user }

return <Navigate to="/dashboard" replace={true} />
} else {
toast.error('Correo o contraseña incorrectos')
}
auth.saveUser(userData)

return <Navigate to="/" replace={true} />
} else {
toast.error('No se pudo iniciar sesión')
}
},
error: 'Correo o contraseña incorrectos',
})
}

return (
Expand Down Expand Up @@ -112,7 +118,7 @@ export default function Login() {
</p> */}
</div>
</div>
<Toaster />
<Toaster richColors />
</main>
)
}
2 changes: 1 addition & 1 deletion src/pages/Logout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ export default function Logout() {
const auth = useAuth()
auth.logout()

return <Navigate to="/login" />
return <Navigate to="/" />
}
Loading

0 comments on commit f09d369

Please sign in to comment.