import { firebaseAdmin } from '@src/utils/auth/firebaseAdmin' ; import { getOrRegisterUser } from '@controllers/userController' ; import { refreshExpiredIdToken } from '@src/utils/auth/refreshExpiredToken' ; import { NextFunction , Request , Response } from 'express' ; const verifyOrRefreshIdToken = async ( idToken , refreshToken ) : Promise < any > => { try { return { ... ( await firebaseAdmin . auth ( ) . verifyIdToken ( idToken , true ) ) , } ; } catch { const token = await refreshExpiredIdToken ( refreshToken ) ; return { ... ( await firebaseAdmin . auth ( ) . verifyIdToken ( token , true ) ) , } ; } } ; const requireLogin = async ( req , res , next ) => { const headerToken = req . headers . authorization ; if ( ! headerToken ) { res . status ( 401 ) . send ( { error : 'No token provided' } ) ; return ; } if ( headerToken && headerToken . split ( ' ' ) [ 0 ] !== 'Bearer' ) { res . status ( 401 ) . send ( { error : 'Invalid token' } ) ; return ; } const idToken = headerToken ?. split ( ' ' ) [ 1 ] || '' ; const refreshToken = ( req . headers . refreshtoken as string ) || '' ; try { const userFromToken = await verifyOrRefreshIdToken ( idToken , refreshToken ) ; const user = await getOrRegisterUser ( userFromToken ) ; if ( user ) req . user = user ; next ( ) ; } catch ( error ) { res . status ( 403 ) . send ( { error : error . message } ) ; return ; } } ; export default requireLogin ;