{"size": 1426, "ext": "js", "max_stars_repo_path": "services/security.js", "max_stars_repo_name": "nbunney/TDVCoreAPI", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "services/security.js", "max_issues_repo_name": "nbunney/TDVCoreAPI", "max_issues_repo_issues_event_min_datetime": "2020-07-23T17:44:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T23:26:52.000Z", "max_forks_repo_path": "services/security.js", "max_forks_repo_name": "nbunney/TDVCoreAPI", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 13, "max_forks_count": null, "avg_line_length": 28.52, "max_line_length": 87, "alphanum_fraction": 0.6115007013}
const jwt = require('jsonwebtoken'); // JSON Web Token implementation

class Security {

  static async validUser(ctx, next) {
    console.log('testing user');
    ctx.state.user = await Security.valdateJWT(ctx);
    if (ctx.state.user.id > 0) {
      return next();
    }
    return false;
  }

  static async validAdmin(ctx, next) {
    ctx.state.user = await Security.valdateJWT(ctx);
    if (ctx.state.user.id > 0 && ctx.state.user.userRoleId >= 1) {
      return next();
    }
    return false;
  }

  static async valdateJWT(ctx) {
    let payload = {};
    if (!ctx.header.authorization) ctx.throw(401, 'Authorisation required');
    const [scheme, token] = ctx.header.authorization.split(' ');
    if (scheme !== 'Bearer') ctx.throw(401, 'Invalid authorisation');

    try {
      payload = jwt.verify(token, process.env.JWT_KEY); // throws on invalid token
      // valid token: accept it...

      let sqla = `select status from user where id = ${payload.id}`;
      const [[res]] = await global.db.query(sqla);

      if (res.status === 0) {
        ctx.body = "Account Disabled";
        const error = {status: 401, message: 'Account Disabled'};
        throw (error);
      }

    } catch (e) {
      if (e.message === 'invalid token') ctx.throw(401, 'Invalid JWT'); // Unauthorized
      ctx.throw(e.status || 401, e.message); // Internal Server Error
    }
    return payload;
  }
}

module.exports = Security;
