{"size": 1192, "ext": "js", "max_stars_repo_path": "utils/jwt.js", "max_stars_repo_name": "DeleMike/Tasks-Manager", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/jwt.js", "max_issues_repo_name": "DeleMike/Tasks-Manager", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/jwt.js", "max_forks_repo_name": "DeleMike/Tasks-Manager", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.2258064516, "max_line_length": 76, "alphanum_fraction": 0.625}
const jwt = require('jsonwebtoken');

/**
 * creates a jwt 
 */
const createJWT = ({
  payload
}) => {
  const token = jwt.sign(payload, process.env.TOKEN_SECRET, {
    expiresIn: process.env.TOKEN_LIFETIME,
  });
  return token;
};

/**
 * checks if the token gotten is valid
 */
const isTokenValid = (token) => jwt.verify(token, process.env.TOKEN_SECRET);

/**
 * Attach cookies to a logged in user
 */
const attachCookiesToResponse = ({
  res,
  user,
  refreshToken
}) => {
  const accessTokenJWT = createJWT({
    payload: {
      user
    }
  });
  const refreshTokenJWT = createJWT({
    payload: {
      user,
      refreshToken
    }
  });

  const oneDay = 1000 * 60 * 60 * 24;
  const longerExp = 1000 * 60 * 60 * 24 * 30;

  res.cookie('accessToken', accessTokenJWT, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    signed: true,
    expires: new Date(Date.now() + oneDay),
  });

  res.cookie('refreshToken', refreshTokenJWT, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    signed: true,
    expires: new Date(Date.now() + longerExp),
  });
};

module.exports = {
  createJWT,
  isTokenValid,
  attachCookiesToResponse,
};