您如何使用Ramda.js重构此函数?

时间:2018-12-16 01:19:23

标签: functional-programming ramda.js

我正在尝试学习Ramda.js,但是想想Ramda中的简单事物总是充满挑战。如果您是Ramda或函数式编程专家,您将如何重构它?

const validateFirebaseIdToken = async (req, res, next) => {
  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');
    // Read the ID Token from the Authorization header.
    idToken = req.headers.authorization.split("Bearer ")[1];
  } else if (req.cookies) {
    console.log('Found "__session" cookie');
    // Read the ID Token from cookie.
    idToken = req.cookies.__session;
  } else {
    // No cookie
    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;
  }
};

1 个答案:

答案 0 :(得分:1)

由于我无法重现您的环境,因此不能保证这是100%正常工作的代码,但是我已经验证了大多数功能都能按预期工作。

检查请求

可以将两组条件语句压缩在一起。检查请求的有效性并提取令牌的方式可以表示为:(我们将在以后处理未授权的情况)

const token = hasToken(req) ? getToken(req) : false;

hasToken将检查请求req是否具有有效的授权标头或__session Cookie:

const hasBearer = pipe(pathOr('', ['headers', 'authorization']), startsWith('Bearer'));
const hasSession = hasPath(['cookies', '__session']);
const hasToken = either(hasBearer, hasSession);

获取令牌

我们可以从标头或cookie中获取令牌:

const getBearer = pipe(path(['headers', 'authorization']), replace('Bearer ', ''));
const getSession = path(['cookies', '__session']);
const getToken = either(getBearer, getSession);

生成403个“未经授权”的回复

我们也可以为此创建一个函数。它可能很简单:

const unauthorized = res => res.status(403).send('Unauthorized');

但是我们也可以将其分解为较小的可重用块:

const status = invoker(1, 'status');
const send = invoker(1, 'send');
const unauthorized = pipe(status(403), send('Unauthorized'));

因此,如果您想生成其他类型的响应,则可以执行以下操作:

const notFound = pipe(status(404), send('Not Found'));
const serverError = pipe(status(500), send('Server Error'));

验证令牌的有效性

我们可以使用功能性方法进行尝试/捕获:

const verifyToken = async (admin, token) =>
  tryCatch(() => admin.auth().verifyIdToken(token), F)();

收回对admin的控制权

原始validateFirebaseIdToken函数依赖于外部变量admin,这不是理想的恕我直言。最好将它作为参数传递。为此,我们可以使用curry

const validateFirebaseIdTokenFunction = curry(async (admin, req, res, next) => {
  // …
});

将所有内容放在一起

const {
  curry,
  either,
  F,
  hasPath,
  invoker,
  path,
  pathOr,
  pipe,
  replace,
  set,
  startsWith,
  tryCatch } = require('ramda');

const hasBearer = pipe(pathOr('', ['headers', 'authorization']), startsWith('Bearer'));
const getBearer = pipe(path(['headers', 'authorization']), replace('Bearer ', ''));
const hasSession = hasPath(['cookies', '__session']);
const getSession = path(['cookies', '__session']);
const hasToken = either(hasBearer, hasSession);
const getToken = either(getBearer, getSession);
const status = invoker(1, 'status');
const send = invoker(1, 'send');
const unauthorized = pipe(status(403), send('Unauthorized'));

const verifyToken = async (admin, token) =>
  tryCatch(() => admin.auth().verifyIdToken(token), F)();

const validateFirebaseIdTokenFunction = curry(async (admin, req, res, next) => {
  const token = hasToken(req) ? getToken(req) : false;
  const tokenVerified = token ? await verifyToken(admin, token) : false;
  return tokenVerified ? set('user', tokenVerified, req) && next() : unauthorized(res);
});

// This function now “waits” for the remaining arguments: `req`, `res` and `next`
const validateFirebaseIdToken = validateFirebaseIdTokenFunction(admin);

使用的Ramda函数列表