Skip to content

Commit

Permalink
Merge branch 'OAuth'
Browse files Browse the repository at this point in the history
  • Loading branch information
dragoni7 committed Jun 24, 2024
2 parents b6a2865 + 4742ca3 commit a04f9f3
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 13 deletions.
4 changes: 3 additions & 1 deletion src/app/routes/Landing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useNavigate } from 'react-router'

import { useEffect} from "react"
import BungieLogin from '../../features/auth/BungieLogin'
import { generateToken, regenerateTokens } from '../../lib/bungie_api/TokenService'
import { regenerateTokens } from '../../lib/bungie_api/TokenService'
import { isAuthenticated } from '../../lib/bungie_api/AuthService'


Expand All @@ -20,6 +20,8 @@ export const LandingRoute = () => {
navigate('/app')
}

console.log("Not authenticated")

}, [])

return (
Expand Down
4 changes: 4 additions & 0 deletions src/app/routes/Return.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ import { useEffect } from "react"
import { useNavigate } from "react-router-dom"
import { handleAuthReturn } from "../../features/auth/AuthReturn"

/**
* Bungie OAuth redirects here
*/
export const ReturnRoute = () => {

const navigate = useNavigate()

useEffect( () => {

if (handleAuthReturn()) {
// exit component if successful
navigate('/')
}

Expand Down
4 changes: 4 additions & 0 deletions src/features/auth/AuthReturn.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ function getAuthCodeFromURL(): string | null {
return window.location.href.includes("code=") ? window.location.href.split('code=')[1] : null
}

/**
* Get auth tokens from auth code
* @returns whether or not tokens were successfully generated
*/
export function handleAuthReturn(): boolean {

const code = getAuthCodeFromURL()
Expand Down
11 changes: 11 additions & 0 deletions src/lib/bungie_api/AuthService.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,28 @@ import { Navigate } from "react-router-dom"
import { isTokenExpired } from "./TokenService"
import { getTokens } from "./TokensStore"

/**
* Navigates to the Bungie OAuth url
*/
export function authenticate(): void {
window.location.replace(`https://www.bungie.net/en/OAuth/Authorize?client_id=${import.meta.env.VITE_CLIENT_ID}&response_type=code`)
}

/**
* Whether or not the user is authenticated.
*
* @returns if auth tokens are present in local store
*/
export function isAuthenticated(): boolean {

const tokens = getTokens()

return !tokens ? false : !isTokenExpired(tokens.accessToken)
}

/**
* Restricts rendering of children if not authenticated
*/
export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {

if (!isAuthenticated()) {
Expand Down
13 changes: 13 additions & 0 deletions src/lib/bungie_api/BungieApiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,23 @@ const apiClient = axios.create({
}
})

/**
* Bungie get request
* @param url
* @param config axios config
* @returns
*/
const _get = (url: string, config = {}) => {
return apiClient.get(url, config)
}

/**
* Bungie post request
* @param url
* @param data request body
* @param config axios config
* @returns
*/
const _post = (url: string, data = {}, config = {}) => {
return apiClient.post(url, data, config)
}
Expand Down
24 changes: 12 additions & 12 deletions src/lib/bungie_api/TokenService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,14 @@ export function isTokenExpired(token?: Token) {
return Date.now() > expiration
}

function getTokenExpiration(token?: Token): number {
return (token && 'acquired' in token && 'expires' in token) ? token.acquired + token.expires * 1000 : 0
export function regenerateTokens(): boolean {

if (canTokensRefresh()) {
generateToken(true)
return true
}

return false
}

export function generateToken(refresh: boolean, authCode=""): Tokens | null {
Expand Down Expand Up @@ -68,6 +74,10 @@ export function generateToken(refresh: boolean, authCode=""): Tokens | null {
return returnToken
}

function getTokenExpiration(token?: Token): number {
return (token && 'acquired' in token && 'expires' in token) ? token.acquired + token.expires * 1000 : 0
}

function handleTokenResponse(response: AxiosResponse): Tokens {
if (response.data.access_token) {

Expand Down Expand Up @@ -98,14 +108,4 @@ function handleTokenResponse(response: AxiosResponse): Tokens {
else {
throw new Error(`Invalid response: ${JSON.stringify(response)}`)
}
}

export function regenerateTokens(): boolean {

if (canTokensRefresh()) {
generateToken(true)
return true
}

return false
}
14 changes: 14 additions & 0 deletions src/lib/bungie_api/TokensStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,33 @@ export interface Tokens {

const key = 'authTokens'

/**
* Gets the locally stored auth tokens
* @returns the tokens or null
*/
export function getTokens(): Tokens | null {
const tokenString = localStorage.getItem(key)
return tokenString ? (JSON.parse(tokenString) as Tokens) : null
}

/**
* Stores auth tokens in local storage.
*/
export function setTokens(tokens: Tokens) {
localStorage.setItem(key, JSON.stringify(tokens))
}

/**
* Removes the locally stored auth tokens
*/
export function removeTokens() {
localStorage.removeItem(key)
}

/**
* Gets the membersip id from the locally stored auth tokens
* @returns membershipId
*/
export function getMembershipId(): string | undefined {
const tokens = getTokens()

Expand Down

0 comments on commit a04f9f3

Please sign in to comment.