mock平台

token.js 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const yapi = require('../yapi')
  2. const crypto = require('crypto');
  3. /*
  4. 下面是使用加密算法
  5. */
  6. // 创建加密算法
  7. const aseEncode = function(data, password) {
  8. // 如下方法使用指定的算法与密码来创建cipher对象
  9. const cipher = crypto.createCipher('aes192', password);
  10. // 使用该对象的update方法来指定需要被加密的数据
  11. let crypted = cipher.update(data, 'utf-8', 'hex');
  12. crypted += cipher.final('hex');
  13. return crypted;
  14. };
  15. // 创建解密算法
  16. const aseDecode = function(data, password) {
  17. /*
  18. 该方法使用指定的算法与密码来创建 decipher对象, 第一个算法必须与加密数据时所使用的算法保持一致;
  19. 第二个参数用于指定解密时所使用的密码,其参数值为一个二进制格式的字符串或一个Buffer对象,该密码同样必须与加密该数据时所使用的密码保持一致
  20. */
  21. const decipher = crypto.createDecipher('aes192', password);
  22. /*
  23. 第一个参数为一个Buffer对象或一个字符串,用于指定需要被解密的数据
  24. 第二个参数用于指定被解密数据所使用的编码格式,可指定的参数值为 'hex', 'binary', 'base64'等,
  25. 第三个参数用于指定输出解密数据时使用的编码格式,可选参数值为 'utf-8', 'ascii' 或 'binary';
  26. */
  27. let decrypted = decipher.update(data, 'hex', 'utf-8');
  28. decrypted += decipher.final('utf-8');
  29. return decrypted;
  30. };
  31. const defaultSalt = 'abcde';
  32. exports.getToken = function getToken(token, uid){
  33. if(!token)throw new Error('token 不能为空')
  34. yapi.WEBCONFIG.passsalt = yapi.WEBCONFIG.passsalt || defaultSalt;
  35. return aseEncode(uid + '|' + token, yapi.WEBCONFIG.passsalt)
  36. }
  37. exports.parseToken = function parseToken(token){
  38. if(!token)throw new Error('token 不能为空')
  39. yapi.WEBCONFIG.passsalt = yapi.WEBCONFIG.passsalt || defaultSalt;
  40. let tokens;
  41. try{
  42. tokens = aseDecode(token, yapi.WEBCONFIG.passsalt)
  43. }catch(e){}
  44. if(tokens && typeof tokens === 'string' && tokens.indexOf('|') > 0){
  45. tokens = tokens.split('|')
  46. return {
  47. uid: tokens[0],
  48. projectToken: tokens[1]
  49. }
  50. }
  51. return false;
  52. }