login_logging.js 4.3 KB

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