Skip to content

Commit

Permalink
encrypt & decrypt fetch requests
Browse files Browse the repository at this point in the history
  • Loading branch information
Shubham-Lal committed Nov 11, 2023
1 parent 36a518e commit 2b80a4a
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 58 deletions.
11 changes: 8 additions & 3 deletions api/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const generateOTP = require('../utils/generateOTP.js');
const sendOTP = require('../mail/sendOTP.js');
const getDataUrl = require('../middleware/dataURL.js');
const { v2 } = require('cloudinary');
const CryptoJS = require('crypto-js');

exports.userRegisterCredential = async (req, res) => {
try {
Expand Down Expand Up @@ -219,9 +220,8 @@ exports.userLogin = async (req, res) => {

res.status(201).json({
success: true,
user,
msg: "Login success!",
loginToken,
loginToken
});
}
catch (error) {
Expand All @@ -234,9 +234,14 @@ exports.userLogin = async (req, res) => {

exports.loadUser = async (req, res) => {
try {
const encryptedData = CryptoJS.AES.encrypt(
JSON.stringify({ user: req.user }),
process.env.DATA_ENCRYPTION_SECRET_KEY
).toString();

res.status(200).json({
success: true,
user: req.user,
data: encryptedData,
});
}
catch (error) {
Expand Down
8 changes: 7 additions & 1 deletion api/controllers/certController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const Certificate = require('../models/certModel.js');
const CryptoJS = require('crypto-js');

exports.verifyCertificate = async (req, res) => {
try {
Expand All @@ -10,9 +11,14 @@ exports.verifyCertificate = async (req, res) => {
});
}

const encryptedData = CryptoJS.AES.encrypt(
JSON.stringify(certData),
process.env.DATA_ENCRYPTION_SECRET_KEY
).toString();

res.status(200).json({
success: true,
data: certData,
data: encryptedData,
});
}
catch (error) {
Expand Down
54 changes: 6 additions & 48 deletions client/src/pages/Certificate/VerifyCertificate.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react'
import React, { useEffect } from 'react'
import { useParams } from 'react-router-dom'
import useWindowHeight from '../../utils/useWindowHeight'
import { useCertStore } from '../../store/useCertStore'
Expand All @@ -12,55 +12,11 @@ const VerifyCertificate = () => {
const { certificateID } = useParams()
const { height, isReady } = useWindowHeight()

const [certLoading, setCertLoading] = useState(true)
const { certData, setCertData } = useCertStore()
const { certLoading, certData, fetchCertData } = useCertStore()

useEffect(() => {
const fetchCertData = async () => {
try {
setCertLoading(true)

const CustomHeader = new Headers()
CustomHeader.append('Content-Type', 'application/json')
const config = {
method: 'GET',
headers: CustomHeader
}

fetch(`/api/cert/verify/${certificateID}`, config)
.then(response => response.json())
.then(result => {
if (result.success === true) {
setCertData({
_id: result.data._id,
fullName: result.data.fullName,
verifyURL: result.data.verifyURL,
verifyQR: result.data.verifyQR,
skillBoostQR: result.data.skillBoostQR,
certificate: result.data.certificate,
message: ''
})
// setTimeout(() => {
setCertLoading(false)
// }, 2000)
}

if (result.success === false) {
setCertData({
message: result.msg
})
setCertLoading(false)
}
})
} catch (error) {
setCertData({
message: 'Error. Try again after some time!'
})
}
}

if (certificateID) fetchCertData()
}, [certificateID])
if (certificateID) fetchCertData(certificateID);
}, [certificateID]);

return (
<div
Expand All @@ -72,6 +28,7 @@ const VerifyCertificate = () => {
>
<div className='h-full pt-[120px] flex flex-col gap-5 items-center justify-center'>
{certLoading ? (
// Fetching Certificate
<>
<div className='relative w-[400px] h-[300px] md:w-[625px] md:h-[426px] lg:w-[950px] lg:h-[652px] border rounded'>
<Skeleton className='absolute -z-10 -top-[4px] left-0 w-full h-full' />
Expand All @@ -95,6 +52,7 @@ const VerifyCertificate = () => {
</div>
</>
) : certData.message ? (
// Error fetching Certificate
<div className='relative bg-white w-[400px] h-[300px] md:w-[625px] md:h-[426px] lg:w-[950px] lg:h-[652px] border rounded text-xl font-extrabold'>
<p className='absolute top-0 left-0 w-full h-full flex items-center justify-center z-50 text-[#4A90F4] text-xl font-extrabold'>
{certData.message}
Expand Down
15 changes: 9 additions & 6 deletions client/src/store/useAuthStore.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { create } from 'zustand';
import { toast } from 'sonner';
import crypto from "crypto-js";

const SECRET_KEY = "THIS_IS_THE_SECRET_KEY_FOR_GDSC_BIT";

export const useAuthStore = create((set) => ({
user: null,
Expand Down Expand Up @@ -165,16 +168,11 @@ export const useLoginStore = create(() => ({
if (result.success === true) {
toast.success(result.msg, { duration: 7500 });
localStorage.setItem("login_token", result.loginToken);
useAuthStore.getState().setUser(result.user);
useAuthStore.getState().setVerifyLoading(false);
useAuthStore.getState().setVerifySuccess(true);
navigate("/");
}

if (result.success === false) {
toast.error(result.msg, { duration: 7500 });
useAuthStore.getState().setVerifyLoading(false);
useAuthStore.getState().setVerifySuccess(false);
}
})
}
Expand All @@ -196,7 +194,12 @@ export const useLoginStore = create(() => ({
.then(response => response.json())
.then(result => {
if (result.success === true) {
useAuthStore.getState().setUser(result.user);
const decryptedData = JSON.parse(
crypto.AES.decrypt(result.data, SECRET_KEY).toString(
crypto.enc.Utf8
)
);
useAuthStore.getState().setUser(decryptedData.user);
useAuthStore.getState().setVerifyLoading(false);
useAuthStore.getState().setVerifySuccess(true);
}
Expand Down
49 changes: 49 additions & 0 deletions client/src/store/useCertStore.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { create } from 'zustand';
import crypto from "crypto-js";

const SECRET_KEY = "THIS_IS_THE_SECRET_KEY_FOR_GDSC_BIT";

export const useCertStore = create((set) => ({
certLoading: true,
setCertLoading: (certLoading) => set({ certLoading: certLoading }),
certData: {
_id: "",
fullName: "",
Expand All @@ -11,4 +16,48 @@ export const useCertStore = create((set) => ({
message: ""
},
setCertData: (certData) => set({ certData: certData }),
fetchCertData: async (certificateID) => {
try {
useCertStore.getState().setCertLoading(true)

const CustomHeader = new Headers()
CustomHeader.append('Content-Type', 'application/json')
const config = {
method: 'GET',
headers: CustomHeader
}

await fetch(`/api/cert/verify/${certificateID}`, config)
.then(response => response.json())
.then(result => {
if (result.success === true) {
const decryptedData = JSON.parse(
crypto.AES.decrypt(result.data, SECRET_KEY).toString(
crypto.enc.Utf8
)
);
useCertStore.getState().setCertData({
_id: decryptedData._id,
fullName: decryptedData.fullName,
verifyURL: decryptedData.verifyURL,
verifyQR: decryptedData.verifyQR,
skillBoostQR: decryptedData.skillBoostQR,
certificate: decryptedData.certificate,
message: ''
})
}

if (result.success === false) {
useCertStore.getState().setCertData({
message: result.msg
})
}
})
.finally(() => useCertStore.getState().setCertLoading(false))
} catch (error) {
useCertStore.getState().setCertData({
message: 'Error. Try again after some time!'
})
}
}
}));

0 comments on commit 2b80a4a

Please sign in to comment.