login_logging.js 4.5 KB

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