Skip to content

Commit

Permalink
feat(login): apply login and token usage on admin routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Mikadows committed May 22, 2022
1 parent aa17131 commit 0232f3e
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 61 deletions.
63 changes: 52 additions & 11 deletions src/components/Auth/Login.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,52 @@
import React from 'react';
import React, {useEffect} from 'react';
import Lottie from 'react-lottie-player';
import loadingSplash from '../../assets/lotties/splash-loading.json';
import { Link } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import { useToken } from '../../hooks/token';
import { login } from '../../hooks/auth/register';
import LoginRequest from '../../hooks/auth/requests/LoginRequest';
import { useToasts } from 'react-toast-notifications';

const Login: React.FC = () => {
const { addToast } = useToasts();
const navigate = useNavigate();
const { token, setToken } = useToken();

useEffect(() => {
if (token) {
navigate('/admin');
}
}, [token, navigate]);

const loginUser = async (event: any) => {
event.preventDefault();

const request = new LoginRequest(
event.target.username.value,
event.target.password.value,
);

if (request.username?.trim() === '' || request.password?.trim() === '') {
addToast(`Email or password are empty`, {
appearance: 'error',
autoDismiss: true,
});
return;
}

try {
const response = await login(request);
addToast(`Welcome ${request.username}`, {
appearance: 'info',
autoDismiss: true,
});
setToken(response);
navigate('/admin/products');
} catch (e) {
addToast(`Login failed`, { appearance: 'error', autoDismiss: true });
}
};

return (
<div>
<section className="h-screen gradient-form bg-gray-200">
Expand All @@ -23,36 +66,34 @@ const Login: React.FC = () => {
Admin Panel - FI-Sweets
</h4>
</div>
<form>
<form onSubmit={loginUser}>
<p className="mb-4">Please login to your account</p>
<div className="mb-4">
<input
type="text"
className="form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded transition ease-in-out m-0 focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none"
id="exampleFormControlInput1"
placeholder="Username"
id="username"
placeholder="Email"
/>
</div>
<div className="mb-4">
<input
type="password"
className="form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded transition ease-in-out m-0 focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none"
id="exampleFormControlInput1"
id="password"
placeholder="Password"
/>
</div>
<div className="text-center pt-1 mb-3 pb-1">
<Link to={'/admin'}>
<button type="submit">
<div
className="inline-block px-6 py-2.5 text-white font-medium text-xs leading-tight uppercase rounded shadow-md bg-blue-500 hover:bg-blue-700 hover:shadow-lg focus:shadow-lg focus:outline-none focus:ring-0 active:shadow-lg transition duration-150 ease-in-out w-full mb-3"
// type="button"
>
Log in
</div>
</Link>
<div className="text-gray-500" >
Forgot password?
</div>
</button>
<div className="text-gray-500">Forgot password?</div>
</div>
</form>
</div>
Expand Down
33 changes: 5 additions & 28 deletions src/components/Products/ModifyProduct.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ const ModifyProduct: React.FC<ModifyProductProps> = ({
const response = await updateSweet(request);
if (response) {
await queryClient.invalidateQueries(`all-sweets`);
await queryClient.invalidateQueries(`sweet-${sweetData.id}`);
addToast(`Sweet updated`, { appearance: 'success', autoDismiss: true });
setOpenedModal(false);
} else {
Expand All @@ -85,30 +86,10 @@ const ModifyProduct: React.FC<ModifyProductProps> = ({
return (
<div className="overflow-x-auto">
<div className="grid bg-white rounded-lg shadow-xl w-fit">
<div className="flex justify-center py-4">
<div className="flex bg-purple-200 rounded-full md:p-4 p-2 border-2 border-purple-300">
<svg
className="w-8 h-8 text-white"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"
/>
</svg>
</div>
</div>

{/*<form>*/}
<form onSubmit={handleModifySweet}>
<div className="flex justify-center">
<div className="flex">
<h1 className="text-gray-600 font-bold md:text-2xl text-xl">
<h1 className="pt-5 text-gray-600 font-bold md:text-2xl text-xl">
Product modification
</h1>
</div>
Expand Down Expand Up @@ -214,15 +195,11 @@ const ModifyProduct: React.FC<ModifyProductProps> = ({
className="hidden"
onChange={onSubmitUploadFile}
/>
{/*<input*/}
{/* type="hidden"*/}
{/* {...register("thumbnail", { required: true })}*/}
{/*/>*/}
</label>
</div>
<div>
{sweetData?.images?.map((image, index) => (
<p key={index}>{image}</p>
<div className="flex pt-3">
{sweetData?.images?.map((image) => (
<img className="mr-3 w-16 h-16" src={image} alt="thumbnail" />
))}
</div>
</div>
Expand Down
17 changes: 11 additions & 6 deletions src/components/Products/ProductList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const ProductList: React.FC = () => {
<div>Produits en ligne</div>
</div>

<table className="row-start-2 col-start-2 col-end-5">
<table className="row-start-2 col-start-2 col-end-5 h-40">
<thead>
<tr className="bg-gray-200 text-gray-600 uppercase text-sm leading-normal">
<th className="py-3 px-6 text-left">Product</th>
Expand All @@ -54,7 +54,8 @@ const ProductList: React.FC = () => {
))}
</tbody>
</table>
<table className="row-start-2 col-start-5 col-end-8">

<table className="row-start-2 col-start-5 col-end-8 h-40">
<thead>
<tr className="bg-gray-200 text-gray-600 uppercase text-sm leading-normal">
<th className="py-3 px-6 text-left">Product</th>
Expand Down Expand Up @@ -132,11 +133,10 @@ const ProductTableRow: React.FC<ProductRowProps> = ({ _id, product }) => {
_id % 2 === 0 ? 'dark:bg-gray-100' : 'dark:bg-gray-300 bg-gray-50'
} hover:bg-gray-100`;

async function handlePublishSweet(id: string) {
const publishRequest = new PublishSweetRequest(id, 'BANNER');
async function handlePublishSweet(id: string, highlight: string) {
const publishRequest = new PublishSweetRequest(id, highlight);
const result = await publishSweet(publishRequest);
// refresh sweets
console.log(result);
await queryClient.invalidateQueries('all-sweets');
addToast(`Sweet published ${result.name.value}`, {
appearance: 'info',
Expand Down Expand Up @@ -216,7 +216,12 @@ const ProductTableRow: React.FC<ProductRowProps> = ({ _id, product }) => {
</svg>
</div>
<div
onClick={() => handlePublishSweet(product.id ? product.id : '')}
onClick={() =>
handlePublishSweet(
product.id ? product.id : '',
product.highlight ? product.highlight : '',
)
}
className="w-4 mr-2 transform hover:text-purple-500 hover:scale-110"
>
<svg
Expand Down
14 changes: 7 additions & 7 deletions src/hooks/auth/register.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { commonRequest } from '../common/request';
import { commonRequest, loginRequest } from '../common/request';
import LoginRequest from './requests/LoginRequest';

const login = async (username: string, password: string): Promise<string> => {
const { data } = await commonRequest({
const login = async (request: LoginRequest): Promise<string> => {
const token = await loginRequest({
url: `/auth/login`,
method: 'POST',
data: {
username: username,
password: password,
username: request.username,
password: request.password,
},
});

return data.access_token;
return token.slice(7);
};

const register = async (
Expand Down
9 changes: 9 additions & 0 deletions src/hooks/auth/requests/LoginRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default class LoginRequest {
username: string | undefined;
password: string | undefined;

constructor(username: string | undefined, password: string | undefined) {
this.username = username;
this.password = password;
}
}
20 changes: 18 additions & 2 deletions src/hooks/common/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,23 @@ const authenticatedRequest = (options: AxiosRequestConfig) => {
};

const commonRequest = (options: AxiosRequestConfig) => {
const onSuccess = (response: any) => response;
const onSuccess = (response: any) => {
console.log(response.headers['authorization']); //['Authorization']
return response;
};
const onError = (error: any) => {
throw error;
// optionaly catch errors and add some additional logging here
// return error;
};

return client({ timeout: 5000, ...options })
.then(onSuccess)
.catch(onError);
};

const loginRequest = (options: AxiosRequestConfig) => {
const onSuccess = (response: any) => response.headers['authorization'];
const onError = (error: any) => {
throw error;
// optionaly catch errors and add some additional logging here
Expand All @@ -34,4 +50,4 @@ const commonRequest = (options: AxiosRequestConfig) => {
.catch(onError);
};

export { authenticatedRequest, commonRequest };
export { authenticatedRequest, commonRequest, loginRequest };
14 changes: 7 additions & 7 deletions src/hooks/sweets/sweetsHooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useQuery } from 'react-query';
import { commonRequest } from '../common/request';
import { authenticatedRequest } from '../common/request';
import ProductModelRow from '../../components/Products/ProductModelRow';
import CreateSweetRequest from './requests/CreateSweetRequest';
import PublishSweetRequest from './requests/PublishSweetRequest';
Expand All @@ -8,7 +8,7 @@ import UpdateSweetRequest from './requests/UpdateSweetRequest';

export function useSweets() {
return useQuery<ProductModelRow[], Error>(`all-sweets`, async () => {
const { data } = await commonRequest({
const { data } = await authenticatedRequest({
url: `admin/sweets`,
});
return data;
Expand All @@ -18,7 +18,7 @@ export function useSweets() {
export function useSweetById(id: string) {
return useQuery<ProductModel, Error>(`sweet-${id}`, async () => {
if (id) {
const { data } = await commonRequest({
const { data } = await authenticatedRequest({
url: `admin/sweets/${id}`,
});
return data;
Expand All @@ -27,7 +27,7 @@ export function useSweetById(id: string) {
}

export async function createSweet(createSweetRequest: CreateSweetRequest) {
const { data } = await commonRequest({
const { data } = await authenticatedRequest({
url: `admin/sweets`,
method: 'POST',
data: createSweetRequest,
Expand All @@ -36,7 +36,7 @@ export async function createSweet(createSweetRequest: CreateSweetRequest) {
}

export async function publishSweet(publishSweetRequest: PublishSweetRequest) {
const { data } = await commonRequest({
const { data } = await authenticatedRequest({
url: `admin/sweets/publish`,
method: 'PUT',
data: publishSweetRequest,
Expand All @@ -48,7 +48,7 @@ export async function uploadSweetImage(sweetId: string, image: File) {
const formData = new FormData();
formData.append('image', image);

const { data } = await commonRequest({
const { data } = await authenticatedRequest({
url: `admin/sweets/${sweetId}/image`,
method: 'POST',
data: formData,
Expand All @@ -58,7 +58,7 @@ export async function uploadSweetImage(sweetId: string, image: File) {
}

export async function updateSweet(request: UpdateSweetRequest) {
const { data } = await commonRequest({
const { data } = await authenticatedRequest({
url: `admin/sweets`,
method: 'PUT',
data: request,
Expand Down

0 comments on commit 0232f3e

Please sign in to comment.