FirebaseはいくつかのサンプルをJavaScriptで公開してくれています🙏
そのサンプルの中のAuthorized HTTPS EndpointをTypeScriptで使いたかったので書き直してみました。
参考URL:
https://github.com/firebase/functions-samples/tree/master/authorized-https-endpoint
https://stackoverflow.com/questions/44383387/typescript-error-property-user-does-not-exist-on-type-request
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as admin from 'firebase-admin'
import * as express from 'express'
import * as cookieParser from 'cookie-parser'
import * as cors from 'cors'
const app = express()
admin.initializeApp()
export interface AuthRequest extends express.Request {
user?: admin.auth.DecodedIdToken
}
const validateFirebaseIdToken = async (req: AuthRequest, res: express.Response, next: express.NextFunction) => {
console.log('Check if request is authorized with Firebase ID token')
if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
!(req.cookies && req.cookies.__session)) {
console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.',
'Make sure you authorize your request by providing the following HTTP header:',
'Authorization: Bearer <Firebase ID Token>',
'or by passing a "__session" cookie.')
res.status(403).send('Unauthorized')
return
}
let idToken
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
console.log('Found "Authorization" header')
idToken = req.headers.authorization.split('Bearer ')[1]
} else if(req.cookies) {
console.log('Found "__session" cookie')
idToken = req.cookies.__session
} else {
res.status(403).send('Unauthorized')
return
}
try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken)
console.log('ID Token correctly decoded', decodedIdToken)
req.user = decodedIdToken
next()
return
} catch (error) {
console.error('Error while verifying Firebase ID token:', error)
res.status(403).send('Unauthorized')
return
}
}
app.use(cors({origin: true}))
app.use(cookieParser())
app.use(validateFirebaseIdToken)
app.get('/hello', (req: AuthRequest, res: express.Response) => {
res.send(`Hello ${req.user?.name}`)
})
// This HTTPS endpoint can only be accessed by your Firebase Users.
// Requests need to be authorized by providing an `Authorization` HTTP header
// with value `Bearer <Firebase ID Token>`.
exports.app = functions.https.onRequest(app)