Code coverage report for thinkjs/lib/Lib/Behavior/TokenBehavior.js

Statements: 100% (22 / 22)      Branches: 100% (8 / 8)      Functions: 100% (6 / 6)      Lines: 100% (22 / 22)      Ignored: none     

All files » thinkjs/lib/Lib/Behavior/ » TokenBehavior.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45          1   1   5 1   4 4 4 4 1 3 1   2                 4 4 4 4 4 4 3   1 1 1          
/**
 * 给表单生成token
 * @param  {[type]} content){               }} [description]
 * @return {[type]}            [description]
 */
module.exports = Behavior(function(){
  'use strict';
  return {
    run: function(content){
      if (!C('token_on')) {
        return content;
      }
      return this.getToken().then(function(token){
        var key = C('token_key');
        var name = C('token_name');
        if (content.indexOf(key) > -1) {
          return content.replace(key, token);
        }else if (content.indexOf('</form>') > -1) {
          return content.replace('</form>', '<input type="hidden" name="' + name +'" value="' + token + '" /></form>');
        }else{
          return content.replace('</head>', '<meta name="' + name + '" content="' + token + '" /></head>');
        }
      })
    },
    /**
     * 获取token值
     * @return {[type]} [description]
     */
    getToken: function(){
      var Session = thinkRequire('Session');
      Session.start(this.http);
      var tokenName = C('token_name');
      var http = this.http;
      return http.session.get(tokenName).then(function(value){
        if (value) {
          return value;
        }
        var token = Session.uid(32);
        return http.session.set(tokenName, token).then(function(){
          return token;
        })
      })
    }
  }
})