/*
 * Decompiled with CFR 0.152.
 * 
 * Could not load the following classes:
 *  com.fasterxml.jackson.databind.ObjectMapper
 *  com.l7tech.common.http.HttpConstants
 *  com.l7tech.gateway.common.security.rbac.Role
 *  com.l7tech.gateway.common.security.rbac.Role$Tag
 *  com.l7tech.gateway.common.transport.SsgConnector$Endpoint
 *  com.l7tech.identity.FailAttemptsExceededException
 *  com.l7tech.identity.FailInactivityPeriodExceededException
 *  com.l7tech.identity.User
 *  com.l7tech.identity.UserDisabledException
 *  com.l7tech.objectmodel.ObjectModelException
 *  com.l7tech.policy.assertion.credential.LoginCredentials
 *  com.l7tech.server.AuthenticatableHttpServlet
 *  com.l7tech.server.ServerConfig
 *  com.l7tech.server.identity.AuthenticationResult
 *  com.l7tech.server.oauth2.OAuth2VerifierResult
 *  com.l7tech.server.oauth2.SSGOAuth2Issuer
 *  com.l7tech.server.security.rbac.RoleManager
 *  com.l7tech.util.Pair
 *  jakarta.servlet.ServletConfig
 *  jakarta.servlet.ServletException
 *  jakarta.servlet.http.Cookie
 *  jakarta.servlet.http.HttpServletRequest
 *  jakarta.servlet.http.HttpServletResponse
 *  org.apache.commons.lang3.StringUtils
 */
package com.l7tech.server.pm2;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.l7tech.common.http.HttpConstants;
import com.l7tech.gateway.common.security.rbac.Role;
import com.l7tech.gateway.common.transport.SsgConnector;
import com.l7tech.identity.FailAttemptsExceededException;
import com.l7tech.identity.FailInactivityPeriodExceededException;
import com.l7tech.identity.User;
import com.l7tech.identity.UserDisabledException;
import com.l7tech.objectmodel.ObjectModelException;
import com.l7tech.policy.assertion.credential.LoginCredentials;
import com.l7tech.server.AuthenticatableHttpServlet;
import com.l7tech.server.ServerConfig;
import com.l7tech.server.identity.AuthenticationResult;
import com.l7tech.server.oauth2.OAuth2VerifierResult;
import com.l7tech.server.oauth2.SSGOAuth2Issuer;
import com.l7tech.server.security.rbac.RoleManager;
import com.l7tech.util.Pair;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Map;
import javax.security.auth.login.LoginException;
import org.apache.commons.lang3.StringUtils;

