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. }
  22. /**
  23. * SSO登录验证
  24. *
  25. * @param {String} username - cld用户名
  26. * @param {String} password - cld密码
  27. * @return {boolean} - 验证结果
  28. */
  29. async loginValid(username, password) {
  30. let result = false;
  31. try {
  32. if (username === '' || password === '') {
  33. throw '用户名或密码错误';
  34. }
  35. // 生成加密token
  36. const postData = {
  37. username,
  38. userpasswd: password,
  39. };
  40. const responseData = await this.ctx.helper.sendRequest(this.authUrl, postData);
  41. if (responseData.length <= 0 || typeof responseData === 'number') {
  42. throw '接口返回错误:' + responseData;
  43. }
  44. // 如果验证成功,则新增SSO数据到数据库
  45. const addResult = await this.ctx.service.customer.addSSOUser(responseData[0]);
  46. if (!addResult) {
  47. console.log('sso user add error');
  48. }
  49. // 更新用户登录时间
  50. const updateData = {
  51. last_login: new Date().getTime() / 1000,
  52. };
  53. result = await this.ctx.service.customer.update(updateData, { email: responseData[0].useremail });
  54. } catch (error) {
  55. console.log('sso:' + error);
  56. result = false;
  57. }
  58. return result;
  59. }
  60. /**
  61. * 获取SSO用户数据
  62. *
  63. * @param {Number} ssoID - sso中的id
  64. * @return {String} - 返回json数据
  65. */
  66. async getSSOUserData(ssoID) {
  67. let result = {};
  68. try {
  69. result = ssoID;
  70. } catch (error) {
  71. result = {};
  72. }
  73. return result;
  74. }
  75. }
  76. module.exports = SSO;