package com.ankurm.authdemo;

import com.ankurm.authdemo.auth.InMemoryLegacyDirectory;
import com.ankurm.authdemo.web.AuthenticationAudit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("layered")
class LayeredProviderTests {

    @Autowired
    MockMvc mvc;
    @Autowired
    AuthenticationAudit audit;
    @Autowired
    InMemoryLegacyDirectory directory;

    @BeforeEach
    void reset() {
        audit.clear();
        directory.setAvailable(true);
    }

    @AfterEach
    void restore() {
        directory.setAvailable(true);
    }

    private String body(String path, MockHttpSession s) throws Exception {
        return mvc.perform(get(path).session(s)).andReturn().getResponse().getContentAsString();
    }

    private int status(String path, MockHttpSession s) throws Exception {
        return mvc.perform(get(path).session(s)).andReturn().getResponse().getStatus();
    }

    /** Event class names in the order they fired, e.g. "AuthenticationSuccessEvent + InteractiveAuthenticationSuccessEvent". */
    private String lastEvent() {
        return audit.events().stream().map(e -> e.substring(0, e.indexOf(' '))).collect(java.util.stream.Collectors.joining(" + "));
    }

    @Test
    void whichProviderAnswersWhom() throws Exception {
        Transcript t = new Transcript("03-layered-providers");
        t.line("Chain order: EncodedCustomAuthProvider (internal users) -> LegacyDirectoryAuthProvider (mainframe)");
        t.line("");

        audit.clear();
        var user = Logins.login(mvc, "user", "password");
        String userEvent = lastEvent();
        String userAuthorities = body("/whoami", user.session());
        t.line("user/password    %-14s %s", user.describe(), userEvent);
        t.line("  /whoami -> %s", userAuthorities);

        audit.clear();
        var admin = Logins.login(mvc, "admin", "secret");
        String adminEvent = lastEvent();
        String adminAuthorities = body("/whoami", admin.session());
        t.line("admin/secret     %-14s %s", admin.describe(), adminEvent);
        t.line("  /whoami -> %s", adminAuthorities);

        audit.clear();
        var locked = Logins.login(mvc, "locked", "secret");
        String lockedEvent = lastEvent();
        t.line("locked/secret    %-14s %s", locked.describe(), lockedEvent);

        audit.clear();
        var ghost = Logins.login(mvc, "ghost", "whatever");
        String ghostEvent = lastEvent();
        t.line("ghost/whatever   %-14s %s", ghost.describe(), ghostEvent);

        audit.clear();
        var wrong = Logins.login(mvc, "admin", "wrong");
        String wrongEvent = lastEvent();
        t.line("admin/wrong      %-14s %s", wrong.describe(), wrongEvent);

        directory.setAvailable(false);
        t.line("");
        t.line("-- legacy directory switched off --");
        audit.clear();
        var userDown = Logins.login(mvc, "user", "password");
        String userDownEvent = lastEvent();
        t.line("user/password    %-14s %s", userDown.describe(), userDownEvent);

        audit.clear();
        var adminDown = Logins.login(mvc, "admin", "secret");
        String adminDownEvent = lastEvent();
        t.line("admin/secret     %-14s %s", adminDown.describe(), adminDownEvent);
        t.write();

        assertThat(userEvent).isEqualTo("AuthenticationSuccessEvent + InteractiveAuthenticationSuccessEvent");
        assertThat(userAuthorities).contains("FACTOR_PASSWORD").contains("ROLE_USER").doesNotContain("ROLE_ADMIN");
        assertThat(adminEvent).isEqualTo("AuthenticationSuccessEvent + InteractiveAuthenticationSuccessEvent");
        assertThat(adminAuthorities).contains("ROLE_ADMIN");
        assertThat(lockedEvent).isEqualTo("AuthenticationFailureLockedEvent");
        assertThat(ghostEvent).isEqualTo("AuthenticationFailureBadCredentialsEvent");
        assertThat(wrongEvent).isEqualTo("AuthenticationFailureBadCredentialsEvent");
        assertThat(userDown.succeeded()).isTrue();
        assertThat(adminDownEvent).isEqualTo("AuthenticationFailureServiceExceptionEvent");
    }

    @Test
    void secondFactorGuardsAdminOnly() throws Exception {
        Transcript t = new Transcript("04-mfa-step-up");
        var admin = Logins.login(mvc, "admin", "secret");
        MockHttpSession s = admin.session();

        int dashboard = status("/user/dashboard", s);
        int panelBefore = status("/admin/panel", s);
        String authBefore = body("/whoami", s);

        int wrong = mvc.perform(post("/mfa/otp").param("code", "000000").session(s).with(csrf()))
                .andReturn().getResponse().getStatus();
        int panelAfterWrong = status("/admin/panel", s);

        int right = mvc.perform(post("/mfa/otp").param("code", "246810").session(s).with(csrf()))
                .andReturn().getResponse().getStatus();
        int panelAfter = status("/admin/panel", s);
        String authAfter = body("/whoami", s);

        var user = Logins.login(mvc, "user", "password");
        mvc.perform(post("/mfa/otp").param("code", "246810").session(user.session()).with(csrf()));
        int userPanel = status("/admin/panel", user.session());

        t.line("admin logs in with password only");
        t.line("  GET  /user/dashboard           -> %d", dashboard);
        t.line("  GET  /admin/panel              -> %d", panelBefore);
        t.line("  GET  /whoami                   -> %s", authBefore);
        t.line("admin submits a wrong code");
        t.line("  POST /mfa/otp code=000000      -> %d", wrong);
        t.line("  GET  /admin/panel              -> %d", panelAfterWrong);
        t.line("admin submits the right code");
        t.line("  POST /mfa/otp code=246810      -> %d", right);
        t.line("  GET  /admin/panel              -> %d", panelAfter);
        t.line("  GET  /whoami                   -> %s", authAfter);
        t.line("user (no ADMIN role) passes the one-time-code step too");
        t.line("  GET  /admin/panel              -> %d", userPanel);
        t.write();

        assertThat(dashboard).isEqualTo(200);
        assertThat(panelBefore).isEqualTo(403);
        assertThat(wrong).isEqualTo(401);
        assertThat(panelAfterWrong).isEqualTo(403);
        assertThat(right).isEqualTo(200);
        assertThat(panelAfter).isEqualTo(200);
        assertThat(authBefore).doesNotContain("FACTOR_OTT");
        assertThat(authAfter).contains("FACTOR_OTT").contains("FACTOR_PASSWORD").contains("ROLE_ADMIN");
        assertThat(userPanel).isEqualTo(403);
    }
}
