'use strict';

const Service = require('egg').Service;

class JWTService extends Service {
  async apply(data) {
    const { ctx } = this;
    const exp = ctx.app.config.jwt.exp;
    const secret = ctx.app.config.jwt.secret;
    const auth_token = ctx.app.jwt.sign(
      {
        data,
        exp,
      },
      secret
    );
    return auth_token;
  }

  async decode_token(token) {
    const { ctx } = this;
    let ret = {};
    try {
      ret = await ctx.app.jwt.decode(token, ctx.app.config.jwt.secret);
    } catch (err) {
      ctx.throw(401, 'jwt解密失败');
    }
    if (ctx.isEmpty(ret)) {
      ctx.throw(401, 'jwt解密失败');
    }
    return ret;
  }

  async del_token(token) {
    const user_id = this.decode_token(token).data.user_id;
    await this.app.memcache.set('auth_token_' + user_id, token, this.ctx.app.config.jwt.exp);
    return true;
  }
}

module.exports = JWTService;
