sso.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. /**
  3. * sso相关接口
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/11/15
  7. * @version
  8. */
  9. // 加密类
  10. const crypto = require('crypto');
  11. class SSO {
  12. /**
  13. * 构造函数
  14. *
  15. * @param {Object} ctx - egg全局变量
  16. * @return {void}
  17. */
  18. constructor(ctx) {
  19. this.authUrl = 'http://sso.smartcost.com.cn/api/jzlogin';
  20. this.ctx = ctx;
  21. this.accountID = 0;
  22. }
  23. /**
  24. * SSO登录验证
  25. *
  26. * @param {String} username - cld用户名
  27. * @param {String} password - cld密码
  28. * @return {boolean} - 验证结果
  29. */
  30. async loginValid(username, password) {
  31. let result = false;
  32. try {
  33. if (username === '' || password === '') {
  34. throw '用户名或密码错误';
  35. }
  36. // 生成加密token
  37. const postData = {
  38. username,
  39. userpasswd: password,
  40. };
  41. const responseData = await this.ctx.helper.sendRequest(this.authUrl, postData);
  42. if (responseData.length <= 0 || typeof responseData === 'number') {
  43. throw '接口返回错误:' + responseData;
  44. }
  45. // 如果验证成功,则新增SSO数据到数据库
  46. const customerId = await this.ctx.service.customer.addSSOUser(responseData[0]);
  47. this.accountID = customerId;
  48. // 更新用户登录时间
  49. const updateData = {
  50. last_login: new Date().getTime() / 1000,
  51. };
  52. result = await this.ctx.service.customer.update(updateData, { email: responseData[0].useremail });
  53. } catch (error) {
  54. console.log('sso:' + error);
  55. result = false;
  56. }
  57. return result;
  58. }
  59. /**
  60. * 获取SSO用户数据
  61. *
  62. * @param {Number} ssoID - sso中的id
  63. * @return {String} - 返回json数据
  64. */
  65. async getSSOUserData(ssoID) {
  66. let result = {};
  67. try {
  68. result = ssoID;
  69. } catch (error) {
  70. result = {};
  71. }
  72. return result;
  73. }
  74. }
  75. module.exports = SSO;