public abstract class PM2AbstractServlet
extends AuthenticatableHttpServlet {
    public static final String L7_SESSION_ID;
    protected ServerConfig serverConfig;
    protected RoleManager roleManager;
    protected SSGOAuth2Issuer ssgOAuth2Issuer;
    protected ObjectMapper objectMapper;
    static final long serialVersionUID = 5534419228757305689L;
    private static final String[] b;

    protected String getFeature() {
        return b[18];
    }

    protected SsgConnector.Endpoint getRequiredEndpoint() {
        return SsgConnector.Endpoint.ADMIN_REMOTE_SSM;
    }

    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
        String[] stringArray = b;
        this.serverConfig = (ServerConfig)this.getBean(stringArray[15], ServerConfig.class);
        this.roleManager = (RoleManager)this.getBean(stringArray[1]);
        this.ssgOAuth2Issuer = (SSGOAuth2Issuer)this.getBean(stringArray[10]);
        this.objectMapper = new ObjectMapper();
    }

    protected PM2AuthContext authenticate(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, PM2AuthType pM2AuthType) throws IOException {
        PM2AuthContext pM2AuthContext;
        block5: {
            block6: {
                block4: {
                    pM2AuthContext = new PM2AuthContext();
                    try {
                        if (!PM2AuthType.BASIC.equals((Object)pM2AuthType)) break block4;
                        this.findBasicCredentials(httpServletRequest, pM2AuthContext);
                        break block5;
                    }
                    catch (IOException iOException) {
                        throw PM2AbstractServlet.a(iOException);
                    }
                }
                try {
                    if (!PM2AuthType.TOKEN.equals((Object)pM2AuthType)) break block6;
                    this.findTokenCredentials(httpServletRequest, pM2AuthContext);
                    break block5;
                }
                catch (IOException iOException) {
                    throw PM2AbstractServlet.a(iOException);
                }
            }
            this.findCookieCredentials(httpServletRequest, pM2AuthContext);
        }
        this.verifyCredentials(httpServletResponse, pM2AuthContext, pM2AuthType);
        return pM2AuthContext;
    }

    protected PM2AuthContext authenticate(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        PM2AuthContext pM2AuthContext = new PM2AuthContext();
        this.findAnyCredentials(httpServletRequest, pM2AuthContext);
        this.verifyCredentials(httpServletResponse, pM2AuthContext);
        return pM2AuthContext;
    }

    private void findBasicCredentials(HttpServletRequest httpServletRequest, PM2AuthContext pM2AuthContext) {
        pM2AuthContext.a = this.findCredentialsBasic(httpServletRequest);
    }

    private void findTokenCredentials(HttpServletRequest httpServletRequest, PM2AuthContext pM2AuthContext) {
        String[] stringArray = b;
        String string = httpServletRequest.getHeader(stringArray[7]);
        if (string != null && string.startsWith(stringArray[13])) {
            pM2AuthContext.b = string.substring(7);
        }
    }

    private void findCookieCredentials(HttpServletRequest httpServletRequest, PM2AuthContext pM2AuthContext) {
        Cookie[] cookieArray = httpServletRequest.getCookies();
        if (cookieArray != null) {
            for (Cookie cookie : cookieArray) {
                if (!cookie.getName().equalsIgnoreCase(b[11])) continue;
                pM2AuthContext.b = cookie.getValue();
                break;
            }
        }
    }

    private void findAnyCredentials(HttpServletRequest httpServletRequest, PM2AuthContext pM2AuthContext) {
        String[] stringArray = b;
        String string = httpServletRequest.getHeader(stringArray[14]);
        if (string != null) {
            if (string.startsWith(stringArray[12])) {
                pM2AuthContext.a = this.findCredentialsBasic(httpServletRequest);
            } else if (string.startsWith(b[13])) {
                pM2AuthContext.b = string.substring(7);
            }
        } else {
            this.findCookieCredentials(httpServletRequest, pM2AuthContext);
        }
    }

    private void verifyCredentials(HttpServletResponse httpServletResponse, PM2AuthContext pM2AuthContext, PM2AuthType pM2AuthType) throws IOException {
        block12: {
            block15: {
                block13: {
                    block14: {
                        block10: {
                            block11: {
                                try {
                                    try {
                                        if (!PM2AuthType.BASIC.equals((Object)pM2AuthType)) break block10;
                                        if (pM2AuthContext.a == null) break block11;
                                    }
                                    catch (IOException iOException) {
                                        throw PM2AbstractServlet.a(iOException);
                                    }
                                    this.authenticateUsingLoginCredentials(httpServletResponse, pM2AuthContext);
                                    break block12;
                                }
                                catch (IOException iOException) {
                                    throw PM2AbstractServlet.a(iOException);
                                }
                            }
                            this.doHttpBasicChallenge(httpServletResponse);
                            break block12;
                        }
                        try {
                            try {
                                if (!PM2AuthType.TOKEN.equals((Object)pM2AuthType)) break block13;
                                if (pM2AuthContext.b == null) break block14;
                            }
                            catch (IOException iOException) {
                                throw PM2AbstractServlet.a(iOException);
                            }
                            this.authenticateUsingToken(httpServletResponse, pM2AuthContext);
                            break block12;
                        }
                        catch (IOException iOException) {
                            throw PM2AbstractServlet.a(iOException);
                        }
                    }
                    this.doHttpBearerChallenge(httpServletResponse);
                    break block12;
                }
                try {
                    if (pM2AuthContext.b == null) break block15;
                    this.authenticateUsingToken(httpServletResponse, pM2AuthContext);
                    break block12;
                }
                catch (IOException iOException) {
                    throw PM2AbstractServlet.a(iOException);
                }
            }
            this.respondError(httpServletResponse, 401, b[25]);
        }
    }

    private void verifyCredentials(HttpServletResponse httpServletResponse, PM2AuthContext pM2AuthContext) throws IOException {
        block5: {
            block6: {
                block4: {
                    try {
                        if (pM2AuthContext.a == null) break block4;
                        this.authenticateUsingLoginCredentials(httpServletResponse, pM2AuthContext);
                        break block5;
                    }
                    catch (IOException iOException) {
                        throw PM2AbstractServlet.a(iOException);
                    }
                }
                try {
                    if (pM2AuthContext.b == null) break block6;
                    this.authenticateUsingToken(httpServletResponse, pM2AuthContext);
                    break block5;
                }
                catch (IOException iOException) {
                    throw PM2AbstractServlet.a(iOException);
                }
            }
            this.doHttpBasicChallenge(httpServletResponse);
        }
    }

    private void authenticateUsingToken(HttpServletResponse httpServletResponse, PM2AuthContext pM2AuthContext) throws IOException {
        pM2AuthContext.d = this.ssgOAuth2Issuer.getVerifier().verify(pM2AuthContext.b);
        if (!pM2AuthContext.d.isValid()) {
            Object object;
            int n;
            HttpServletResponse httpServletResponse2;
            PM2AbstractServlet pM2AbstractServlet;
            String string = pM2AuthContext.d.getErrorDescription();
            try {
                pM2AbstractServlet = this;
                httpServletResponse2 = httpServletResponse;
                n = 401;
                object = string.endsWith(".") ? string : string + ".";
            }
            catch (IOException iOException) {
                throw PM2AbstractServlet.a(iOException);
            }
            pM2AbstractServlet.respondError(httpServletResponse2, n, (String)object);
            return;
        }
        pM2AuthContext.f = this.getUser(pM2AuthContext.d.getResult());
        pM2AuthContext.e = true;
    }

    private void authenticateUsingLoginCredentials(HttpServletResponse httpServletResponse, PM2AuthContext pM2AuthContext) throws IOException {
        String string = pM2AuthContext.a.getLogin();
        Object object = "";
        try {
            pM2AuthContext.c = this.adminSessionManager.authenticate(pM2AuthContext.a, false);
        }
        catch (LoginException loginException) {
            httpServletResponse.setStatus(401);
            String[] stringArray = b;
            object = stringArray[21];
        }
        catch (ObjectModelException objectModelException) {
            httpServletResponse.setStatus(401);
            String[] stringArray = b;
            object = stringArray[22];
        }
        catch (UserDisabledException userDisabledException) {
            httpServletResponse.setStatus(403);
            String[] stringArray = b;
            object = "'" + string + stringArray[24];
        }
        catch (FailAttemptsExceededException failAttemptsExceededException) {
            httpServletResponse.setStatus(403);
            String[] stringArray = b;
            object = "'" + string + stringArray[19];
        }
        catch (FailInactivityPeriodExceededException failInactivityPeriodExceededException) {
            httpServletResponse.setStatus(403);
            String[] stringArray = b;
            object = "'" + string + stringArray[23];
        }
        try {
            if (StringUtils.isNotEmpty((CharSequence)object)) {
                httpServletResponse.setContentType(b[0]);
                httpServletResponse.getWriter().println((String)object);
                return;
            }
        }
        catch (LoginException loginException) {
            throw PM2AbstractServlet.a(loginException);
        }
        try {
            if (pM2AuthContext.c == null) {
                this.respondError(httpServletResponse, 401, b[16]);
                return;
            }
        }
        catch (LoginException loginException) {
            throw PM2AbstractServlet.a(loginException);
        }
        pM2AuthContext.f = pM2AuthContext.c.getUser();
        pM2AuthContext.e = true;
    }

    private User getUser(Map<String, Object> map) {
        String[] stringArray = b;
        String string = (String)map.get(stringArray[17]);
        String string2 = (String)map.get(stringArray[6]);
        String string3 = (String)map.get(stringArray[4]);
        return this.ssgOAuth2Issuer.getUser(string2, string, string3);
    }

    /*
     * Loose catch block
     */
    protected boolean verifyRBAC(PM2AuthContext pM2AuthContext) {
        User user = pM2AuthContext.getAuthenticatedUser();
        boolean bl = false;
        try {
            boolean bl2;
            block7: {
                block6: {
                    if (!this.roleManager.isAdministrativeUser(new Pair((Object)user.getProviderId(), (Object)user.getId()), user)) break block6;
                    try {
                        block8: {
                            if (!this.isUserAdmin(user)) break block6;
                            break block8;
                            catch (Exception exception) {
                                throw PM2AbstractServlet.a(exception);
                            }
                        }
                        bl2 = true;
                        break block7;
                    }
                    catch (Exception exception) {
                        throw PM2AbstractServlet.a(exception);
                    }
                }
                bl2 = false;
            }
            bl = bl2;
        }
        catch (Exception exception) {
            // empty catch block
        }
        return bl;
    }

    private boolean isUserAdmin(User user) {
        try {
            Collection collection = this.roleManager.getAssignedRoles(user);
            for (Role role : collection) {
                if (!Role.Tag.ADMIN.equals((Object)role.getTag())) continue;
                return true;
            }
        }
        catch (Exception exception) {
            this.logger.warning(b[2] + exception.getMessage());
            return false;
        }
        return false;
    }

    private void doHttpBearerChallenge(HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setStatus(401);
        String[] stringArray = b;
        httpServletResponse.setHeader(HttpConstants.HEADER_WWW_AUTHENTICATE, stringArray[5]);
        httpServletResponse.setContentType(stringArray[0]);
        httpServletResponse.getWriter().println(stringArray[9]);
    }

    protected void respondError(HttpServletResponse httpServletResponse, int n, String string) throws IOException {
        httpServletResponse.setStatus(n);
        httpServletResponse.setContentType(b[20]);
        PrintWriter printWriter = httpServletResponse.getWriter();
        printWriter.print(n);
        printWriter.print(" ");
        printWriter.print(string);
        printWriter.close();
    }

    protected void respondSuccess(HttpServletResponse httpServletResponse, String string) throws IOException {
        this.respondSuccess(httpServletResponse, string, b[8]);
    }

    protected void respondSuccess(HttpServletResponse httpServletResponse, String string, String string2) throws IOException {
        httpServletResponse.setContentType(string2);
        httpServletResponse.getWriter().print(string);
    }

    private static Exception a(Exception exception) {
        return exception;
    }

    /*
     * Unable to fully structure code
     */
    static {
        block10: {
            block9: {
                var5 = new String[26];
                var3_1 = 0;
                var2_2 = "t\u0018|5~s<a\u0014jzq`8a\u000fw$%>%t\u001b)y\u000br\u0012h$\u001cb>a\u001aa3\u001cE\u000fv.##4e\ta3<j>i\u0013ca$p5r]v.=fp\u0007LJW\u0012\u0016J\u0014\ts\bf+4`$D\u0013\u0006B\u0018e34q\np\u000fk78g5r4`\rA\bp)>q9z\u001cp(>m\u001fa\rt-8`1t\u0014k/~i#o\u0013?a2k1r\u000ea5lv$fP<\u0018A\bp)4m$i\u001ee58l> /a0$j\"e\u0019*\u000fs\u000ec\u000e\u0010v$hOM2\"v5r\u0007LJW\u0012\u0016J\u0014\u0005B\u001cw(2\u0006B\u0018e34q\rA\bp)>q9z\u001cp(>m\fs\u0018v74q\u0013o\u0013b(6\u0016A\bp)4m$i\u001ee58l> \u001be(=f4.\u0005l\u0012c(?\rs\u0018v78`5:<`,8m%']a92f5d\u0018`a<b( \u001be(=f4 \u0011k&>mpa\tp$<s$sS\u0019t\u0018|5~s<a\u0014jzq`8a\u000fw$%>%t\u001b)y\rL\u0012c(?#6a\u0014h$5-\u001eA\bp)4m$i\u001ee58l> \rv.'j4e\u000f$$#q?rS\u001d']a92f5d\u0018`a8m1c\tm78w) \ra38l4.";
                var4_3 = "t\u0018|5~s<a\u0014jzq`8a\u000fw$%>%t\u001b)y\u000br\u0012h$\u001cb>a\u001aa3\u001cE\u000fv.##4e\ta3<j>i\u0013ca$p5r]v.=fp\u0007LJW\u0012\u0016J\u0014\ts\bf+4`$D\u0013\u0006B\u0018e34q\np\u000fk78g5r4`\rA\bp)>q9z\u001cp(>m\u001fa\rt-8`1t\u0014k/~i#o\u0013?a2k1r\u000ea5lv$fP<\u0018A\bp)4m$i\u001ee58l> /a0$j\"e\u0019*\u000fs\u000ec\u000e\u0010v$hOM2\"v5r\u0007LJW\u0012\u0016J\u0014\u0005B\u001cw(2\u0006B\u0018e34q\rA\bp)>q9z\u001cp(>m\fs\u0018v74q\u0013o\u0013b(6\u0016A\bp)4m$i\u001ee58l> \u001be(=f4.\u0005l\u0012c(?\rs\u0018v78`5:<`,8m%']a92f5d\u0018`a<b( \u001be(=f4 \u0011k&>mpa\tp$<s$sS\u0019t\u0018|5~s<a\u0014jzq`8a\u000fw$%>%t\u001b)y\rL\u0012c(?#6a\u0014h$5-\u001eA\bp)4m$i\u001ee58l> \rv.'j4e\u000f$$#q?rS\u001d']a92f5d\u0018`a8m1c\tm78w) \ra38l4.".length();
                var1_4 = 25;
                var0_5 = -1;
lbl7:
                // 2 sources

                while (true) {
                    v0 = 21;
                    v1 = ++var0_5;
                    v2 = var2_2.substring(v1, v1 + var1_4);
                    v3 = -1;
                    break block9;
                    break;
                }
lbl13:
                // 1 sources

                while (true) {
                    var5[var3_1++] = PM2AbstractServlet.b(v0, PM2AbstractServlet.b(v2));
                    if ((var0_5 += var1_4) < var4_3) {
                        var1_4 = var2_2.charAt(var0_5);
                        ** continue;
                    }
                    var2_2 = "#Yi6uc=w\u0018b)0cz W\u001cs6<h:$\u000ea6ui;pYe6!f6h\u0010s-0ct}\u001ctk";
                    var4_3 = "#Yi6uc=w\u0018b)0cz W\u001cs6<h:$\u000ea6ui;pYe6!f6h\u0010s-0ct}\u001ctk".length();
                    var1_4 = 14;
                    var0_5 = -1;
lbl22:
                    // 2 sources

                    while (true) {
                        v0 = 17;
                        v4 = ++var0_5;
                        v2 = var2_2.substring(v4, v4 + var1_4);
                        v3 = 0;
                        break block9;
                        break;
                    }
                    break;
                }
lbl28:
                // 1 sources

                while (true) {
                    var5[var3_1++] = PM2AbstractServlet.b(v0, PM2AbstractServlet.b(v2));
                    if ((var0_5 += var1_4) < var4_3) {
                        var1_4 = var2_2.charAt(var0_5);
                        ** continue;
                    }
                    break block10;
                    break;
                }
            }
            switch (v3) {
                default: {
                    ** continue;
                }
                ** case 0:
lbl39:
                // 1 sources

                ** continue;
            }
        }
        PM2AbstractServlet.b = var5;
        PM2AbstractServlet.L7_SESSION_ID = PM2AbstractServlet.b[3];
    }

    private static char[] b(String string) {
        char[] cArray = string.toCharArray();
        if (cArray.length < 2) {
            cArray = cArray;
            cArray[0] = (char)(cArray[0] ^ 0x45);
        }
        return cArray;
    }

    /*
     * Handled impossible loop by duplicating code
     * Enabled aggressive block sorting
     */
    private static String b(int n, char[] cArray) {
        char[] cArray2;
        block11: {
            int n2;
            int n3;
            int n4;
            block10: {
                n4 = n;
                cArray2 = cArray;
                n3 = cArray.length;
                n2 = 0;
                if (!true) break block10;
                n3 = n3;
                if (n3 <= n2) break block11;
            }
            do {
                n4 = n4;
                cArray2 = cArray2;
                int n5 = n2;
                cArray2[n5] = (char)(cArray2[n5] ^ (n4 ^ (switch (n2 % 7) {
                    case 0 -> 21;
                    case 1 -> 104;
                    case 2 -> 17;
                    case 3 -> 84;
                    case 4 -> 68;
                    case 5 -> 22;
                    default -> 69;
                })));
                ++n2;
                n3 = n3;
            } while (n3 > n2);
        }
        return new String(cArray2).intern();
    }

    public static class PM2AuthContext {
        private LoginCredentials a;
        private String b;
        private AuthenticationResult c;
        private OAuth2VerifierResult d;
        private boolean e;
        private User f;

        public boolean hasCredentials() {
            return this.a != null || this.b != null;
        }

        public boolean isAuthenticated() {
            return this.e;
        }

        public AuthenticationResult getAuthResult() {
            return this.c;
        }

        public OAuth2VerifierResult getOAuthResult() {
            return this.d;
        }

        public User getAuthenticatedUser() {
            return this.f;
        }
    }

    public static final class PM2AuthType
    extends Enum<PM2AuthType> {
        public static final /* enum */ PM2AuthType BASIC;
        public static final /* enum */ PM2AuthType COOKIE;
        public static final /* enum */ PM2AuthType TOKEN;
        private static final /* synthetic */ PM2AuthType[] $VALUES;

        public static PM2AuthType[] values() {
            return (PM2AuthType[])$VALUES.clone();
        }

        public static PM2AuthType valueOf(String string) {
            return Enum.valueOf(PM2AuthType.class, string);
        }

        private static /* synthetic */ PM2AuthType[] $values() {
            return new PM2AuthType[]{BASIC, COOKIE, TOKEN};
        }

        /*
         * Enabled aggressive block sorting
         */
        static {
            String[] stringArray = new String[3];
            int n = 0;
            String string = "' -+k\u001b\u0005&.1)a\u00050 )%l";
            int n2 = "' -+k\u001b\u0005&.1)a\u00050 )%l".length();
            int n3 = 6;
            int n4 = -1;
            while (true) {
                int n5 = ++n4;
                stringArray[n++] = PM2AuthType.a(101, PM2AuthType.a(string.substring(n5, n5 + n3)));
                if ((n4 += n3) >= n2) {
                    BASIC = new PM2AuthType();
                    COOKIE = new PM2AuthType();
                    TOKEN = new PM2AuthType();
                    $VALUES = PM2AuthType.$values();
                    return;
                }
                n3 = string.charAt(n4);
            }
        }

        private static char[] a(String string) {
            char[] cArray = string.toCharArray();
            if (cArray.length < 2) {
                cArray = cArray;
                cArray[0] = (char)(cArray[0] ^ 0x7C);
            }
            return cArray;
        }

        /*
         * Handled impossible loop by duplicating code
         * Enabled aggressive block sorting
         */
        private static String a(int n, char[] cArray) {
            char[] cArray2;
            block11: {
                int n2;
                int n3;
                int n4;
                block10: {
                    n4 = n;
                    cArray2 = cArray;
                    n3 = cArray.length;
                    n2 = 0;
                    if (!true) break block10;
                    n3 = n3;
                    if (n3 <= n2) break block11;
                }
                do {
                    n4 = n4;
                    cArray2 = cArray2;
                    int n5 = n2;
                    cArray2[n5] = (char)(cArray2[n5] ^ (n4 ^ (switch (n2 % 7) {
                        case 0 -> 1;
                        case 1 -> 10;
                        case 2 -> 7;
                        case 3 -> 5;
                        case 4 -> 71;
                        case 5 -> 59;
                        default -> 124;
                    })));
                    ++n2;
                    n3 = n3;
                } while (n3 > n2);
            }
            return new String(cArray2).intern();
        }
    }
}
