userUtil.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. let redis = require('../database/redisStorage');
  2. let config = require('../config/config')
  3. module.exports = {
  4. /**
  5. * 登录,生成session
  6. * 使用时间与random参数确保前后两次session不固定
  7. * ICON_SESSION 用与判断每次请求判断用户是否是同一个
  8. *
  9. * @param {Integer} userId 用户ID
  10. * @param {Object} ctx 请求对象
  11. * @return {String} session的key
  12. */
  13. async setIconSession (userId, ctx) {
  14. return await redis.set({
  15. userId: userId,
  16. time: global.globalConfig.nowTime,
  17. random: Math.random(),
  18. type: 'ICON_SESSION'
  19. });
  20. },
  21. /**
  22. * 用于自动登录的session
  23. *
  24. * @param {Integer} userId 用户ID
  25. * @param {Object} ctx 请求对象
  26. * @return {String} session的key
  27. */
  28. async setIconAutoLoginSession (userId, ctx) {
  29. return await redis.set({
  30. userId: userId,
  31. time: global.globalConfig.nowTime,
  32. random: Math.random(),
  33. type: 'ICON_AUTO_LOGIN_SESSION'
  34. });
  35. },
  36. /**
  37. * 给客户端写会话cookie,每次请求带过来确认身份
  38. *
  39. * @param {String} value session的key
  40. * @param {Boolean} expired 是否过期
  41. * @param {Object} ctx 请求对象
  42. * @return {void}
  43. */
  44. setIconSessionCookie (value, expired, ctx) {
  45. let expiredTime = expired ? new Date(config.defaultExpiresTime) : null;
  46. ctx.cookies.set('ICON_SESSION', value, {
  47. path: '/',
  48. domain: config.host,
  49. expires: expiredTime,
  50. httpOnly: true
  51. })
  52. },
  53. /**
  54. * 给客户端写自动登录cookie,每次请求带过来当会话cookie失效后实现自动登录
  55. *
  56. * @param {String} value session的key
  57. * @param {Boolean} expired 是否过期
  58. * @param {Object} ctx 请求对象
  59. * @return {void}
  60. */
  61. setIconAutoLoginSessionCookie (value, expired, ctx) {
  62. let expiredTime = expired ? new Date(config.defaultExpiresTime) : new Date(global.globalConfig.nowTime + config.autoLoginSessionExpires);
  63. ctx.cookies.set('ICON_AUTO_LOGIN_SESSION', value, {
  64. path: '/',
  65. domain: config.host,
  66. expires: expiredTime,
  67. httpOnly: true
  68. });
  69. },
  70. /**
  71. * 获取客户端写会话cookie,每次请求带过来确认身份
  72. *
  73. * @param {Object} ctx 请求对象
  74. * @return {String} cookie值
  75. */
  76. getIconSessionCookie (ctx) {
  77. return ctx.cookies.get('ICON_SESSION', {
  78. path: '/',
  79. domain: config.host,
  80. httpOnly: true
  81. })
  82. },
  83. /**
  84. * 获取客户端写自动登录cookie
  85. *
  86. * @param {Object} ctx 请求对象
  87. * @return {String} cookie值
  88. */
  89. getIconAutoLoginSessionCookie (ctx) {
  90. return ctx.cookies.get('ICON_AUTO_LOGIN_SESSION', {
  91. path: '/',
  92. domain: config.host,
  93. httpOnly: true
  94. })
  95. }
  96. }