🐛 fix(App.tsx): import missing AuthContext and getLoggedUser functions to fix compilation error

🐛 fix(authContext.tsx): change import statement for Users type to fix compilation error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): change type of userData state to Users type to fix compilation error
🐛 fix(authContext.tsx): remove unnecessary import statement for LoginType to fix unused import warning
🐛 fix(authContext.tsx): remove unnecessary import statement for api to fix unused import warning
🐛 fix(authContext.tsx): change import statement for Cookies to fix unused import warning
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext.tsx): add missing comma in AuthContext initial value object to fix syntax error
🐛 fix(authContext

🔀 refactor(auth.ts): update types and imports in AuthContextType for better code organization and clarity
This commit is contained in:
Cristhian Zanforlin Lousa 2023-08-12 15:19:00 -03:00
commit 75c1499eaa
8 changed files with 86 additions and 56 deletions

View file

@ -14,6 +14,8 @@ import { alertContext } from "./contexts/alertContext";
import { locationContext } from "./contexts/locationContext";
import { TabsContext } from "./contexts/tabsContext";
import Router from "./routes";
import { AuthContext } from "./contexts/authContext";
import { getLoggedUser } from "./controllers/API";
export default function App() {
let { setCurrent, setShowSideBar, setIsStackedOpen } =

View file

@ -1,8 +1,7 @@
import { createContext, useEffect, useState } from "react";
import { AuthContextType, userData } from "../types/contexts/auth";
import { LoginType } from "../types/api";
import { api } from "../controllers/API/api";
import Cookies from 'universal-cookie';
import Cookies from "universal-cookie";
import { Users } from "../types/api";
import { AuthContextType } from "../types/contexts/auth";
const initialValue: AuthContextType = {
isAuthenticated: false,
@ -14,7 +13,7 @@ const initialValue: AuthContextType = {
userData: null,
setUserData: () => {},
getAuthentication: () => false,
authenticationErrorCount: 0
authenticationErrorCount: 0,
};
export const AuthContext = createContext<AuthContextType>(initialValue);
@ -23,7 +22,7 @@ export function AuthProvider({ children }): React.ReactElement {
const [accessToken, setAccessToken] = useState<string | null>(null);
const [refreshToken, setRefreshToken] = useState<string | null>(null);
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
const [userData, setUserData] = useState<userData>(null);
const [userData, setUserData] = useState<Users>(null);
const cookies = new Cookies();
useEffect(() => {
@ -33,25 +32,25 @@ export function AuthProvider({ children }): React.ReactElement {
}
}, []);
function getAuthentication(){
const storedRefreshToken = cookies.get('refresh_token');
const storedAccess = cookies.get('access_token');
function getAuthentication() {
const storedRefreshToken = cookies.get("refresh_token");
const storedAccess = cookies.get("access_token");
const auth = storedAccess && storedRefreshToken ? true : false;
return auth;
}
function login(newAccessToken: string, refreshToken: string) {
cookies.set('access_token', newAccessToken, { path: '/' });
cookies.set('refresh_token', refreshToken, { path: '/' });
cookies.set("access_token", newAccessToken, { path: "/" });
cookies.set("refresh_token", refreshToken, { path: "/" });
setAccessToken(newAccessToken);
setRefreshToken(refreshToken);
setIsAuthenticated(true);
}
function logout() {
cookies.remove('access_token', { path: '/' });
cookies.remove('refresh_token', { path: '/' });
cookies.remove("access_token", { path: "/" });
cookies.remove("refresh_token", { path: "/" });
setUserData(null);
setAccessToken(null);
setRefreshToken(null);
setIsAuthenticated(false);
@ -77,7 +76,6 @@ export function AuthProvider({ children }): React.ReactElement {
logout();
}
}
return (
// !! to convert string to boolean
@ -92,7 +90,7 @@ export function AuthProvider({ children }): React.ReactElement {
setUserData,
userData,
getAuthentication,
authenticationErrorCount: 0
authenticationErrorCount: 0,
}}
>
{children}

View file

@ -388,9 +388,14 @@ export async function renewAccessToken(token: string) {
}
}
export async function getAllUsers(): Promise<Users> {
export async function getLoggedUser(): Promise<Users> {
try {
return await api.get(`${BASE_URL_API}user`);
const res = await api.get(`${BASE_URL_API}user`);
if (res.status === 200) {
return res.data;
}
} catch (error) {
console.log("Error:", error);
throw error;

View file

@ -1,6 +1,6 @@
import * as Form from "@radix-ui/react-form";
import { Eye, EyeOff } from "lucide-react";
import { useEffect, useState } from "react";
import { useContext, useEffect, useState } from "react";
import { Button } from "../../components/ui/button";
import { Checkbox } from "../../components/ui/checkbox";
import { CONTROL_NEW_USER } from "../../constants/constants";
@ -11,6 +11,7 @@ import {
} from "../../types/components";
import { nodeIconsLucide } from "../../utils/styleUtils";
import BaseModal from "../baseModal";
import { AuthContext } from "../../contexts/authContext";
export default function UserManagementModal({
title,
@ -34,6 +35,11 @@ export default function UserManagementModal({
const [isDisabled, setIsDisabled] = useState(data?.is_disabled ?? false);
const [isSuperUser, setIsSuperUser] = useState(data?.is_superuser ?? false);
const [inputState, setInputState] = useState<UserInputType>(CONTROL_NEW_USER);
const { userData} = useContext(AuthContext);
console.log(userData);
function handleInput({
target: { name, value },
@ -236,28 +242,30 @@ export default function UserManagementModal({
</Form.Control>
</div>
</Form.Field>
{userData?.is_superuser && (
<Form.Field name="is_superuser">
<div>
<Form.Label className="data-[invalid]:label-invalid mr-3">
Superuser
</Form.Label>
<Form.Control asChild>
<Checkbox
checked={isSuperUser}
value={isSuperUser}
id="is_superuser"
className="relative top-0.5"
onCheckedChange={(value) => {
handleInput({
target: { name: "is_superuser", value },
});
setIsSuperUser(value);
}}
/>
</Form.Control>
</div>
</Form.Field>
<div>
<Form.Label className="data-[invalid]:label-invalid mr-3">
Superuser
</Form.Label>
<Form.Control asChild>
<Checkbox
checked={isSuperUser}
value={isSuperUser}
id="is_superuser"
className="relative top-0.5"
onCheckedChange={(value) => {
handleInput({
target: { name: "is_superuser", value },
});
setIsSuperUser(value);
}}
/>
</Form.Control>
</div>
</Form.Field>
)}
</div>
</div>

View file

@ -5,7 +5,7 @@ import { Input } from "../../../components/ui/input";
import { CONTROL_LOGIN_STATE } from "../../../constants/constants";
import { alertContext } from "../../../contexts/alertContext";
import { AuthContext } from "../../../contexts/authContext";
import { onLogin } from "../../../controllers/API";
import { getLoggedUser, onLogin } from "../../../controllers/API";
import { LoginType } from "../../../types/api";
import {
inputHandlerEventType,
@ -17,7 +17,7 @@ export default function LoginAdminPage() {
const [inputState, setInputState] =
useState<loginInputStateType>(CONTROL_LOGIN_STATE);
const { login } = useContext(AuthContext);
const { login, getAuthentication, setUserData } = useContext(AuthContext);
const { password, username } = inputState;
const { setErrorData } = useContext(alertContext);
@ -36,6 +36,7 @@ export default function LoginAdminPage() {
onLogin(user)
.then((user) => {
login(user.access_token, user.refresh_token);
getUser();
navigate("/admin/");
})
.catch((error) => {
@ -46,6 +47,16 @@ export default function LoginAdminPage() {
});
}
function getUser(){
if(getAuthentication){
setTimeout(() => {
getLoggedUser().then((user) => {
setUserData(user);
}).catch((error) => {});
}, 1000);
}
}
return (
<div className="flex h-full w-full flex-col items-center justify-center bg-muted">
<div className="flex w-72 flex-col items-center justify-center gap-2">

View file

@ -1,4 +1,4 @@
import _ from "lodash";
import _, { set } from "lodash";
import { X } from "lucide-react";
import { useEffect, useRef, useState,useContext } from "react";
import PaginatorComponent from "../../components/PaginatorComponent";

View file

@ -8,7 +8,7 @@ import { Input } from "../../components/ui/input";
import { CONTROL_LOGIN_STATE } from "../../constants/constants";
import { alertContext } from "../../contexts/alertContext";
import { AuthContext } from "../../contexts/authContext";
import { onLogin } from "../../controllers/API";
import { getLoggedUser, onLogin } from "../../controllers/API";
import { LoginType } from "../../types/api";
import {
inputHandlerEventType,
@ -20,7 +20,7 @@ export default function LoginPage(): JSX.Element {
useState<loginInputStateType>(CONTROL_LOGIN_STATE);
const { password, username } = inputState;
const { login } = useContext(AuthContext);
const { login, getAuthentication, setUserData } = useContext(AuthContext);
const navigate = useNavigate();
const { setErrorData } = useContext(alertContext);
@ -38,6 +38,7 @@ export default function LoginPage(): JSX.Element {
onLogin(user)
.then((user) => {
login(user.access_token, user.refresh_token);
getUser();
navigate("/");
})
.catch((error) => {
@ -48,6 +49,16 @@ export default function LoginPage(): JSX.Element {
});
}
function getUser(){
if(getAuthentication){
setTimeout(() => {
getLoggedUser().then((user) => {
setUserData(user);
}).catch((error) => {});
}, 1000);
}
}
return (
<Form.Root
onSubmit={(event) => {
@ -55,7 +66,7 @@ export default function LoginPage(): JSX.Element {
event.preventDefault();
return;
}
signIn();
const data = Object.fromEntries(new FormData(event.currentTarget));
event.preventDefault();
}}
@ -115,7 +126,7 @@ export default function LoginPage(): JSX.Element {
</div>
<div className="w-full">
<Form.Submit asChild>
<Button onClick={() => signIn()} className="mr-3 mt-6 w-full">
<Button className="mr-3 mt-6 w-full">
Sign in
</Button>
</Form.Submit>

View file

@ -1,3 +1,5 @@
import { Users } from "../api";
export type AuthContextType = {
isAuthenticated: boolean;
accessToken: string | null;
@ -5,15 +7,8 @@ export type AuthContextType = {
login: (accessToken: string, refreshToken: string) => void;
logout: () => void;
refreshAccessToken: (refreshToken: string) => Promise<void>;
userData: userData | null;
setUserData: (userData: userData | null) => void;
userData: Users | null;
setUserData: (userData: Users | null) => void;
getAuthentication: () => boolean;
authenticationErrorCount: number;
};
export type userData = {
id: string;
name: string;
email: string;
role: string;
};