session.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /*
  2. * @Author: HonorLee
  3. * @Version 1.0
  4. * @LastUpdate 2018/6/19
  5. * @License MIT
  6. */
  7. import { RedisClientType } from '@redis/client';
  8. import MD5 from 'md5'
  9. export default class Session{
  10. public static setStorageType(type:'file'|'redis',instance:RedisClientType|undefined){
  11. SessionManager._storageType = type;
  12. if(type=='redis') SessionManager._storageInstance = instance;
  13. }
  14. //Session实例
  15. public sessionID:string;
  16. private _sessionKey:string;
  17. private _requestData:RequestData;
  18. constructor(requestData:RequestData,sessionID?:string|undefined){
  19. this.sessionID = sessionID?sessionID:MD5(new Date().getTime()+''+Math.floor(Math.random()*9000+1000));
  20. this._sessionKey = `session_${this.sessionID}`;
  21. this._requestData = requestData;
  22. if(!sessionID && this._requestData.res){
  23. let sessionCookie = `SESSIONID=${this.sessionID};max-age=${7*24*60*60};path=/`;
  24. if(requestData.refer.host) sessionCookie += `;domain=${requestData.refer.host}`;
  25. this._requestData.res.setHeader('Set-Cookie',sessionCookie);
  26. }
  27. }
  28. async set(key:string,value:any|null){
  29. if(!await SessionManager.check(this._sessionKey)){
  30. this.set('sessionid',this.sessionID);
  31. this.setExpire(7*24*60*60);
  32. }
  33. return await SessionManager.set(this._sessionKey,key,value);
  34. }
  35. async setExpire(expire:number,autoRenew?:boolean){
  36. return await SessionManager.setExpire(this._sessionKey,expire,autoRenew)
  37. }
  38. async get(key:string){
  39. return await SessionManager.get(this._sessionKey,key);
  40. }
  41. async getAll(){
  42. return await SessionManager.getAll(this._sessionKey);
  43. }
  44. async clear(){
  45. return await SessionManager.clear(this._sessionKey);
  46. }
  47. }
  48. class SessionManager{
  49. //全局存储控制
  50. public static _storageType = 'file'; //默认以文件形式存储
  51. public static _storageInstance:RedisClientType|undefined;
  52. public static async check(sessionKey:string){
  53. if(SessionManager._storageType=='redis' && SessionManager._storageInstance){
  54. const ret = await SessionManager._storageInstance.exists(sessionKey);
  55. if(ret==1) return true;
  56. return false;
  57. }
  58. }
  59. public static async set(sessionKey:string,key:string,value:any|null){
  60. if(SessionManager._storageType=='redis' && SessionManager._storageInstance){
  61. let ret;
  62. if(value==null){
  63. ret= await SessionManager._storageInstance.hDel(sessionKey,key);
  64. }else{
  65. ret= await SessionManager._storageInstance.hSet(sessionKey,key,value);
  66. }
  67. if(ret) return true
  68. else return false;
  69. }else{
  70. }
  71. return true;
  72. }
  73. public static async setExpire(sessionKey:string,expire:number,autoRenew?:boolean){
  74. if(SessionManager._storageType=='redis' && SessionManager._storageInstance){
  75. const ret = await SessionManager._storageInstance?.expire(sessionKey,expire);
  76. if(!ret) return false;
  77. }else{
  78. }
  79. return true;
  80. }
  81. public static async get(sessionKey:string,key:string){
  82. let ret;
  83. if(SessionManager._storageType=='redis' && SessionManager._storageInstance){
  84. ret = await SessionManager._storageInstance.hGet(sessionKey,key);
  85. }else{
  86. }
  87. return ret;
  88. }
  89. public static async getAll(sessionKey:string){
  90. let ret;
  91. if(SessionManager._storageType=='redis' && SessionManager._storageInstance){
  92. ret = await SessionManager._storageInstance.hGetAll(sessionKey);
  93. }else{
  94. }
  95. return true;
  96. }
  97. public static async clear(sessionKey:string){
  98. let ret;
  99. if(SessionManager._storageType=='redis' && SessionManager._storageInstance){
  100. ret = await SessionManager._storageInstance.del(sessionKey);
  101. }else{
  102. }
  103. return ret;
  104. }
  105. }
  106. /**
  107. setWithSessionID:function(sessionID,key,value,callback){
  108. callback = Manager.buildCallback(callback);
  109. if(!key || value==null) return callback.call(this,'Session key or value is empty',null);
  110. let _this = this;
  111. let session = {};
  112. session.id = sessionID;
  113. session.data = {};
  114. session.data[key] = value;
  115. session.expire = Config.SessionExpire*60;
  116. session.expireTime = new Date().getTime()+session.expire*1000;
  117. session.autoRenewExpire = Config.SessionExpire*60;
  118. Manager.set(session,function(err){
  119. if(err) return callback.call(_this,'Session set err;',null);
  120. callback.call(_this,null,session);
  121. });
  122. },
  123. setExpireTime:function(sessionid,expire,autoRenewExpire,callback){
  124. let _this = this;
  125. callback = Manager.buildCallback(callback);
  126. if(!sessionid) return callback.call(this,'Session id is empty',null);
  127. if(!expire) return callback.call(this,'Session expire must bigger than 0',null);
  128. Session.get(sessionid,function(err,data){
  129. if(err || !data) return callback.call(this,'Session is gone',null);
  130. let session = data;
  131. session.expire = expire*60;
  132. autoRenewExpire = autoRenewExpire*1;
  133. if(autoRenewExpire>0) session.autoRenewExpire = autoRenewExpire*60;
  134. Manager.set(session,function(err){
  135. if(err){
  136. LOGGER.error(err);
  137. callback.call(_this,'Session set expire error',null);
  138. }else{
  139. callback.call(_this,null,session);
  140. }
  141. })
  142. });
  143. },
  144. update:function(sessionid,key,value,callback){
  145. callback = Manager.buildCallback(callback);
  146. if(!sessionid || !key || value==null) return callback.call(this,'Session id,key or value is empty',null);
  147. let _this = this;
  148. Manager.get(sessionid,function(err,result){
  149. let session;
  150. if(err || result == null){
  151. session = {id:sessionid,data:{}};
  152. }else{
  153. session = result;
  154. }
  155. if(err || result == null || Config.Session.AutoRefresh){
  156. session.expire = session.autoRenewExpire;
  157. session.expireTime = new Date().getTime()+session.expire*1000;
  158. }
  159. session.data[key] = value;
  160. Manager.set(session,function(err){
  161. if(err) return callback.call(_this,'Session set error');
  162. callback.call(_this,null,session)
  163. });
  164. });
  165. },
  166. get:function(sessionid,callback){
  167. callback = Manager.buildCallback(callback);
  168. if(!sessionid) return callback.call(this,'Session id is empty',null);
  169. let _this = this;
  170. Manager.get(sessionid,function(err,result){
  171. callback.call(_this,null,result);
  172. });
  173. },
  174. getKeyValue:function(sessionid,key,callback){
  175. callback = Manager.buildCallback(callback);
  176. if(!sessionid || !key) return callback.call(this,'Session id or key is empty',null);
  177. let _this = this;
  178. Session.get(sessionid,function(err,result){
  179. if(err || !result) return callback.call(_this,null);
  180. callback.call(_this,null,result.data[key]);
  181. });
  182. },
  183. clear:function(sessionid){
  184. if(!sessionid) return;
  185. Manager.clear(sessionid);
  186. },
  187. instance:function(sessionID,callback){
  188. return new Instance(sessionID,callback);
  189. }
  190. };
  191. module.exports = Session;
  192. var Manager = {
  193. get:function(sessionid,callback){
  194. let session;
  195. if(Config.Session.StoreType.toLowerCase()=='memcache' && Config.Database.Memcache.on && Memcache){
  196. Memcache.get('session_'+sessionid,function(err,result){
  197. if(err) return callback(err);
  198. session = result;
  199. callback(null,result);
  200. if(session && Config.Session.AutoRefresh){
  201. session.expire = session.autoRenewExpire;
  202. session.expireTime = new Date().getTime()+session.expire*1000;
  203. Manager.set(session,null);
  204. }
  205. });
  206. }else{
  207. try{
  208. session = JSON.parse(FILE.readFileSync(Core.Path.Session + '/' + sessionid,'UTF-8'));
  209. }catch(e){}
  210. if(session && session.expireTime){
  211. if(new Date().getTime()>session.expireTime){
  212. if(Config.Session.AutoRefresh){
  213. session.expire = session.autoRenewExpire;
  214. session.expireTime = new Date().getTime()+session.expire*1000;
  215. Manager.set(session,null);
  216. }else{
  217. session = null;
  218. Manager.clear(sessionid);
  219. }
  220. }
  221. }
  222. if(callback) callback(null,session);
  223. }
  224. },
  225. set:function(session,callback){
  226. if(Config.Session.StoreType.toLowerCase()=='memcache' && Config.Database.Memcache.on && Memcache){
  227. Memcache.set('session_'+session.id,session,session.expire,function(err){
  228. if(err){
  229. Logger.error(err);
  230. if(callback) callback(err);
  231. return;
  232. }
  233. if(callback) callback();
  234. });
  235. }else{
  236. FILE.writeFileSync(Core.Path.Session + '/' + session.id,JSON.stringify(session),'UTF-8');
  237. if(callback) callback();
  238. }
  239. },
  240. clear:function(sessionid){
  241. if(Config.Session.StoreType.toLowerCase()=='memcache' && Config.Database.Memcache.on && Memcache){
  242. Memcache.del('session_'+sessionid);
  243. }else{
  244. try{
  245. FILE.rmdirSync(Core.Path.Session + '/' + sessionid);
  246. }catch(e){}
  247. }
  248. },
  249. buildCallback:function(callback){
  250. if(callback && typeof callback=='function') return callback;
  251. return function(){};
  252. }
  253. }
  254. var Instance = function(sessionID,callback){
  255. var _data;
  256. var _sessionID = sessionID;
  257. var _this = this;
  258. this.sessionID = _sessionID;
  259. this.get = function(key){
  260. return _data[key];
  261. }
  262. this.set = function(key,value){
  263. _data[key] = value;
  264. Session.update(_sessionID,key,value);
  265. }
  266. this.setExpireTime = function(expire,autoRenewExpire){
  267. Session.setExpireTime(_sessionID,expire,autoRenewExpire);
  268. }
  269. if(sessionID){
  270. Session.get(sessionID,function(err,session){
  271. if(err || !session){
  272. Session.setWithSessionID(sessionID,'status',0,function(err,new_session){
  273. _data = new_session.data;
  274. // _this.sessionID = new_session.id;
  275. if(callback) callback(sessionID,_this);
  276. });
  277. }else{
  278. _data = session.data;
  279. _this.sessionID = session.id;
  280. if(callback) callback(session.id,_this);
  281. }
  282. });
  283. }else{
  284. Session.set('status',0,function(err,new_session){
  285. _data = new_session.data;
  286. _sessionID = new_session.id;
  287. _this.sessionID = new_session.id;
  288. if(callback) callback(new_session.id,_this);
  289. });
  290. }
  291. return this;
  292. }
  293. **/