-
-
Save admench/5ebef44645839c6601b0f02e9e371289 to your computer and use it in GitHub Desktop.
useSessionCheck.ts Vue composable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# .env | |
SESSION_LIFETIME=2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts" setup> | |
const props = defineProps<BasePageProps>() | |
useSessionCheck(props) | |
</script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function share(Request $request): array | |
{ | |
return [ | |
...parent::share($request), | |
'auth' => [ | |
'session' => [ | |
'expires' => now()->addMinutes(config('session.lifetime'))->setTimezone('Europe/London')->toDateTimeString(), | |
], | |
], | |
]; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// useSessionCheck composable: | |
import type { BasePageProps } from '@/types' | |
import { toast } from '@/components/ui/toast' | |
import { router } from '@inertiajs/vue3' | |
import { useDocumentVisibility } from '@vueuse/core' | |
import { watch } from 'vue' | |
/* | |
* If the user returns to the tab after a period of inactivity, | |
* check if the session has expired. If so, reload page | |
* (which will redirect to login page with intended | |
* url stored in session). | |
*/ | |
export function useSessionCheck(props: BasePageProps) { | |
const expires = props.auth.session.expires | |
const expiresDate = new Date(expires) | |
const visibility = useDocumentVisibility() | |
watch(visibility, (visible) => { | |
if (visible === 'visible') { | |
const now = new Date() | |
if (expiresDate < now) { | |
toast({ title: 'Session expired', description: 'Please login again' }) | |
router.reload() | |
} | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment