{"size": 1297, "ext": "js", "max_stars_repo_path": "middleware/auth_user.js", "max_stars_repo_name": "tiandiwy/tomjs", "max_stars_repo_stars_event_min_datetime": "2019-11-19T02:11:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T02:11:05.000Z", "max_issues_repo_path": "middleware/auth_user.js", "max_issues_repo_name": "tiandiwy/tomjs", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "middleware/auth_user.js", "max_forks_repo_name": "tiandiwy/tomjs", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.1315789474, "max_line_length": 84, "alphanum_fraction": 0.5797995374}
const require2 = require('tomjs/handlers/require2');
const { isObject } = require2('tomjs/handlers/base_tools');
const { getDBObjByID } = require2('tomjs/handlers/db_tools');
const configs = require2('tomjs/configs')();
const UserModel = require2(configs.auth.auth_model);

module.exports = async function (ctx, next) {
    if (!isObject(ctx.auth)) {
        ctx.auth = {};
        ctx.auth.ID = undefined;
        ctx.auth.USER = undefined;
    }

    ctx.auth.id = () => {
        if (ctx.auth.ID) { return ctx.auth.ID; }
        else if (isObject(ctx.state) && isObject(ctx.state[configs.auth.jwt_key])) {
            ctx.auth.ID = ctx.state[configs.auth.jwt_key][configs.auth.jwt_key_id];
            return ctx.auth.ID;
        }
        return undefined;
    };
    if (!ctx.auth.ID) { ctx.auth.ID = ctx.auth.id(); }

    ctx.auth.user = async () => {
        let users = UserModel.Model();
        if (isObject(ctx.state) && isObject(ctx.state[configs.auth.jwt_key])) {
            let id = ctx.state[configs.auth.jwt_key][configs.auth.jwt_key_id];
            if (id) {
                ctx.auth.USER = await getDBObjByID(users, id);
                return ctx.auth.USER;
            }
        }
        ctx.auth.USER = undefined;
        return ctx.auth.USER;
    };
    return next();
};
