Skip to content

Commit

Permalink
Improving auth: using cookies & localstorage to persist sessions
Browse files Browse the repository at this point in the history
  • Loading branch information
benzerbett committed Dec 7, 2023
1 parent 33add27 commit c80ea16
Show file tree
Hide file tree
Showing 21 changed files with 511 additions and 487 deletions.
17 changes: 13 additions & 4 deletions controllers/auth/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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': {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 => {
Expand Down
9 changes: 6 additions & 3 deletions controllers/auth/public_auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 => {
Expand Down
12 changes: 8 additions & 4 deletions pages/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,26 @@ export default function App(props) {
<UserContext.Provider value={(() => {
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

})()}>
<UserGroupContext.Provider value={(() => {
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
})()}>
<PermissionContext.Provider value={(() => {
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

Expand Down
5 changes: 4 additions & 1 deletion pages/admin_offices/add.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,21 @@ 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;
const [status, setStatus] = useState(null)

const [county, setCounty] = useState('');
const [hide, setHide] = useState(false)
const [user, setUser] = useState(userCtx)

// Drop down select options data
const formRef = useRef(null)
Expand Down Expand Up @@ -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')
}
Expand Down
7 changes: 5 additions & 2 deletions pages/admin_offices/edit/[id].js
Original file line number Diff line number Diff line change
Expand Up @@ -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: []};
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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')
}
Expand Down
4 changes: 3 additions & 1 deletion pages/admin_offices/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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')
}
Expand Down
8 changes: 4 additions & 4 deletions pages/community-units/approve/[id].js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -49,7 +50,6 @@ const ApproveCommunityUnit = (props) => {
{value: `${cu.facility_county}`, label: 'County'},
]

const userCtx = useContext(UserContext)

let reject = ''
useEffect(() =>
Expand All @@ -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')
}
Expand Down
5 changes: 4 additions & 1 deletion pages/community-units/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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')
}
Expand Down
9 changes: 5 additions & 4 deletions pages/dashboard/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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([])
Expand Down Expand Up @@ -149,7 +149,7 @@ const Dashboard = (props) => {


useEffect(() => {

setUser(userCtx)

let mtd = true
if (mtd) {
Expand Down Expand Up @@ -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{
Expand Down
15 changes: 4 additions & 11 deletions pages/facilities/[id].js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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')
}
Expand Down
5 changes: 4 additions & 1 deletion pages/facilities/add.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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')
}
Expand Down
Loading

0 comments on commit c80ea16

Please sign in to comment.