1- import { randomUUID } from 'node:crypto'
21import type { H3Event } from 'h3'
3- import { eventHandler , createError , getQuery , getRequestURL , sendRedirect } from 'h3'
4- import { withQuery , parsePath } from 'ufo'
2+ import { eventHandler , getQuery , sendRedirect } from 'h3'
3+ import { withQuery } from 'ufo'
54import { defu } from 'defu'
6- import { handleAccessTokenErrorResponse , handleMissingConfiguration } from '../utils'
7- import { useRuntimeConfig } from '#imports'
5+ import { randomUUID } from 'uncrypto'
6+ import { handleMissingConfiguration , handleAccessTokenErrorResponse , getOAuthRedirectURL , requestAccessToken } from '../utils'
7+ import { useRuntimeConfig , createError } from '#imports'
88import type { OAuthConfig } from '#auth-utils'
99
1010export interface OAuthBattledotnetConfig {
@@ -62,8 +62,7 @@ export function oauthBattledotnetEventHandler({ config, onSuccess, onError }: OA
6262 authorizationParams : { } ,
6363 } ) as OAuthBattledotnetConfig
6464
65- const query = getQuery ( event )
66- const { code } = query
65+ const query = getQuery < { code ?: string , error ?: string } > ( event )
6766
6867 if ( query . error ) {
6968 const error = createError ( {
@@ -80,8 +79,9 @@ export function oauthBattledotnetEventHandler({ config, onSuccess, onError }: OA
8079 )
8180 }
8281
83- const redirectURL = config . redirectURL || getRequestURL ( event ) . href
84- if ( ! code ) {
82+ const redirectURL = config . redirectURL || getOAuthRedirectURL ( event )
83+
84+ if ( ! query . code ) {
8585 config . scope = config . scope || [ 'openid' ]
8686 config . region = config . region || 'EU'
8787
@@ -109,27 +109,16 @@ export function oauthBattledotnetEventHandler({ config, onSuccess, onError }: OA
109109 config . scope . push ( 'openid' )
110110 }
111111
112- const authCode = Buffer . from ( `${ config . clientId } :${ config . clientSecret } ` ) . toString ( 'base64' )
113-
114- // TODO: improve typing
115- // eslint-disable-next-line @typescript-eslint/no-explicit-any
116- const tokens : any = await $fetch (
117- config . tokenURL as string ,
118- {
119- method : 'POST' ,
120- headers : {
121- 'Content-Type' : 'application/x-www-form-urlencoded' ,
122- 'Authorization' : `Basic ${ authCode } ` ,
123- } ,
124- params : {
125- code,
126- grant_type : 'authorization_code' ,
127- scope : config . scope . join ( ' ' ) ,
128- redirect_uri : parsePath ( redirectURL ) . pathname ,
129- } ,
112+ const tokens = await requestAccessToken ( config . tokenURL as string , {
113+ headers : {
114+ Authorization : `Basic ${ Buffer . from ( `${ config . clientId } :${ config . clientSecret } ` ) . toString ( 'base64' ) } ` ,
115+ } ,
116+ params : {
117+ grant_type : 'authorization_code' ,
118+ scope : config . scope . join ( ' ' ) ,
119+ redirect_uri : redirectURL ,
120+ code : query . code ,
130121 } ,
131- ) . catch ( ( error ) => {
132- return { error }
133122 } )
134123
135124 if ( tokens . error ) {
0 commit comments