koa-session源码学习——session处理流程

上一篇文章中,咱们以ctx.session.views=2 这一行代码为线索,探讨了示例代码以及koa-session源码的总体执行流程,sess.session为追踪重点,今天咱们进一步完善源码中关于session的处理流程。json

咱们接着上篇的内容向下进行,上一篇中的this.session打印以下:cookie

Session {_sessCtx: ContextSession, _ctx: Object, isNew: true, views: 2}

 

咱们从Index.js的 commit()方法提及:session

return async function session(ctx, next) {
    const sess = ctx[CONTEXT_SESSION];
    if (sess.store) await sess.initFromExternal();
    try {
      await next();
    } catch (err) {
      throw err;
    } finally {
      if (opts.autoCommit) {
        await sess.commit();
      }
    }
  };

sess.commit()调用的是 ContextSession 里的commit方法,首先来看该方法的开头部分:koa

const session = this.session;
const opts = this.opts;
const ctx = this.ctx;

咱们将这里的session打印出来,结果以下:async

Session {_sessCtx: ContextSession, _ctx: Object, isNew: true, views: 2}

发现到这里尚未加密,咱们继续向下看,_shouldSaveSession()方法里的:this

const json = session.toJSON();

此时打印出json:编码

Object {views: 2}

能够看到上面的session只剩下了views属性,来看看.JSON()方法的代码:加密

toJSON() {
    const obj = {};

    Object.keys(this).forEach(key => {
      if (key === 'isNew') return;
      if (key[0] === '_') return;           //key[0]表明key的第一位
      obj[key] = this[key];
    });

    return obj;
  }

能够理解,是将session里的 isNew属性 和 以‘_’开头的属性都去掉了。spa

 

继续看_shouldSaveSession()方法里的:插件

const changed = prevHash !== util.hash(json);
if (changed) return 'changed';

prevHash为create()方法里生成的,假设咱们是第一次执行ctx.session.views=2,ctx.cookies.get 为空,所以这里的 prevHash为undefined,咱们再将util.hash(json),打印出来,查看一下:

552152158

你会发现原来的json,由Object {views: 2}变为了552152158。 所以这段代码返回的是 ‘changed’

 

咱们来看util.hash()方法:

hash(sess) {
    return crc(JSON.stringify(sess));
  },

很简单的代码!用的crc插件进行处理,其中JSON.stringify(sess)的做用是,将json从 Object {views: 2} 变为:{"views":2},由object格式变为了JSON格式。

 

最后到save()方法,先将待保存的session对象,添加了_expire属性和_maxAge属性:

// set expire for check
json._expire = maxAge + Date.now();
json._maxAge = maxAge;

咱们再将json打印出来:

Object {views: 2, _expire: 1592550308718, _maxAge: 86400000}

 

而后对整个json也就是session进行base64编码加密:

json = opts.encode(json);

加密后的json再次打印出来为:

eyJ2aWV3cyI6MiwiX2V4cGlyZSI6MTU5MjU1MDM3MjI0MiwiX21heEFnZSI6ODY0MDAwMDB9

 

此时在因特网上传输起来,已经具备了必定得保密性。

 

base64编码方法以下:

encode(body) {
  body = JSON.stringify(body);
  return Buffer.from(body).toString('base64');    //base64编码实际是对二进制数进行编码,Buffer.from()为Node.js处理二进制数据时使用。
}

 

对应的base64解码方法:

decode(string) {
  let json = Buffer.from(string,'base64').toString('utf-8');
  json = JSON.parse(json);
  return json;
}

 

最后将base64编码的json,保存到cookie中:

this.ctx.cookies.set(key, json, opts);

 

由此咱们能够看到,session其实是以cookie 的形式保存的。

 

最后附上base64加密、解密源码,感兴趣的朋友能够研究下:

const _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="

// private method for UTF-8 encoding
function _utf8_encode(string) {
  string = string.replace(/\r\n/g, "\n");
  var utftext = "";
  for (var n = 0; n < string.length; n++) {
    var c = string.charCodeAt(n);
    if (c < 128) {
      utftext += String.fromCharCode(c);
    } else if ((c > 127) && (c < 2048)) {
      utftext += String.fromCharCode((c >> 6) | 192);
      utftext += String.fromCharCode((c & 63) | 128);
    } else {
      utftext += String.fromCharCode((c >> 12) | 224);
      utftext += String.fromCharCode(((c >> 6) & 63) | 128);
      utftext += String.fromCharCode((c & 63) | 128);
    }

  }
  return utftext;
}

function _utf8_decode(utftext) {
  var string = "";
  var i = 0;
  var c = 0;
  var c3 = 0;
  var c2 = 0;
  while (i < utftext.length) {
    c = utftext.charCodeAt(i);
    if (c < 128) {
      string += String.fromCharCode(c);
      i++;
    } else if ((c > 191) && (c < 224)) {
      c2 = utftext.charCodeAt(i + 1);
      string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
      i += 2;
    } else {
      c2 = utftext.charCodeAt(i + 1);
      c3 = utftext.charCodeAt(i + 2);
      string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
      i += 3;
    }
  }
  return string;
}

export default {
  // public method for encoding
  encode: function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;
    input = _utf8_encode(input);
    while (i < input.length) {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;
      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }
      output = output +
        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
    }
    return output;
  },

  // public method for decoding
  decode: function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
      enc1 = _keyStr.indexOf(input.charAt(i++));
      enc2 = _keyStr.indexOf(input.charAt(i++));
      enc3 = _keyStr.indexOf(input.charAt(i++));
      enc4 = _keyStr.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }
    }
    output = _utf8_decode(output);
    return output;
  }
}

 

若是文章中有不正确的地方,欢迎你们交流指正。

相关文章
相关标签/搜索