-
Notifications
You must be signed in to change notification settings - Fork 31
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add option to save session data to local storage #900
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
/** | ||
* | ||
* Copyright 2024 Splunk Inc. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
* | ||
*/ | ||
import { isIframe } from './utils' | ||
import { SessionState } from './types' | ||
|
||
export const COOKIE_NAME = '_splunk_rum_sid' | ||
|
||
const CookieSession = 4 * 60 * 60 * 1000 // 4 hours | ||
const InactivityTimeoutSeconds = 15 * 60 | ||
|
||
export const cookieStore = { | ||
set: (value: string): void => { | ||
document.cookie = value | ||
}, | ||
get: (): string => document.cookie, | ||
} | ||
|
||
export function parseCookieToSessionState(): SessionState | undefined { | ||
const rawValue = findCookieValue(COOKIE_NAME) | ||
if (!rawValue) { | ||
return undefined | ||
} | ||
|
||
const decoded = decodeURIComponent(rawValue) | ||
if (!decoded) { | ||
return undefined | ||
} | ||
|
||
let sessionState: unknown = undefined | ||
try { | ||
sessionState = JSON.parse(decoded) | ||
} catch { | ||
return undefined | ||
} | ||
|
||
if (!isSessionState(sessionState)) { | ||
return undefined | ||
} | ||
|
||
// id validity | ||
if ( | ||
!sessionState.id || | ||
typeof sessionState.id !== 'string' || | ||
!sessionState.id.length || | ||
sessionState.id.length !== 32 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. could you please use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sure, it will be improved in upcoming PR. |
||
) { | ||
return undefined | ||
} | ||
|
||
// startTime validity | ||
if (!sessionState.startTime || typeof sessionState.startTime !== 'number' || isPastMaxAge(sessionState.startTime)) { | ||
return undefined | ||
} | ||
|
||
return sessionState | ||
} | ||
|
||
export function renewCookieTimeout(sessionState: SessionState, cookieDomain: string | undefined): void { | ||
if (isPastMaxAge(sessionState.startTime)) { | ||
// safety valve | ||
return | ||
} | ||
|
||
const cookieValue = encodeURIComponent(JSON.stringify(sessionState)) | ||
const domain = cookieDomain ? `domain=${cookieDomain};` : '' | ||
let cookie = COOKIE_NAME + '=' + cookieValue + '; path=/;' + domain + 'max-age=' + InactivityTimeoutSeconds | ||
|
||
if (isIframe()) { | ||
cookie += ';SameSite=None; Secure' | ||
} else { | ||
cookie += ';SameSite=Strict' | ||
} | ||
|
||
cookieStore.set(cookie) | ||
} | ||
|
||
export function clearSessionCookie(cookieDomain?: string): void { | ||
const domain = cookieDomain ? `domain=${cookieDomain};` : '' | ||
const cookie = `${COOKIE_NAME}=;domain=${domain};expires=Thu, 01 Jan 1970 00:00:00 GMT` | ||
cookieStore.set(cookie) | ||
} | ||
|
||
export function findCookieValue(cookieName: string): string | undefined { | ||
const decodedCookie = decodeURIComponent(cookieStore.get()) | ||
const cookies = decodedCookie.split(';') | ||
for (let i = 0; i < cookies.length; i++) { | ||
const c = cookies[i].trim() | ||
if (c.indexOf(cookieName + '=') === 0) { | ||
return c.substring((cookieName + '=').length, c.length) | ||
} | ||
} | ||
return undefined | ||
} | ||
|
||
function isPastMaxAge(startTime: number): boolean { | ||
const now = Date.now() | ||
return startTime > now || now > startTime + CookieSession | ||
} | ||
|
||
function isSessionState(maybeSessionState: unknown): maybeSessionState is SessionState { | ||
return ( | ||
typeof maybeSessionState === 'object' && | ||
maybeSessionState !== null && | ||
'id' in maybeSessionState && | ||
typeof maybeSessionState['id'] === 'string' && | ||
'startTime' in maybeSessionState && | ||
typeof maybeSessionState['startTime'] === 'number' | ||
) | ||
} |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
/** | ||
* | ||
* Copyright 2024 Splunk Inc. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
* | ||
*/ | ||
import { SessionState } from './types' | ||
import { safelyGetLocalStorage, safelySetLocalStorage, safelyRemoveFromLocalStorage } from './utils/storage' | ||
|
||
const SESSION_ID_LENGTH = 32 | ||
const SESSION_DURATION_MS = 4 * 60 * 60 * 1000 // 4 hours | ||
|
||
const SESSION_ID_KEY = '_SPLUNK_SESSION_ID' | ||
const SESSION_LAST_UPDATED_KEY = '_SPLUNK_SESSION_LAST_UPDATED' | ||
|
||
export const getSessionStateFromLocalStorage = (): SessionState | undefined => { | ||
const sessionId = safelyGetLocalStorage(SESSION_ID_KEY) | ||
if (!isSessionIdValid(sessionId)) { | ||
return | ||
} | ||
|
||
const startTimeString = safelyGetLocalStorage(SESSION_LAST_UPDATED_KEY) | ||
const startTime = Number.parseInt(startTimeString, 10) | ||
if (!isSessionStartTimeValid(startTime) || isSessionExpired(startTime)) { | ||
return | ||
} | ||
|
||
return { id: sessionId, startTime } | ||
} | ||
|
||
export const setSessionStateToLocalStorage = (sessionState: SessionState): void => { | ||
if (isSessionExpired(sessionState.startTime)) { | ||
return | ||
} | ||
|
||
safelySetLocalStorage(SESSION_ID_KEY, sessionState.id) | ||
safelySetLocalStorage(SESSION_LAST_UPDATED_KEY, String(sessionState.startTime)) | ||
} | ||
|
||
export const clearSessionStateFromLocalStorage = (): void => { | ||
safelyRemoveFromLocalStorage(SESSION_ID_KEY) | ||
safelyRemoveFromLocalStorage(SESSION_LAST_UPDATED_KEY) | ||
} | ||
|
||
const isSessionIdValid = (sessionId: unknown): boolean => | ||
typeof sessionId === 'string' && sessionId.length === SESSION_ID_LENGTH | ||
|
||
const isSessionStartTimeValid = (startTime: unknown): boolean => | ||
typeof startTime === 'number' && startTime <= Date.now() | ||
|
||
const isSessionExpired = (startTime: number) => Date.now() - startTime > SESSION_DURATION_MS |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you need this here... I guess it is covered with
!== 32
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This was part of the original code, I'm refactoring this in upcoming PR.