'use strict';

module.exports = (options, app) => {

  return async function(ctx, next) {

    const uuid = ctx.headers.uuid;
    const key = 'course_v5_user_session_' + uuid;
    let userInfo = await ctx.app.memcache.get(key);
    if (!userInfo) {
      userInfo = await ctx.classModel.V5.CourseUser.findOne({ where: { uuid, is_deleted: 0 } });
      if (ctx.isEmpty(userInfo)) {
        ctx.failed('用户不存在');
      } else {
        await ctx.app.memcache.set(key, { user_uuid: uuid, openid: userInfo.openid, session_key: '', phone: userInfo.phone }, 86400 * 7);
      }
    }
    const openid = userInfo.openid;
    const phone = userInfo.phone;
    const authToken = ctx.headers.auth_token;
    if (ctx.helper.md5(uuid + openid + phone + 'jbwl') !== authToken) {
      ctx.failed('login auth error');
    }
    ctx.setUserUuid(uuid);
    ctx.setOpenId(openid);

    await next();
  };
};
