login_logging.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. console.log('a_ip', a_ip);
  63. if (!a_ip) return '';
  64. if (a_ip === '127.0.0.1' || a_ip === '::1' || a_ip.indexOf('192.168') !== -1) return '服务器本机访问';
  65. const { ip = '', region = '', city = '', isp = '' } = await this.sendRequest(a_ip);
  66. let address = '';
  67. region && (address += region + '省');
  68. city && (address += city + '市 ');
  69. isp && (address += isp + ' ');
  70. ip && (address += `(${ip})`);
  71. return address;
  72. }
  73. /**
  74. * 发送请求获取详细地址
  75. * @param {String} ip - ip地址
  76. * @param {Number} max - 最大重试次数
  77. * @return {Object} the result of request
  78. * @private
  79. */
  80. async sendRequest(ip, max = 3) {
  81. return new Promise(resolve => {
  82. const start = () => {
  83. if (max <= 0) {
  84. resolve(); // 已达到最大重试次数,返回空的执行承若
  85. }
  86. max--;
  87. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  88. dateType: 'json',
  89. encoding: 'utf8',
  90. timeout: 2000,
  91. headers: {
  92. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  93. },
  94. }).then(({ status, data }) => {
  95. if (status === 200) {
  96. const result = JSON.parse(data.toString()).data;
  97. if (!result.ip) {
  98. start();
  99. } else {
  100. max++;
  101. resolve(result);
  102. }
  103. } else {
  104. max--;
  105. start();
  106. }
  107. }).catch(() => {
  108. start();
  109. });
  110. };
  111. start();
  112. });
  113. }
  114. /**
  115. * 获取登录日志
  116. * @param {Number} pid - 项目id
  117. * @param {Number} uid - 用户id
  118. * @return {Promise<Array>} 日志数组
  119. */
  120. async getLoginLogs(pid, uid) {
  121. return this.db.select(this.tableName, {
  122. where: { pid, uid, show: 0 },
  123. orders: [['create_time', 'desc']],
  124. columns: ['browser', 'create_time', 'ip', 'os', 'address'],
  125. limit: 10, offset: 0,
  126. });
  127. }
  128. }
  129. return LoginLogging;
  130. };