@@ -35,24 +35,34 @@ function createFetchClient(
3535 retry : false ,
3636
3737 async onRequest ( context ) {
38- let csrfToken = readCsrfCookie ( authentication . csrfCookie )
39-
40- if ( ! csrfToken . value ) {
41- await $fetch ( authentication . csrfEndpoint , {
42- baseURL : authentication . baseUrl ,
43- credentials : 'include' ,
44- retry : false ,
45- } )
46-
47- csrfToken = readCsrfCookie ( authentication . csrfCookie )
38+ // todo: move this to interceptors
39+ if ( authentication . mode === 'token' ) {
40+ let csrfToken = readCsrfCookie ( authentication . csrfCookie )
41+
42+ if ( ! csrfToken . value ) {
43+ await $fetch ( authentication . csrfEndpoint , {
44+ baseURL : authentication . baseUrl ,
45+ credentials : 'include' ,
46+ retry : false ,
47+ } )
48+
49+ csrfToken = readCsrfCookie ( authentication . csrfCookie )
50+ }
51+
52+ if ( ! csrfToken . value ) {
53+ logger . warn ( `${ authentication . csrfCookie } cookie is missing, unable to set ${ authentication . csrfHeader } header` )
54+ return
55+ }
56+
57+ context . options . headers . set ( authentication . csrfHeader , csrfToken . value )
4858 }
4959
50- if ( ! csrfToken . value ) {
51- logger . warn ( `${ authentication . csrfCookie } cookie is missing, unable to set ${ authentication . csrfHeader } header` )
52- return
60+ // todo: move this to interceptors
61+ if ( authentication . mode === 'token' ) {
62+ const { tokenStorage } = useAppConfig ( ) . echo . authentication
63+ const token = await tokenStorage . get ( )
64+ context . options . headers . set ( 'Authorization' , 'Bearer ' + token )
5365 }
54-
55- context . options . headers . set ( authentication . csrfHeader , csrfToken . value )
5666 } ,
5767 }
5868
@@ -127,10 +137,33 @@ function prepareEchoOptions(config: ModuleOptions, logger: ConsolaInstance) {
127137 }
128138}
129139
130- export default defineNuxtPlugin ( ( _nuxtApp ) => {
140+ async function setupDefaultTokenStorage ( nuxtApp : NuxtApp , logger : ConsolaInstance ) {
141+ logger . debug (
142+ 'Token storage is not defined, switch to default cookie storage' ,
143+ )
144+
145+ const defaultStorage = await import ( './storages/cookieTokenStorage' )
146+
147+ nuxtApp . runWithContext ( ( ) => {
148+ updateAppConfig ( {
149+ echo : {
150+ authentication : {
151+ tokenStorage : defaultStorage . cookieTokenStorage ,
152+ }
153+ } ,
154+ } )
155+ } )
156+ }
157+
158+ export default defineNuxtPlugin ( async ( _nuxtApp ) => {
131159 const config = useEchoConfig ( )
160+ const appConfig = useAppConfig ( )
132161 const logger = createEchoLogger ( config . logLevel )
133162
163+ if ( config . authentication ?. mode === 'token' && ! appConfig . echo ?. authentication ?. tokenStorage ) {
164+ await setupDefaultTokenStorage ( _nuxtApp , logger )
165+ }
166+
134167 window . Pusher = Pusher
135168 window . Echo = new Echo ( prepareEchoOptions ( config , logger ) )
136169
0 commit comments