逻辑层和数据接口写好后,就是gate服务器,不用修改,直接拿来用
开始用auth做一个功能,来实现基于token验证用户权限。在shared文件夹下新建token.js
//node.js crypto模块,主要功能是加密和解密 var crypto = require('crypto'); /** * Create token by uid. Encrypt uid and timestamp to get a token. * encoding * @param {String} uid user id * @param {String|Number} timestamp * @param {String} pwd encrypt password * @return {String} token string */ module.exports.create= function(uid, timestamp,pwd){ var msg = uid +'|' + timestamp; var cipher = crypto.createCipher('aes256', pwd); var enc = cipher.update(msg,'utf8','hex'); enc += cipher.final('hex'); return enc; } /** * Parse token to validate it and get the uid and timestamp. * decoding * @param {String} token token string * @param {String} pwd decrypt password * @return {Object} uid and timestamp that exported from token. null for illegal token. */ module.exports.parse = function(token,pwd){ var decipher = crypto.createDecipher('aes256',pwd); var dec; try{ dec= decipher.update(token,'hex','utf8'); dec += decipher.final('utf8'); }catch(err){ console.error('[token] fail to decrypt token. %j', token); return null; } var ts = dec.split('|'); if(ts.length!=2){ //illegal token return null; } return {uid:ts[0],timestamp:Number(ts[1])}; }
在app/servers下新建auth文件夹,新建remote文件夹,新建authRemote.js
var tokenService =require('../../../../../shared/token'); var userDao = require('../../../dao/userDao'); var Code = require('../../../../../shared/code'); var DEFAULT_SECRET='pomelo_session_secret'; var DEFAULT_EXPIRE=6 * 60 * 60 * 1000; //default session expire time: 6hours module.exports = function(app){ return new Remote(app); }; var Remote = function(app){ this.app = app; var session = app.get('session') || {}; this.secret = session.secret || DEFAULT_SECRET; this.expire = session.expire || DEFAULT_EXPIRE; }; var pro = Remote.prototype; /** * Auth token and check whether expire. * * @param {String} token token string * @param {Function} cb * @return {Void} */ pro.auth = function(token,cb){ var res=tokenService.parse(token, this.secret); if(!res){ cb(null, Code.ENTRY.FA_TOKEN_ILLEGAL); return; } if(!checkExpire(res, this.expire)){ cb(null,Code.ENTRY.FA_TOKEN_EXPIRE); return; } userDao.getUserById(res.uid, function(err,user){ if(err){ cb(err); return; } cb(null, Code.OK, user); }); } /** * Check the token whether expire. * * @param {Object} token token info * @param {Number} expire expire time * @return {Boolean} true for not expire and false for expire */ var checkExpire = function(token,expire){ if(expire<0){ //negative expire means never expire return true; } return (Date.now() - token.timestamp) < expire; }