Skip to content

Commit

Permalink
chore: add lint rule and format
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe committed Jan 29, 2024
1 parent fce4d55 commit 3e3c831
Show file tree
Hide file tree
Showing 32 changed files with 5,124 additions and 186 deletions.
12 changes: 6 additions & 6 deletions packages/auth-js/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class ClientSessionError extends AuthError {}
export interface AuthClientConfig {
baseUrl: string
basePath: string
credentials?: RequestCredentials,
credentials?: RequestCredentials
/** Stores last session response */
_session?: Session | null | undefined
/** Used for timestamp since last sycned (in seconds) */
Expand All @@ -33,9 +33,7 @@ export interface UseSessionOptions<R extends boolean> {

// Util type that matches some strings literally, but allows any other string as well.
// @source https://github.com/microsoft/TypeScript/issues/29729#issuecomment-832522611
export type LiteralUnion<T extends U, U = string> =
| T
| (U & Record<never, never>)
export type LiteralUnion<T extends U, U = string> = T | (U & Record<never, never>)

export interface ClientSafeProvider {
id: LiteralUnion<BuiltInProviderType>
Expand Down Expand Up @@ -137,7 +135,9 @@ export async function fetchData<T = any>(

const res = await fetch(url, options)
const data = await res.json()
if (!res.ok) throw data
if (!res.ok) {
throw data
}
return data as T
} catch (error) {
logger.error(new ClientFetchError((error as Error).message, error as any))
Expand Down Expand Up @@ -211,4 +211,4 @@ export function parseUrl(url?: string): {
base,
toString: () => base,
}
}
}
7 changes: 4 additions & 3 deletions packages/auth-js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ export async function getAuthUser(c: Context): Promise<AuthUser | null> {
...config.callbacks,
async session(...args) {
authUser = args[0]
const session =
(await config.callbacks?.session?.(...args)) ?? args[0].session
const session = (await config.callbacks?.session?.(...args)) ?? args[0].session
const user = args[0].user ?? args[0].token
return { user, ...session } satisfies Session
},
Expand All @@ -90,7 +89,9 @@ export function verifyAuth(): MiddlewareHandler {
status: 401,
})
throw new HTTPException(401, { res })
} else c.set('authUser', authUser)
} else {
c.set('authUser', authUser)
}

