login_logging.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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. try {
  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. } catch (error) {
  73. return '';
  74. }
  75. }
  76. /**
  77. * 发送请求获取详细地址
  78. * @param {String} ip - ip地址
  79. * @return {Object} the result of request
  80. * @private
  81. */
  82. async sendRequest(ip) {
  83. return new Promise((resolve, reject) => {
  84. this.ctx.curl(`https://api01.aliyun.venuscn.com/ip?ip=${ip}`, {
  85. dateType: 'json',
  86. encoding: 'utf8',
  87. timeout: 2000,
  88. headers: {
  89. Authorization: 'APPCODE 85c64bffe70445c4af9df7ae31c7bfcc',
  90. },
  91. }).then(({ status, data }) => {
  92. if (status === 200) {
  93. const result = JSON.parse(data.toString()).data;
  94. if (!result.ip) {
  95. resolve();
  96. } else {
  97. resolve(result);
  98. }
  99. } else {
  100. resolve();
  101. }
  102. }).catch(error => {
  103. reject(error);
  104. });
  105. });
  106. }
  107. /**
  108. * 获取登录日志
  109. * @param {Number} pid - 项目id
  110. * @param {Number} uid - 用户id
  111. * @return {Promise<Array>} 日志数组
  112. */
  113. async getLoginLogs(pid, uid) {
  114. return this.db.select(this.tableName, {
  115. where: { pid, uid, show: 0 },
  116. orders: [['create_time', 'desc']],
  117. columns: ['browser', 'create_time', 'ip', 'os', 'address'],
  118. limit: 10, offset: 0,
  119. });
  120. }
  121. }
  122. return LoginLogging;
  123. };