'use strict';

// 加密类
const crypto = require('crypto');
module.exports = options => {
    /**
     * session判断中间件
     *
     * @param {function} next - 中间件继续执行的方法
     * @return {void}
     */
    return function* sessionAuth(next) {
        try {
            // 判断session
            const userSession = this.session.userSession;
            if (userSession === undefined) {
                throw '不存在session';
            }
            // 校验session
            if (userSession.username === undefined || userSession.loginTime === undefined) {
                throw '用户数据不完整';
            }
            // 校验session
            const sessionToken = crypto.createHmac('sha1', userSession.loginTime + '')
                .update(userSession.username).digest().toString('base64');
            if (sessionToken !== userSession.sessionToken) {
                throw 'session数据错误';
            }

            // 同步消息
            //yield this.service.notify.syncNotifyData();
        } catch (error) {
            console.log(error);
            return this.redirect('/');
        }
        yield next;
    };
};
