login_logging.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. * @param {Number} type - 登录类型
  34. * @param {Number} status - 是否显示记录
  35. */
  36. async addLoginLog(type, status) {
  37. const { ctx } = this;
  38. const ip = ctx.request.ip ? ctx.request.ip : '';
  39. const ipInfo = await this.getIpInfoFromApi(ip);
  40. const parser = new UAParser(ctx.header['user-agent']);
  41. const osInfo = parser.getOS();
  42. const cpuInfo = parser.getCPU();
  43. const browserInfo = parser.getBrowser();
  44. const payload = {
  45. os: `${osInfo.name} ${osInfo.version} ${cpuInfo.architecture}`,
  46. browser: `${browserInfo.name} ${browserInfo.version}`,
  47. ip,
  48. address: ipInfo,
  49. uid: ctx.session.sessionUser.accountId,
  50. pid: ctx.session.sessionProject.id,
  51. type,
  52. show: status,
  53. };
  54. return await this.createLog(payload);
  55. }
  56. /**
  57. * 根据ip请求获取详细地址
  58. * @param {String} a_ip - ip地址
  59. * @return {String} 详细地址
  60. */
  61. async getIpInfoFromApi(a_ip = '') {
  62. if (!a_ip) return '';
  63. if (a_ip === '127.0.0.1' || a_ip === '::1' || a_ip.indexOf('192.168') !== -1) return '服务器本机访问';
  64. const { ip = '', region = '', city = '', isp = '' } = await this.sendRequest(a_ip);
  65. let address = '';
  66. region && (address += region + '省');
  67. city && (address += city + '市 ');
  68. isp && (address += isp + ' ');
  69. ip && (address += `(${ip})`);
  70. return address;
  71. }
  72. /**
  73. * 发送请求获取详细地址
  74. * @param {String} ip - ip地址
  75. * @param {Number} max - 最大重试次数
  76. * @return {Object} the result of request
  77. * @private
  78. */
  79. async sendRequest(ip, max = 3) {
  80. return new Promise(resolve => {
  81. const start = () => {
  82. if (max <= 0) {
  83. resolve(); // 已达到最大重试次数,返回空的执行承若
  84. }
  85. max--;
  86. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  87. dateType: 'json',
  88. encoding: 'utf8',
  89. timeout: 2000,
  90. headers: {
  91. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  92. },
  93. }).then(({ status, data }) => {
  94. if (status === 200) {
  95. const result = JSON.parse(data.toString()).data;
  96. if (!result.ip) {
  97. start();
  98. } else {
  99. max++;
  100. resolve(result);
  101. }
  102. } else {
  103. max--;
  104. start();
  105. }
  106. }).catch(() => {
  107. start();
  108. });
  109. };
  110. start();
  111. });
  112. }
  113. /**
  114. * 获取登录日志
  115. * @param {Number} pid - 项目id
  116. * @param {Number} uid - 用户id
  117. * @return {Promise<Array>} 日志数组
  118. */
  119. async getLoginLogs(pid, uid) {
  120. return this.db.select(this.tableName, {
  121. where: { pid, uid, show: 0 },
  122. orders: [['create_time', 'desc']],
  123. columns: ['browser', 'create_time', 'ip', 'os', 'address'],
  124. limit: 10, offset: 0,
  125. });
  126. }
  127. }
  128. return LoginLogging;
  129. };