await next()
}
Expand Down
39 changes: 27 additions & 12 deletions packages/auth-js/src/react.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class AuthConfigManager {
_config: AuthClientConfig = {
baseUrl: parseUrl(window.location.origin).origin,
basePath: parseUrl(window.location.origin).path,
credentials:'same-origin',
credentials: 'same-origin',
_lastSync: 0,
_session: undefined,
_getSession: () => {},
Expand Down Expand Up @@ -112,8 +112,11 @@ export function useSession<R extends boolean>(
error: 'SessionRequired',
callbackUrl: window.location.href,
})}`
if (onUnauthenticated) onUnauthenticated()
else window.location.href = url
if (onUnauthenticated) {
onUnauthenticated()
} else {
window.location.href = url
}
}
}, [requiredAndNotLoading, onUnauthenticated])

Expand Down Expand Up @@ -153,7 +156,11 @@ export async function getSession(params?: GetSessionParams) {
* @internal
*/
export async function getCsrfToken() {
const response = await fetchData<{ csrfToken: string }>('csrf', authConfigManager.getConfig(), logger)
const response = await fetchData<{ csrfToken: string }>(
'csrf',
authConfigManager.getConfig(),
logger
)
return response?.csrfToken ?? ''
}

Expand Down Expand Up @@ -215,7 +222,9 @@ export async function signIn<P extends RedirectableProviderType | undefined = un
const url = (data as any).url ?? callbackUrl
window.location.href = url
// If url contains a hash, the browser does not reload the page. We reload manually
if (url.includes('#')) window.location.reload()
if (url.includes('#')) {
window.location.reload()
}
return
}

Expand Down Expand Up @@ -261,7 +270,9 @@ export async function signOut<R extends boolean = true>(
const url = (data as any).url ?? callbackUrl
window.location.href = url
// If url contains a hash, the browser does not reload the page. We reload manually
if (url.includes('#')) window.location.reload()
if (url.includes('#')) {
window.location.reload()
}
// @ts-expect-error TODO: Fix this
return
}
Expand All @@ -285,18 +296,19 @@ export function SessionProvider(props: SessionProviderProps) {
__AUTHJS._lastSync = hasInitialSession ? now() : 0

const [session, setSession] = React.useState(() => {
if (hasInitialSession) __AUTHJS._session = props.session
if (hasInitialSession) {
__AUTHJS._session = props.session
}
return props.session
})


const [loading, setLoading] = React.useState(!hasInitialSession)

React.useEffect(() => {
__AUTHJS._getSession = async ({ event } = {}) => {
try {
const storageEvent = event === 'storage'

if (storageEvent || __AUTHJS._session === undefined) {
__AUTHJS._lastSync = now()
__AUTHJS._session = await getSession({
Expand Down Expand Up @@ -363,8 +375,9 @@ export function SessionProvider(props: SessionProviderProps) {
// and makes our tab visible again, re-fetch the session, but only if
// this feature is not disabled.
const visibilityHandler = () => {
if (refetchOnWindowFocus && document.visibilityState === 'visible')
if (refetchOnWindowFocus && document.visibilityState === 'visible') {
__AUTHJS._getSession({ event: 'visibilitychange' })
}
}
document.addEventListener('visibilitychange', visibilityHandler, false)
return () => document.removeEventListener('visibilitychange', visibilityHandler, false)
Expand All @@ -390,7 +403,9 @@ export function SessionProvider(props: SessionProviderProps) {
data: session,
status: loading ? 'loading' : session ? 'authenticated' : 'unauthenticated',
async update(data: any) {
if (loading || !session) return
if (loading || !session) {
return
}
setLoading(true)
const newSession = await fetchData<Session>(
'session',
Expand All @@ -415,4 +430,4 @@ export function SessionProvider(props: SessionProviderProps) {
)

return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>
}
}
13 changes: 6 additions & 7 deletions packages/auth-js/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import {webcrypto} from 'node:crypto'
import { webcrypto } from 'node:crypto'
import { Hono } from 'hono'
import { describe, expect, it } from 'vitest'
import { authHandler, verifyAuth,initAuthConfig} from '../src'

import { authHandler, verifyAuth, initAuthConfig } from '../src'

// @ts-expect-error - global crypto
//needed for node 18 and below but should work in node 20 and above
global.crypto = webcrypto
global.crypto = webcrypto

describe('Auth.js Adapter Middleware', () => {
it('Should return 500 if AUTH_SECRET is missing', async () => {
Expand Down Expand Up @@ -37,7 +36,7 @@ describe('Auth.js Adapter Middleware', () => {
const app = new Hono()

app.use('/*', (c, next) => {
c.env = {'AUTH_SECRET':'secret'}
c.env = { AUTH_SECRET: 'secret' }
return next()
})

Expand All @@ -60,7 +59,7 @@ describe('Auth.js Adapter Middleware', () => {
const app = new Hono()

app.use('/*', (c, next) => {
c.env = {'AUTH_SECRET':'secret'}
c.env = { AUTH_SECRET: 'secret' }
return next()
})

Expand All @@ -77,7 +76,7 @@ describe('Auth.js Adapter Middleware', () => {

app.use('/api/auth/*', authHandler())

app.get('/api/protected', (c)=> c.text('protected'))
app.get('/api/protected', (c) => c.text('protected'))
const req = new Request('http://localhost/api/protected')
const res = await app.request(req)
expect(res.status).toBe(401)
Expand Down
3 changes: 3 additions & 0 deletions packages/bun-transpiler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,8 @@
"hono": "^3.11.7",
"tsup": "^8.0.1",
"vitest": "^1.0.4"
},
"engines": {
"node": ">=18.14.1"
}
}
4 changes: 3 additions & 1 deletion packages/bun-transpiler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ export const bunTranspiler = (options?: BunTranspilerOptions) => {
const extensions = options?.extensions ?? defaultOptions.extensions
const headers = options?.headers ?? defaultOptions.headers

if (extensions?.every((ext) => !url.pathname.endsWith(ext))) return
if (extensions?.every((ext) => !url.pathname.endsWith(ext))) {
return
}

try {
const loader = url.pathname.split('.').pop() as Bun.TranspilerOptions['loader']
Expand Down
4 changes: 3 additions & 1 deletion packages/esbuild-transpiler/src/transpiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ export const esbuildTranspiler = (options?: EsbuildTranspilerOptions) => {
const url = new URL(c.req.url)
const extensions = options?.extensions ?? ['.ts', '.tsx']

if (extensions.every((ext) => !url.pathname.endsWith(ext))) return
if (extensions.every((ext) => !url.pathname.endsWith(ext))) {
return
}

const headers = { 'content-type': options?.contentType ?? 'text/javascript' }
const script = await c.res.text()
Expand Down
4 changes: 3 additions & 1 deletion packages/firebase-auth/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ const setFirebaseToken = (c: Context, idToken: FirebaseIdToken) => c.set(idToken

export const getFirebaseToken = (c: Context): FirebaseIdToken | null => {
const idToken = c.get(idTokenContextKey)
if (!idToken) return null
if (!idToken) {
return null
}
return idToken
}
4 changes: 3 additions & 1 deletion packages/graphql-server/bun_test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ const TestSchema = new GraphQLSchema({

const urlString = (query?: Record<string, string>): string => {
const base = 'http://localhost/graphql'
if (!query) return base
if (!query) {
return base
}
const queryString = new URLSearchParams(query).toString()
return `${base}?${queryString}`
}
Expand Down
4 changes: 3 additions & 1 deletion packages/graphql-server/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ const TestSchema = new GraphQLSchema({

const urlString = (query?: Record<string, string>): string => {
const base = 'http://localhost/graphql'
if (!query) return base
if (!query) {
return base
}
const queryString = new URLSearchParams(query).toString()
return `${base}?${queryString}`
}
Expand Down
30 changes: 22 additions & 8 deletions packages/oauth-providers/src/providers/discord/authFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,15 @@ export class AuthFlow {
body: parsedOptions,
}).then((res) => res.json())) as DiscordTokenResponse | DiscordErrorResponse

if ('error_description' in response)
if ('error_description' in response) {
throw new HTTPException(400, { message: response.error_description })
if ('error' in response) throw new HTTPException(400, { message: response.error })
if ('message' in response) throw new HTTPException(400, { message: response.message })
}
if ('error' in response) {
throw new HTTPException(400, { message: response.error })
}
if ('message' in response) {
throw new HTTPException(400, { message: response.message })
}

if ('access_token' in response) {
this.token = {
Expand All @@ -103,7 +108,9 @@ export class AuthFlow {
}
}

if ('scope' in response) this.granted_scopes = response.scope.split(' ')
if ('scope' in response) {
this.granted_scopes = response.scope.split(' ')
}
}

async getUserData() {
Expand All @@ -114,11 +121,18 @@ export class AuthFlow {
},
}).then((res) => res.json())) as DiscordMeResponse | DiscordErrorResponse

if ('error_description' in response)
if ('error_description' in response) {
throw new HTTPException(400, { message: response.error_description })
if ('error' in response) throw new HTTPException(400, { message: response.error })
if ('message' in response) throw new HTTPException(400, { message: response.message })
}
if ('error' in response) {
throw new HTTPException(400, { message: response.error })
}
if ('message' in response) {
throw new HTTPException(400, { message: response.message })
}

if ('user' in response) this.user = response.user
if ('user' in response) {
this.user = response.user
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ export async function refreshToken(
body: params,
}).then((res) => res.json())) as DiscordTokenResponse | { error: string }

if ('error' in response) throw new HTTPException(400, { message: response.error })
if ('error' in response) {
throw new HTTPException(400, { message: response.error })
}

return response
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ export async function revokeToken(
body: params,
})

if (response.status !== 200) throw new HTTPException(400, { message: 'Something went wrong' })
if (response.status !== 200) {
throw new HTTPException(400, { message: 'Something went wrong' })
}

return true
}
20 changes: 15 additions & 5 deletions packages/oauth-providers/src/providers/facebook/authFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,9 @@ export class AuthFlow {
| FacebookTokenResponse
| FacebookErrorResponse

if ('error' in response) throw new HTTPException(400, { message: response.error?.message })
if ('error' in response) {
throw new HTTPException(400, { message: response.error?.message })
}

if ('access_token' in response) {
this.token = {
Expand All @@ -93,9 +95,13 @@ export class AuthFlow {
`https://graph.facebook.com/v18.0/me?access_token=${this.token?.token}`
).then((res) => res.json())) as FacebookMeResponse | FacebookErrorResponse

if ('error' in response) throw new HTTPException(400, { message: response.error?.message })
if ('error' in response) {
throw new HTTPException(400, { message: response.error?.message })
}

if ('id' in response) this.user = response
if ('id' in response) {
this.user = response
}
}

async getUserData() {
Expand All @@ -107,8 +113,12 @@ export class AuthFlow {
`https://graph.facebook.com/${this.user?.id}?fields=${parsedFields}&access_token=${this.token?.token}`
).then((res) => res.json())) as FacebookUser | FacebookErrorResponse

if ('error' in response) throw new HTTPException(400, { message: response.error?.message })
if ('error' in response) {
throw new HTTPException(400, { message: response.error?.message })
}

if ('id' in response) this.user = response
if ('id' in response) {
this.user = response
}
}
}
Loading

0 comments on commit 3e3c831

Please sign in to comment.