login_logging.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. 'use strict';
  2. /**
  3. * 登录日志-数据模型
  4. *
  5. * @author lanjianrong
  6. * @date 2020/8/31
  7. * @version
  8. */
  9. const UAParser = require('ua-parser-js');
  10. module.exports = app => {
  11. class LoginLogging extends app.BaseService {
  12. constructor(ctx) {
  13. super(ctx);
  14. this.tableName = 'login_logging';
  15. }
  16. /**
  17. * 创建记录
  18. * @param {Object} payload - 载荷
  19. */
  20. async createLog(payload) {
  21. const transaction = await this.db.beginTransaction();
  22. try {
  23. transaction.insert(this.tableName, payload);
  24. await transaction.commit();
  25. } catch (error) {
  26. await transaction.rollback();
  27. throw error;
  28. }
  29. }
  30. /**
  31. * 创建登录日志
  32. * @return {Boolean} 日志是否创建成功
  33. */
  34. async addLoginLog() {
  35. const { ctx } = this;
  36. const ip = ctx.header['x-real-ip'] ? ctx.header['x-real-ip'] : '';
  37. const ipInfo = await this.getIpInfoFromApi(ip);
  38. const parser = new UAParser(ctx.header['user-agent']);
  39. const osInfo = parser.getOS();
  40. const cpuInfo = parser.getCPU();
  41. const browserInfo = parser.getBrowser();
  42. const payload = {
  43. os: `${osInfo.name} ${osInfo.version} ${cpuInfo.architecture}`,
  44. browser: `${browserInfo.name} ${browserInfo.version}`,
  45. ip,
  46. address: ipInfo,
  47. uid: ctx.session.sessionUser.accountId,
  48. pid: ctx.session.sessionProject.id,
  49. };
  50. return await this.createLog(payload);
  51. }
  52. /**
  53. * 根据ip请求获取详细地址
  54. * @param {String} a_ip - ip地址
  55. * @return {String} 详细地址
  56. */
  57. async getIpInfoFromApi(a_ip = '') {
  58. if (!a_ip) return '';
  59. if (a_ip === '127.0.0.1') return '服务器本机访问';
  60. const { ip = '', region = '', city = '', isp = '' } = await this.sendRequest(a_ip);
  61. let address = '';
  62. region && (address += region + '省');
  63. city && (address += city + '市 ');
  64. isp && (address += isp + ' ');
  65. ip && (address += `(${ip})`);
  66. return address;
  67. }
  68. /**
  69. * 发送请求获取详细地址
  70. * @param {String} ip - ip地址
  71. * @param {Number} max - 最大重试次数
  72. * @return {Object} the result of request
  73. * @private
  74. */
  75. async sendRequest(ip, max = 3) {
  76. return new Promise(resolve => {
  77. const start = () => {
  78. if (max <= 0) {
  79. resolve(); // 已达到最大重试次数,返回空的执行承若
  80. }
  81. max--;
  82. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  83. dateType: 'json',
  84. encoding: 'utf8',
  85. timeout: 2000,
  86. headers: {
  87. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  88. },
  89. }).then(({ status, data }) => {
  90. if (status === 200) {
  91. const result = JSON.parse(data.toString()).data;
  92. if (!result.ip) {
  93. start();
  94. } else {
  95. max++;
  96. resolve(result);
  97. }
  98. } else {
  99. max--;
  100. start();
  101. }
  102. }).catch(() => {
  103. start();
  104. });
  105. };
  106. start();
  107. });
  108. }
  109. /**
  110. * 获取登录日志
  111. * @param {Number} pid - 项目id
  112. * @param {Number} uid - 用户id
  113. * @return {Promise<Array>} 日志数组
  114. */
  115. async getLoginLogs(pid, uid) {
  116. return this.db.select(this.tableName, {
  117. where: { pid, uid },
  118. orders: [['create_time', 'desc']],
  119. columns: ['browser', 'create_time', 'ip', 'os', 'address'],
  120. limit: 10, offset: 0,
  121. });
  122. }
  123. }
  124. return LoginLogging;
  125. };