From c80ea168ab0e2876040130fcf9679d2d40b77b69 Mon Sep 17 00:00:00 2001 From: Bett Date: Thu, 7 Dec 2023 19:18:27 +0300 Subject: [PATCH] Improving auth: using cookies & localstorage to persist sessions --- controllers/auth/auth.js | 17 +- controllers/auth/public_auth.js | 9 +- pages/_app.js | 12 +- pages/admin_offices/add.js | 5 +- pages/admin_offices/edit/[id].js | 7 +- pages/admin_offices/index.js | 4 +- pages/community-units/approve/[id].js | 8 +- pages/community-units/index.js | 5 +- pages/dashboard/index.js | 9 +- pages/facilities/[id].js | 15 +- pages/facilities/add.js | 5 +- pages/facilities/approve_reject/[id].js | 809 ++++++++++++------------ pages/facilities/edit/[id].js | 7 +- pages/facilities/index.js | 44 +- pages/facilities/regulate/[id].js | 7 +- pages/facilities/upgrade/[id].js | 5 +- pages/index.js | 8 - pages/logout.js | 1 + pages/public/chu/[id].js | 2 +- pages/reports/index.js | 5 +- pages/system_setup/index.js | 14 +- 21 files changed, 511 insertions(+), 487 deletions(-) diff --git a/controllers/auth/auth.js b/controllers/auth/auth.js index e43bb123..bff15e08 100644 --- a/controllers/auth/auth.js +++ b/controllers/auth/auth.js @@ -48,7 +48,7 @@ const getToken = (req, res, refresh_token, creds) => { bod.client_id = process.env.CLIENT_ID bod.client_secret = process.env.CLIENT_SECRET - console.log({ token_url: process.env.TOKEN_URL }) + // console.log({ token_url: process.env.TOKEN_URL }) return fetch(process.env.TOKEN_URL, { 'method': 'POST', 'headers': { @@ -182,9 +182,17 @@ const logUserIn = (req, res, creds, was) => { const getUserDetails = async (token, url) => { if (typeof window != "undefined") { - let savedSession = window.sessionStorage.getItem('user') + // let savedSession = window.sessionStorage.getItem('user') + // if (savedSession && savedSession.length > 0) { + // savedSession = JSON.parse(window.sessionStorage.getItem('user')) + // } + // if (savedSession && savedSession?.id && savedSession?.id.length > 0) { + // console.log('Saved session: ', savedSession) + // return savedSession + // } + let savedSession = window.localStorage.getItem('user') if (savedSession && savedSession.length > 0) { - savedSession = JSON.parse(window.sessionStorage.getItem('user')) + savedSession = JSON.parse(window.localStorage.getItem('user')) } if (savedSession && savedSession?.id && savedSession?.id.length > 0) { console.log('Saved session: ', savedSession) @@ -212,7 +220,8 @@ const getUserDetails = async (token, url) => { } if (typeof window !== "undefined") { // console.log('getUserDetails returning ', response) - window.sessionStorage.setItem('user', JSON.stringify(response)) + // window.sessionStorage.setItem('user', JSON.stringify(response)) + window.localStorage.setItem('user', JSON.stringify(response)) } return response }).catch(err => { diff --git a/controllers/auth/public_auth.js b/controllers/auth/public_auth.js index 9b041a60..9eee619a 100644 --- a/controllers/auth/public_auth.js +++ b/controllers/auth/public_auth.js @@ -155,9 +155,11 @@ const checkToken = async (req, res, isProtected, creds) => { const getUserDetails = async (token, url) => { if (typeof window != "undefined") { - let savedSession = window.sessionStorage.getItem('user') + // let savedSession = window.sessionStorage.getItem('user') + let savedSession = window.localStorage.getItem('user') if (savedSession && savedSession.length > 0) { - savedSession = JSON.parse(window.sessionStorage.getItem('user')) + // savedSession = JSON.parse(window.sessionStorage.getItem('user')) + savedSession = JSON.parse(window.localStorage.getItem('user')) } if (savedSession && savedSession?.id && savedSession?.id.length > 0) { console.log('Saved session: ', savedSession) @@ -185,7 +187,8 @@ const getUserDetails = async (token, url) => { } if (typeof window !== "undefined") { // console.log('getUserDetails returning ', response) - window.sessionStorage.setItem('user', JSON.stringify(response)) + // window.sessionStorage.setItem('user', JSON.stringify(response)) + window.localStorage.setItem('user', JSON.stringify(response)) } return response }).catch(err => { diff --git a/pages/_app.js b/pages/_app.js index 117b603d..1485da86 100644 --- a/pages/_app.js +++ b/pages/_app.js @@ -32,22 +32,26 @@ export default function App(props) { { let user if (typeof window !== "undefined") { - user = JSON.parse(window.sessionStorage.getItem('user')) - } + // user = JSON.parse(window.sessionStorage.getItem('user')) + user = JSON.parse(window.localStorage.getItem('user')) + } + // console.log({'_app_user':user}) return user })()}> { let userGroup if (typeof window !== "undefined") { - userGroup = JSON.parse(window.sessionStorage.getItem('user'))?.groups[0]?.name + // userGroup = JSON.parse(window.sessionStorage.getItem('user'))?.groups[0]?.name + userGroup = JSON.parse(window.localStorage.getItem('user'))?.groups[0]?.name } return userGroup })()}> { let userPermissions if (typeof window !== "undefined") { - userPermissions = JSON.parse(window.sessionStorage.getItem('user'))?.all_permissions + // userPermissions = JSON.parse(window.sessionStorage.getItem('user'))?.all_permissions + userPermissions = JSON.parse(window.localStorage.getItem('user'))?.all_permissions } return userPermissions diff --git a/pages/admin_offices/add.js b/pages/admin_offices/add.js index 0decd93b..0449976c 100644 --- a/pages/admin_offices/add.js +++ b/pages/admin_offices/add.js @@ -7,11 +7,13 @@ import { } from '@heroicons/react/solid'; import Select from 'react-select'; import Link from 'next/link' +import { UserContext } from '../../providers/user'; const FormData = require('form-data'); function AddAdminOffice(props) { + const userCtx = React.useContext(UserContext); // Form drop down options const countyOptions = props['0']?.counties; const subCountyOptions = props['1']?.sub_counties; @@ -19,6 +21,7 @@ function AddAdminOffice(props) { const [county, setCounty] = useState(''); const [hide, setHide] = useState(false) + const [user, setUser] = useState(userCtx) // Drop down select options data const formRef = useRef(null) @@ -73,7 +76,7 @@ function AddAdminOffice(props) { } useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx) if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/admin_offices/edit/[id].js b/pages/admin_offices/edit/[id].js index ebba7700..f724f110 100644 --- a/pages/admin_offices/edit/[id].js +++ b/pages/admin_offices/edit/[id].js @@ -8,11 +8,14 @@ import { ChevronDoubleLeftIcon, } from '@heroicons/react/solid'; import Select from 'react-select'; +import { UserContext } from '../../../providers/user'; const _ = require('underscore') function EditAdminOffice(props) { + const userCtx = React.useContext(UserContext); + // Form drop down options const counties = props['0']?.counties ?? {counties: []}; const sub_counties = props['1']?.sub_counties ?? {sub_counties: []}; @@ -56,7 +59,7 @@ function EditAdminOffice(props) { setHide(!hide) } - const [user, setUser] = useState(null) + const [user, setUser] = useState(userCtx) //Form Field data const formRef = useRef(null) @@ -138,7 +141,7 @@ function EditAdminOffice(props) { } useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx) if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/admin_offices/index.js b/pages/admin_offices/index.js index 781bca22..53cc7243 100644 --- a/pages/admin_offices/index.js +++ b/pages/admin_offices/index.js @@ -43,6 +43,7 @@ const AdminOffices = (props) => { const router = useRouter() const userPermissions = useContext(PermissionContext) + const userCtx = useContext(UserContext) const rows = props?.data?.results?.map(({ id, county_name, sub_county_name, name, is_national, phone_number, email }) => ({ id, county_name, sub_county_name, name, is_national: is_national == true ? 'Yes' : 'No', phone_number, email })) const columns = [ @@ -74,10 +75,11 @@ const AdminOffices = (props) => { , } ] + const [user, setUser] = useState(userCtx) useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx) if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/community-units/approve/[id].js b/pages/community-units/approve/[id].js index 6e9160b5..ec3146f2 100644 --- a/pages/community-units/approve/[id].js +++ b/pages/community-units/approve/[id].js @@ -19,11 +19,12 @@ import CommunityUnitSideMenu from '../../../components/CommunityUnitSideMenu'; const ApproveCommunityUnit = (props) => { - const router = useRouter() + const router = useRouter(); + const userCtx = useContext(UserContext); let cu = props.data; // Reference hooks for the services section - const [user, setUser] = useState(null); + const [user, setUser] = useState(userCtx); const [isCHULDetails, setIsCHULDetails] = useState(true); const [appRejReason, setAppRejReason] = useState('') const [isApproveReject, setIsApproveReject] = useState(false); @@ -49,7 +50,6 @@ const ApproveCommunityUnit = (props) => { {value: `${cu.facility_county}`, label: 'County'}, ] - const userCtx = useContext(UserContext) let reject = '' useEffect(() => @@ -64,7 +64,7 @@ const ApproveCommunityUnit = (props) => { }, [cu, reject]); useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx); if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/community-units/index.js b/pages/community-units/index.js index 4c8c5c10..455d56b0 100644 --- a/pages/community-units/index.js +++ b/pages/community-units/index.js @@ -12,9 +12,12 @@ import { useRouter } from 'next/router'; import { Menu } from '@headlessui/react'; import { ChevronDownIcon } from '@heroicons/react/outline'; import CommunityUnitSideMenu from '../../components/CommunityUnitSideMenu'; +import { UserContext } from '../../providers/user'; const CommunityUnit = (props) => { + const userCtx = React.useContext(UserContext); + const [user, setUser] = useState(userCtx); const router = useRouter(); const cus = props?.data?.results; const filters = props?.filters; @@ -41,7 +44,7 @@ const CommunityUnit = (props) => { // Check user for authentication useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx) if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/dashboard/index.js b/pages/dashboard/index.js index f586fb03..548ea4e0 100644 --- a/pages/dashboard/index.js +++ b/pages/dashboard/index.js @@ -75,7 +75,7 @@ const Dashboard = (props) => { const [isquarterOpen, setIsquarterOpen] = useState(false); const [isOpen, setIsOpen] = useState(false); const [drillDown, setDrillDown] = useState({}) - const [user, setUser] = useState(null) + const [user, setUser] = useState(userCtx) const [subcounties, setSubcounties] = useState([]) const [counties, setCounties] = useState([]) const [wards, setWards] = useState([]) @@ -149,7 +149,7 @@ const Dashboard = (props) => { useEffect(() => { - + setUser(userCtx) let mtd = true if (mtd) { @@ -187,9 +187,10 @@ const Dashboard = (props) => { if(userCtx?.groups[0].id == 2) fetchWards(user?.user_sub_counties[0]?.sub_county ?? null) if(userCtx?.groups[0].id == 1) fetchSubCounties(userCtx?.county) - if(userCtx?.groups[0].id == 7) fetchCounties() + if(userCtx?.groups[0].id == 7) fetchCounties(); + + setUser(userCtx) - const user = JSON.parse(sessionStorage.getItem('user')) if(user.id === 6){ router.push('/auth/login') }else{ diff --git a/pages/facilities/[id].js b/pages/facilities/[id].js index 9fa20b6f..a855d7c8 100644 --- a/pages/facilities/[id].js +++ b/pages/facilities/[id].js @@ -63,7 +63,7 @@ const Facility = (props) => { const filters = [] - const [user, setUser] = useState(null); + const [user, setUser] = useState(userCtx); const [open, setOpen] = useState(true); const [openCloseModal, setOpenCloseModal] = useState(true) @@ -95,22 +95,15 @@ const Facility = (props) => { useEffect(() => { setIsClient(true) - }, []) - - - - // let reject = '' - - useEffect(() => { - - if (userCtx) setUser(userCtx); + + if (userCtx) setUser(userCtx); console.log({userCtx}) return () => { }; }, [isClosingFacility, isReasonRejected]); useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx); if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/facilities/add.js b/pages/facilities/add.js index 9550f2dd..4ca53c6f 100644 --- a/pages/facilities/add.js +++ b/pages/facilities/add.js @@ -5,11 +5,13 @@ import Link from "next/link"; import Head from "next/head"; import FacilitySideMenu from "../../components/FacilitySideMenu"; import {useState, useEffect, createContext} from 'react'; +import { UserContext } from "../../providers/user"; export const FormOptionsContext = createContext({}); export default function AddFacility(props) { + const userCtx = React.useContext(UserContext); const filters = []; const [khisSynched, setKhisSynched] = useState(false); @@ -18,9 +20,10 @@ export default function AddFacility(props) { const [allFctsSelected, setAllFctsSelected] = useState(false); const [title, setTitle] = useState(''); const [isClient, setIsClient] = useState(false) + const [user, setUser] = useState(userCtx) useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx) if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/facilities/approve_reject/[id].js b/pages/facilities/approve_reject/[id].js index 977e26dc..b8e5aaed 100644 --- a/pages/facilities/approve_reject/[id].js +++ b/pages/facilities/approve_reject/[id].js @@ -1,16 +1,16 @@ -import { useState, useEffect, useContext } from'react' +import { useState, useEffect, useContext } from 'react' import MainLayout from '../../../components/MainLayout'; import FacilitySideMenu from '../../../components/FacilitySideMenu'; import { useRouter } from 'next/router'; import { - validateRejectFacility, - approveRejectFacilityUpdates, - approveRejectFacility - } from "../../../controllers/facility/approveRejectFacility"; + validateRejectFacility, + approveRejectFacilityUpdates, + approveRejectFacility +} from "../../../controllers/facility/approveRejectFacility"; import { ChevronRightIcon, - XCircleIcon, + XCircleIcon, ChevronDownIcon, CheckCircleIcon, InformationCircleIcon @@ -20,29 +20,31 @@ import FacilityUpdatesTable from "../../../components/FacilityUpdatesTable"; import { checkToken } from "../../../controllers/auth/auth"; import Link from 'next/link' import FacilityDetailsTabs from '../../../components/FacilityDetailsTabs'; -import {Formik, Form, Field} from 'formik'; -import {useAlert} from 'react-alert' +import { Formik, Form, Field } from 'formik'; +import { useAlert } from 'react-alert' +import { UserContext } from '../../../providers/user'; function ApproveReject(props) { - + const userCtx = React.useContext(UserContext); + const [user, setUser] = useState(userCtx); // console.log({props}) const alert = useAlert() const router = useRouter() const [isFacDetails, setIsFacDetails] = useState(true); - + const [khisSynched, setKhisSynched] = useState(false); - const [facilityFeedBack, setFacilityFeedBack] = useState([]) - const [pathId, setPathId] = useState('') + const [facilityFeedBack, setFacilityFeedBack] = useState([]) + const [pathId, setPathId] = useState('') const [allFctsSelected, setAllFctsSelected] = useState(false); - const [title, setTitle] = useState('') + const [title, setTitle] = useState('') const facility = props["0"]?.data; - const {facility_updated_json } = props["2"]?.updates ?? {facility_updated_json: null}; + const { facility_updated_json } = props["2"]?.updates ?? { facility_updated_json: null }; const filters = [] // const [reject, setReject] = useState(null) @@ -50,310 +52,309 @@ function ApproveReject(props) { const [isClient, setIsClient] = useState(false) - - useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) - if(user.id === 6){ - router.push('/auth/login') - } - setIsClient(true) - }, []) + useEffect(() => { + setUser(userCtx) + if (user.id === 6) { + router.push('/auth/login') + } + + setIsClient(true) + }, []) let reject - if(isClient) { + if (isClient) { return ( -
- - - {/* Breadcramps */} - -
- - Home - - {"/"} - - Facilities - - {"/"} - - {facility?.official_name ?? ""} ( # - {facility?.code || "NO_CODE"} ) +
+ + + {/* Breadcramps */} + +
+ + Home + + {"/"} + + Facilities + + {"/"} + + {facility?.official_name ?? ""} ( # + {facility?.code || "NO_CODE"} ) + +
+ + {/* Header */} +
+ + {/* Header Bunner */} +
+
+ router.push(`/facilities/${facility?.id}`)} className="text-4xl hover:text-blue-600 cursor-pointer tracking-tight font-bold leading-tight"> + {facility?.official_name} +
+ + #{facility?.code || "NO_CODE"} + + +
+
+
+
+ {facility?.operational || facility?.operation_status_name ? ( + + + Operational + + ) : ( + "" + )} + {facility?.approved ? ( + + + Validated + + ) : ( + + + Not Validated + + )} + {facility?.has_edits && ( + + + Has changes + + )} + {facility?.is_complete ? ( + + + Completed{" "} + + ) : ( + + + Incomplete{" "} + + )} + {facility?.closed && ( + + + Closed + + )} +
+
+
+
+ + {/* Facility Side Menu Filters */} +
+ +
+ +
+

+ { + facility?.is_approved ? + 'Approve/Reject Facility' : + 'Validate/Reject Facility' + } - {/* Header */} -
- - {/* Header Bunner */} -
-
- router.push(`/facilities/${facility?.id}`)} className="text-4xl hover:text-blue-600 cursor-pointer tracking-tight font-bold leading-tight"> - {facility?.official_name} - -
- - #{facility?.code || "NO_CODE"} - - -
-
-
-
- {facility?.operational || facility?.operation_status_name ? ( - - - Operational - - ) : ( - "" - )} - {facility?.approved ? ( - - - Validated - - ) : ( - - - Not Validated - - )} - {facility?.has_edits && ( - - - Has changes - - )} - {facility?.is_complete ? ( - - - Completed{" "} - - ) : ( - - - Incomplete{" "} - - )} - {facility?.closed && ( - - - Closed - - )} -
-
-
-
+

+ + + {/* Facility details */} +
+
+ +

+ {facility?.operation_status_name || " - "} +

- {/* Facility Side Menu Filters */} -
- +
+ +

+ {facility?.keph_level_name || " - "} +

-
-

- { - facility?.is_approved ? - 'Approve/Reject Facility': - 'Validate/Reject Facility' - } +
+ +

+ {facility?.admission_status_name || " - "} +

+
+
+ +

+ {facility?.facility_type_name || " - "} +

+
+ + +
+ +

+ {facility?.county || " - "} +

+
+ + + {facility?.date_established && ( +
+ +

+ {new Date(facility?.date_established).toLocaleDateString( + "en-GB", + { year: "numeric", month: "long", day: "numeric" } + ) || " - "} +

+
+ )} +

+ + + {/* Facility details hidden section */} + +
+ +
+ + + {!isFacDetails && + +
+ {/* {console.log({isFacDetails})} */} + +
+ } + + {/* Comments and Updates Section */} + +
+

+ {facility?.has_edits ? 'Approve Updates' : facility?.is_approved ? "Approval / Reject facility" : "Comment on the validation"} +

+ {facility?.is_approved} + { + // if facility is not validated and has no edits + if (!facility?.approved && !facility?.has_edits) { + validateRejectFacility(facility?.id, reject, comment, alert) + } + // if facility is validated and has edits + if (facility?.approved && facility?.has_edits) { + approveRejectFacilityUpdates(reject, alert, facility?.latest_update) + } + // if facility is not approved and is validated + if (!facility?.approved_national_level && facility?.approved) { + console.log('FACILITY WILL BE APPROVED') + approveRejectFacility(facility?.id, comment, alert, reject) + } + } + } + > +
+ + { + !facility?.has_edits ? + + : + // Facility Updates Table + + + } + +
+ + - - - - {/* Facility details */} -
-
- -

- {facility?.operation_status_name || " - "} -

-
- -
- -

- {facility?.keph_level_name || " - "} -

-
- -
- -

- {facility?.admission_status_name || " - "} -

-
-
- -

- {facility?.facility_type_name || " - "} -

-
- - -
- -

- {facility?.county || " - "} -

-
- - - {facility?.date_established && ( -
- -

- {new Date(facility?.date_established).toLocaleDateString( - "en-GB", - { year: "numeric", month: "long", day: "numeric" } - ) || " - "} -

-
- )} -
- - - {/* Facility details hidden section */} - -
+ {!facility?.approved_national_level && -
- - - {!isFacDetails && - -
- {/* {console.log({isFacDetails})} */} - -
- } + type="submit" + className="bg-red-600 text-gray-100 -md p-2 font-semibold" + onClick={() => reject = facility?.has_edits ? false : facility?.is_approved ? false : true} - {/* Comments and Updates Section */} - -
-

- {facility?.has_edits ? 'Approve Updates' : facility?.is_approved ? "Approval / Reject facility" : "Comment on the validation"} -

- {facility?.is_approved} - { - // if facility is not validated and has no edits - if (!facility?.approved && !facility?.has_edits) - { - validateRejectFacility(facility?.id, reject, comment, alert) - } - // if facility is validated and has edits - if(facility?.approved && facility?.has_edits) { - approveRejectFacilityUpdates(reject, alert, facility?.latest_update) - } - // if facility is not approved and is validated - if(!facility?.approved_national_level && facility?.approved) { - console.log('FACILITY WILL BE APPROVED') - approveRejectFacility(facility?.id, comment, alert, reject) - } - } - } - > - - - { - !facility?.has_edits ? - - : - // Facility Updates Table - - - } - -
- - - - {!facility?.approved_national_level && - - } -
- -
+ {facility?.has_edits ? 'Decline Updates' : facility?.approved_national_level ? '' : 'Reject Facility'} + + }
+ + +
-
-
+
+
) } @@ -363,78 +364,78 @@ function ApproveReject(props) { } ApproveReject.getInitialProps = async (ctx) => { - const allOptions = []; - - if (ctx.query.q) { - const query = ctx.query.q; - if (typeof window !== "undefined" && query.length > 2) { - window.location.href = `/facilities?q=${query}`; - } else { - if (ctx.res) { - ctx.res.writeHead(301, { - Location: "/facilities?q=" + query, - }); - ctx.res.end(); - return {}; - } + const allOptions = []; + + if (ctx.query.q) { + const query = ctx.query.q; + if (typeof window !== "undefined" && query.length > 2) { + window.location.href = `/facilities?q=${query}`; + } else { + if (ctx.res) { + ctx.res.writeHead(301, { + Location: "/facilities?q=" + query, + }); + ctx.res.end(); + return {}; } } - return checkToken(ctx.req, ctx.res) - .then((t) => { - if (t.error) { - throw new Error("Error checking token"); - } else { - let token = t.token; - let _data; - let url = - process.env.NEXT_PUBLIC_API_URL + - "/facilities/facilities/" + - ctx.query.id + - "/"; - return fetch(url, { - headers: { - Authorization: "Bearer " + token, - Accept: "application/json", - }, - }) - .then((r) => r.json()) - .then(async (json) => { - allOptions.push({ - data: json, - }) - - - // fetch ward boundaries - if (json) { - try { - const response = await fetch( - `${process.env.NEXT_PUBLIC_API_URL}/common/wards/${json.ward}/`, - { - headers: { - Authorization: "Bearer " + token, - Accept: "application/json", - }, - } - ); - - _data = await response.json(); - - const [lng, lat] = - _data?.ward_boundary.properties.center.coordinates; - - allOptions.push({ - geoLocation: JSON.parse(JSON.stringify(_data?.ward_boundary)), - center: [lat, lng], - }); - } catch (e) { - console.error("Error in fetching ward boundaries", e.message); - } + } + return checkToken(ctx.req, ctx.res) + .then((t) => { + if (t.error) { + throw new Error("Error checking token"); + } else { + let token = t.token; + let _data; + let url = + process.env.NEXT_PUBLIC_API_URL + + "/facilities/facilities/" + + ctx.query.id + + "/"; + return fetch(url, { + headers: { + Authorization: "Bearer " + token, + Accept: "application/json", + }, + }) + .then((r) => r.json()) + .then(async (json) => { + allOptions.push({ + data: json, + }) + + + // fetch ward boundaries + if (json) { + try { + const response = await fetch( + `${process.env.NEXT_PUBLIC_API_URL}/common/wards/${json.ward}/`, + { + headers: { + Authorization: "Bearer " + token, + Accept: "application/json", + }, + } + ); + + _data = await response.json(); + + const [lng, lat] = + _data?.ward_boundary.properties.center.coordinates; + + allOptions.push({ + geoLocation: JSON.parse(JSON.stringify(_data?.ward_boundary)), + center: [lat, lng], + }); + } catch (e) { + console.error("Error in fetching ward boundaries", e.message); } - - // fetch facility updates - if(json){ - try{ - const facilityUpdateData = await (await fetch( `${process.env.NEXT_PUBLIC_API_URL}/facilities/facility_updates/${json.latest_update}/`, + } + + // fetch facility updates + if (json) { + try { + const facilityUpdateData = await (await fetch(`${process.env.NEXT_PUBLIC_API_URL}/facilities/facility_updates/${json.latest_update}/`, { headers: { Authorization: "Bearer " + token, @@ -442,46 +443,46 @@ ApproveReject.getInitialProps = async (ctx) => { }, } )).json() - - allOptions.push({ - updates: facilityUpdateData, - }) - - } - catch(e){ - console.error('Encountered error while fetching facility update data', e.message) - } + + allOptions.push({ + updates: facilityUpdateData, + }) + } - - return allOptions; - }) - .catch((err) => { - console.log("Error fetching facilities: ", err); - return { - error: true, - err: err, - data: [], - }; - }); - } - }) - .catch((err) => { - console.log("Error checking token: ", err); - if (typeof window !== "undefined" && window) { - if (ctx?.asPath) { - window.location.href = ctx?.asPath; - } else { - window.location.href = "/facilities"; - } + catch (e) { + console.error('Encountered error while fetching facility update data', e.message) + } + } + + return allOptions; + }) + .catch((err) => { + console.log("Error fetching facilities: ", err); + return { + error: true, + err: err, + data: [], + }; + }); + } + }) + .catch((err) => { + console.log("Error checking token: ", err); + if (typeof window !== "undefined" && window) { + if (ctx?.asPath) { + window.location.href = ctx?.asPath; + } else { + window.location.href = "/facilities"; } - setTimeout(() => { - return { - error: true, - err: err, - data: [], - }; - }, 1000); - }); - + } + setTimeout(() => { + return { + error: true, + err: err, + data: [], + }; + }, 1000); + }); + } export default ApproveReject \ No newline at end of file diff --git a/pages/facilities/edit/[id].js b/pages/facilities/edit/[id].js index 591a48b7..ee2dcb7a 100644 --- a/pages/facilities/edit/[id].js +++ b/pages/facilities/edit/[id].js @@ -4,17 +4,20 @@ import MainLayout from '../../../components/MainLayout'; import Link from "next/link"; import Head from "next/head"; import FacilitySideMenu from "../../../components/FacilitySideMenu"; -import { useState, useEffect, createContext } from 'react'; +import React, { useState, useEffect, createContext } from 'react'; import { FormOptionsContext } from "../add"; import FacilityUpdatesTable from '../../../components/FacilityUpdatesTable' import { useRouter } from "next/router"; import { useAlert } from "react-alert"; import { all } from "underscore"; +import { UserContext } from "../../../providers/user"; export const FacilityUpdatesContext = createContext(null) export default function EditFacility(props) { + const userCtx = React.useContext(UserContext); + const [user, setUser] = useState(userCtx); const filters = []; const [khisSynched, setKhisSynched] = useState(false); @@ -47,7 +50,7 @@ export default function EditFacility(props) { // console.log({allOptions: props}) - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx) if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/facilities/index.js b/pages/facilities/index.js index fc0438f9..f81d9ac0 100644 --- a/pages/facilities/index.js +++ b/pages/facilities/index.js @@ -20,8 +20,7 @@ import NativePickers from '../../components/date-picker' // import { PermissionContext } from '../../providers/permissions' import FacilitySideMenu from '../../components/FacilitySideMenu' import { UserContext } from '../../providers/user' -import {Formik, Form, Field} from 'formik' - +import {Formik, Form, Field} from 'formik'; const FacilityHome = (props) => { @@ -35,27 +34,28 @@ const FacilityHome = (props) => { let fltrs = filters const [drillDown, setDrillDown] = useState({}) const userCtx = useContext(UserContext); + console.log({userCtx}) // const qf = props?.query?.qf ?? null if (filters && typeof filters === "object") { - filters["has_edits"] = [{ id: "has_edits", name: "Has edits" },] - filters["is_approved"] = [{ id: "is_approved", name: "Is approved" }] - filters["is_complete"] = [{ id: "is_complete", name: "Is complete" }] - filters["number_of_beds"] = [{ id: "number_of_beds", name: "Number of beds" }] - filters["number_of_cots"] = [{ id: "number_of_cots", name: "Number of cots" }] - filters["open_whole_day"] = [{ id: "open_whole_day", name: "Open whole day" }] - filters["open_weekends"] = [{ id: "open_weekends", name: "Open weekends" }] - filters["open_public_holidays"] = [{ id: "open_public_holidays", name: "Open public holidays" }] - delete fltrs.has_edits - delete fltrs.is_approved - delete fltrs.is_complete - delete fltrs.number_of_beds - delete fltrs.number_of_cots - delete fltrs.open_whole_day - delete fltrs.open_weekends - delete fltrs.open_public_holidays -} + filters["has_edits"] = [{ id: "has_edits", name: "Has edits" },] + filters["is_approved"] = [{ id: "is_approved", name: "Is approved" }] + filters["is_complete"] = [{ id: "is_complete", name: "Is complete" }] + filters["number_of_beds"] = [{ id: "number_of_beds", name: "Number of beds" }] + filters["number_of_cots"] = [{ id: "number_of_cots", name: "Number of cots" }] + filters["open_whole_day"] = [{ id: "open_whole_day", name: "Open whole day" }] + filters["open_weekends"] = [{ id: "open_weekends", name: "Open weekends" }] + filters["open_public_holidays"] = [{ id: "open_public_holidays", name: "Open public holidays" }] + delete fltrs.has_edits + delete fltrs.is_approved + delete fltrs.is_complete + delete fltrs.number_of_beds + delete fltrs.number_of_cots + delete fltrs.open_whole_day + delete fltrs.open_weekends + delete fltrs.open_public_holidays + } const multiFilters = ['service_category', 'service', 'county', 'subcounty', 'ward', 'constituency'] @@ -71,12 +71,14 @@ const FacilityHome = (props) => { const [facilityFeedBack, setFacilityFeedBack] = useState([]) const [pathId, setPathId] = useState(props?.path.split('id=')[1] || '') const [allFctsSelected, setAllFctsSelected] = useState(true); - const [isClient, setIsClient] = useState(false) + const [isClient, setIsClient] = useState(false); + const [user, setUser] = useState(userCtx) useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx) + console.log({user}) if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/facilities/regulate/[id].js b/pages/facilities/regulate/[id].js index c1632c76..b9b7dec1 100644 --- a/pages/facilities/regulate/[id].js +++ b/pages/facilities/regulate/[id].js @@ -18,10 +18,11 @@ import FacilitySideMenu from '../../../components/FacilitySideMenu' const RegulateFacility = props => { + const userCtx = useContext(UserContext) const facility = props["0"]?.data; const regulationStateOptions = props['1']?.regulation_status const [isFacDetails, setIsFacDetails] = useState(true); - const [user, setUser] = useState(null); + const [user, setUser] = useState(userCtx); const formRef = useRef(null); const regulationRef = useRef(null) @@ -33,16 +34,14 @@ const RegulateFacility = props => { const [title, setTitle] = useState('') const filters = [] - const userCtx = useContext(UserContext) let reject = '' useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx); if(user.id === 6){ router.push('/auth/login') } - if (userCtx) setUser(userCtx); return () => { setIsFacDetails(true); diff --git a/pages/facilities/upgrade/[id].js b/pages/facilities/upgrade/[id].js index a2ae717c..d48f6157 100644 --- a/pages/facilities/upgrade/[id].js +++ b/pages/facilities/upgrade/[id].js @@ -12,10 +12,13 @@ import { ChevronRightIcon, ChevronDownIcon } from '@heroicons/react/solid' import { Table, TableBody, TableCell, TableRow } from '@mui/material'; import { useAlert } from 'react-alert' import { handleFacilityUpgrades } from '../../../controllers/facility/facilityHandlers' +import { UserContext } from '../../../providers/user' const UpgradeFacility = props => { + const userCtx = React.useContext(UserContext) + const [user, setUser] = useState(userCtx) const alert = useAlert() const router = useRouter() @@ -75,7 +78,7 @@ const UpgradeFacility = props => { const [isClient, setIsClient] = useState(false) useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx); if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/index.js b/pages/index.js index ab491c2b..b4cd7bb4 100644 --- a/pages/index.js +++ b/pages/index.js @@ -82,14 +82,6 @@ const Home = (props) => { }, [isLoggedIn]) - // useEffect(() => { - // const user = JSON.parse(sessionStorage.getItem('user')); - - // if(user.id === 6){ - // router.push('/auth/login') - // } - // }, []) - if(isClient){ diff --git a/pages/logout.js b/pages/logout.js index 56aa4bd6..33c34285 100644 --- a/pages/logout.js +++ b/pages/logout.js @@ -10,6 +10,7 @@ const Logout = props => { if (!props?.error && !props?.detail) { if (typeof window !== 'undefined') { window.sessionStorage.removeItem('user') + window.localStorage.removeItem('user') window.document.cookie = 'access_token=; expires=Thu, 01 Jan 1970 00:00:00 GMT;' window.location.href = '/' } else { diff --git a/pages/public/chu/[id].js b/pages/public/chu/[id].js index 9e07143b..564b92a6 100644 --- a/pages/public/chu/[id].js +++ b/pages/public/chu/[id].js @@ -27,7 +27,7 @@ const CommunityUnit = (props) => { const center = props['1'].center useEffect(() => { if (typeof window !== 'undefined') { //auth.add_group - let usr = JSON.parse(window.sessionStorage.getItem('user')) + // let usr = JSON.parse(window.sessionStorage.getItem('user')) if(window.localStorage?.getItem(cu?.id) !== null){ setRating(JSON.parse(window.localStorage?.getItem(cu?.id))[0]) diff --git a/pages/reports/index.js b/pages/reports/index.js index 909d0e36..199a2485 100644 --- a/pages/reports/index.js +++ b/pages/reports/index.js @@ -16,6 +16,7 @@ import { // import { Box } from '@material-ui/core'; import { propsToGridData } from '../../components/ReportsData'; +import { UserContext } from '../../providers/user'; const StyledDataGrid = styled(DataGrid)(() => ({ @@ -33,6 +34,8 @@ const StyledDataGrid = styled(DataGrid)(() => ({ function Reports(props) { + const userCtx = React.useContext(UserContext); + const [user, setUser] = useState(userCtx); // Constants @@ -67,7 +70,7 @@ function Reports(props) { }, [reportTitle]) useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx) if(user.id === 6){ router.push('/auth/login') } diff --git a/pages/system_setup/index.js b/pages/system_setup/index.js index bfbb5ba7..46530da9 100644 --- a/pages/system_setup/index.js +++ b/pages/system_setup/index.js @@ -50,6 +50,7 @@ import { import { styled } from '@mui/material/styles'; import { PencilAltIcon } from '@heroicons/react/outline'; +import { UserContext } from '../../providers/user'; const StyledDataGrid = styled(DataGrid)(() => ({ @@ -67,6 +68,8 @@ const StyledDataGrid = styled(DataGrid)(() => ({ const system_setup = (props) => { + const userCtx = useContext(UserContext) + const userPermissions = useContext(PermissionContext) @@ -99,6 +102,7 @@ const system_setup = (props) => { const handleClose = () => setOpen(false); const [sbcty_constituency, setSbctyConstituency] = useState([]); const [value, setValue] = React.useState('1'); + const [user, setUser] = useState(userCtx); const [isClient, setIsClient] = useState(false) const [columns, setColumns] = useState([ @@ -152,7 +156,7 @@ const system_setup = (props) => { useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) + setUser(userCtx); if(user.id === 6){ router.push('/auth/login') } @@ -161,14 +165,6 @@ const system_setup = (props) => { router.push('/unauthorized') } - },[]) - - - useEffect(() => { - const user = JSON.parse(sessionStorage.getItem('user')) - if(user.id === 6){ - router.push('/auth/login') - } setIsClient(true) }, [])