// SPDX-FileCopyrightText: 2024 Redict Contributors
// SPDX-FileCopyrightText: 2024 Salvatore Sanfilippo <antirez at gmail dot com>
//
// SPDX-License-Identifier: BSD-3-Clause
// SPDX-License-Identifier: LGPL-3.0-only

#include "redictmodule.h"

#include <string.h>

/* This is a second sample module to validate that module authentication callbacks can be registered
 * from multiple modules. */

/* Non Blocking Module Auth callback / implementation. */
int auth_cb(RedictModuleCtx *ctx, RedictModuleString *username, RedictModuleString *password, RedictModuleString **err) {
    const char *user = RedictModule_StringPtrLen(username, NULL);
    const char *pwd = RedictModule_StringPtrLen(password, NULL);
    if (!strcmp(user,"foo") && !strcmp(pwd,"allow_two")) {
        RedictModule_AuthenticateClientWithACLUser(ctx, "foo", 3, NULL, NULL, NULL);
        return REDICTMODULE_AUTH_HANDLED;
    }
    else if (!strcmp(user,"foo") && !strcmp(pwd,"deny_two")) {
        RedictModuleString *log = RedictModule_CreateString(ctx, "Module Auth", 11);
        RedictModule_ACLAddLogEntryByUserName(ctx, username, log, REDICTMODULE_ACL_LOG_AUTH);
        RedictModule_FreeString(ctx, log);
        const char *err_msg = "Auth denied by Misc Module.";
        *err = RedictModule_CreateString(ctx, err_msg, strlen(err_msg));
        return REDICTMODULE_AUTH_HANDLED;
    }
    return REDICTMODULE_AUTH_NOT_HANDLED;
}

int test_rm_register_auth_cb(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    RedictModule_RegisterAuthCallback(ctx, auth_cb);
    RedictModule_ReplyWithSimpleString(ctx, "OK");
    return REDICTMODULE_OK;
}

int RedictModule_OnLoad(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    if (RedictModule_Init(ctx,"moduleauthtwo",1,REDICTMODULE_APIVER_1)== REDICTMODULE_ERR)
        return REDICTMODULE_ERR;
    if (RedictModule_CreateCommand(ctx,"testmoduletwo.rm_register_auth_cb", test_rm_register_auth_cb,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;
    return REDICTMODULE_OK;
}