问题描述
我目前正在创建auth中间件,以确保请求标头中存在有效的firebase令牌。代码如下:
身份验证
import * as firebase from 'firebase-admin';
import { NextFunction,Request,Response } from 'express';
const getAuthToken = (req: Request,res: Response,next: NextFunction) => {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
req.authToken = req.headers.authorization.split(' ')[1];
} else {
req.authToken = null;
}
next();
};
export const checkIfAuthenticated = (req: Request,next: NextFunction) => {
getAuthToken(req,res,async () => {
try {
const { authToken } = req;
const userInfo = await firebase.auth().verifyIdToken(authToken);
req.authId = userInfo.uid;
return next();
} catch (e) {
return res.status(401).send({ error: 'You are not authorized to make this request' });
}
});
};
export const checkIfAdmin = (req: Request,async () => {
try {
const authToken = req;
const userInfo = await firebase.auth().verifyIdToken(authToken);
if (userInfo.admin === true) {
req.authId = userInfo.uid;
return next();
}
} catch (e) {
return res.status(401).send({ error: 'You are not authorized to make this request' });
}
});
};
app.ts
app.get('/api/users',checkIfAuthenticated,(req,res) => {
executeQuery('SELECT * from user')
.then(function (results: unkNown) {
res.send(results);
})
.catch(function (err: unkNown) {
res.status(400).send(err);
});
});
但是,在auth.ts中,我不断遇到以下错误,该如何解决它们:
1。在getAuthToken
中2。在checkIfAuthenticated
3。在checkIfAdmin
错误:(30,60)TS2345:无法将类型'Request
'的参数分配给类型'string'的参数。
解决方法
修复如下:
import * as firebase from 'firebase-admin';
import { NextFunction,Request,Response } from 'express';
export interface IGetAuthTokenRequest extends Request {
authToken: string;
authId: string;
}
const getAuthToken = (req: IGetAuthTokenRequest,res: Response,next: NextFunction) => {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
req.authToken = req.headers.authorization.split(' ')[1];
} else {
req.authToken = null;
}
next();
};
export const checkIfAuthenticated = (
req: IGetAuthTokenRequest,next: NextFunction
) => {
getAuthToken(req,res,async () => {
try {
const { authToken } = req;
const userInfo = await firebase.auth().verifyIdToken(authToken);
req.authId = userInfo.uid;
return next();
} catch (e) {
return res.status(401).send({ error: 'You are not authorized to make this request' });
}
});
};
export const checkIfAdmin = (req: IGetAuthTokenRequest,next: NextFunction) => {
getAuthToken(req,async () => {
try {
const userInfo = await firebase.auth().verifyIdToken(req.authToken);
if (userInfo.admin === true) {
req.authId = userInfo.uid;
return next();
}
} catch (e) {
return res.status(401).send({ error: 'You are not authorized to make this request' });
}
});