'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;
    return ctx.app.jwt.decode(token, ctx.app.config.jwt.secret);
  }

  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;
