'use strict';

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

  return async function(ctx, next) {

    const uuid = ctx.headers.uuid;
    const key = 'course_v3_user_session_' + uuid;
    let auth_info = await ctx.app.memcache.get(key);
    if (!auth_info) {
      auth_info = await ctx.classModel.V3.CourseUser.findOne({ where: { uuid } });
      if (ctx.isEmpty(auth_info)) {
        ctx.failed('user not exist');
      } else {
        await ctx.app.memcache.set(key, { user_uuid: uuid, openid: auth_info.openid }, 86400 * 7);
      }
    }
    const openid = auth_info.openid;
    const user_uuid = auth_info.user_uuid;
    const auth_token = ctx.headers.auth_token;
    if (ctx.helper.md5(openid + uuid + 'jbwl') != auth_token) {
      ctx.failed('login auth error');
    }
    // console.info('11111111111111111111111111111111');
    // console.info(auth_info);
    ctx.setUserUuid(user_uuid);
    ctx.setOpenId(openid);

    await next();
  };
};
