package com.monkeyk.os.web.controller;

import com.monkeyk.os.web.WebUtils;
import com.monkeyk.os.web.oauth.OAuthAuthxRequest;
import com.monkeyk.os.web.oauth.authorize.CodeAuthorizeHandler;
import com.monkeyk.os.web.oauth.authorize.TokenAuthorizeHandler;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * URL: oauth/authorize
 *
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("oauth/")
public class OauthAuthorizeController {


    private static final Logger LOG = LoggerFactory.getLogger(OauthAuthorizeController.class);


    /**
     * Must handle the grant_type as follow:
     * grant_type="authorization_code" -> response_type="code"
     * ?response_type=code&scope=read,write&client_id=[client_id]&redirect_uri=[redirect_uri]&state=[state]
     * <p/>
     * grant_type="implicit"   -> response_type="token"
     * ?response_type=token&scope=read,write&client_id=[client_id]&client_secret=[client_secret]&redirect_uri=[redirect_uri]
     * <p/>
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping("authorize")
    public void authorize(HttpServletRequest request, HttpServletResponse response) throws Exception {

        try {
            OAuthAuthxRequest oauthRequest = new OAuthAuthxRequest(request);

            //If it is auth used
            if (checkAndHandleAuthHeaderUsed(response, oauthRequest)) {
                return;
            }

            if (oauthRequest.isCode()) {
                CodeAuthorizeHandler codeAuthorizeHandler = new CodeAuthorizeHandler(oauthRequest, response);
                LOG.debug("Go to  response_type = 'code' handler: {}", codeAuthorizeHandler);
                codeAuthorizeHandler.handle();

            } else if (oauthRequest.isToken()) {
                TokenAuthorizeHandler tokenAuthorizeHandler = new TokenAuthorizeHandler(oauthRequest, response);
                LOG.debug("Go to response_type = 'token' handler: {}", tokenAuthorizeHandler);
                tokenAuthorizeHandler.handle();

            } else {
                unsupportResponseType(oauthRequest, response);
            }

        } catch (OAuthProblemException e) {
            //exception
            OAuthResponse oAuthResponse = OAuthASResponse
                    .errorResponse(HttpServletResponse.SC_FOUND)
                    .location(e.getRedirectUri())
                    .error(e)
                    .buildJSONMessage();
            WebUtils.writeOAuthJsonResponse(response, oAuthResponse);
        }


    }

    private boolean checkAndHandleAuthHeaderUsed(HttpServletResponse response, OAuthAuthxRequest oauthRequest) throws OAuthSystemException {
        if (oauthRequest.isClientAuthHeaderUsed()) {
            OAuthResponse oAuthResponse = OAuthResponse.status(HttpServletResponse.SC_FOUND)
                    .location(oauthRequest.getRedirectURI())
                    .setParam("client_id", oauthRequest.getClientId())
                    .buildJSONMessage();

            LOG.debug("Auth header used by client: {}, return directly", oauthRequest.getClientId());
            WebUtils.writeOAuthJsonResponse(response, oAuthResponse);
            return true;
        }
        return false;
    }

    private void unsupportResponseType(OAuthAuthxRequest oauthRequest, HttpServletResponse response) throws OAuthSystemException {
        final String responseType = oauthRequest.getResponseType();
        LOG.debug("Unsupport response_type '{}' by client_id '{}'", responseType, oauthRequest.getClientId());

        OAuthResponse oAuthResponse = OAuthResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                .setError(OAuthError.CodeResponse.UNSUPPORTED_RESPONSE_TYPE)
                .setErrorDescription("Unsupport response_type '" + responseType + "'")
                .buildJSONMessage();
        WebUtils.writeOAuthJsonResponse(response, oAuthResponse);
    }


    @RequestMapping(value = "oauth_login")
    public String oauthLogin() {
        return "oauth/oauth_login";
    }


    @RequestMapping(value = "oauth_approval")
    public String oauthApproval() {
        return "oauth/oauth_approval";
    }


}
@@ -1828,151 +1828,8 @@
 );%0A%0A
-            //If it is auth used%0A            if (checkAndHandleAuthHeaderUsed(response, oauthRequest)) %7B%0A                return;%0A            %7D%0A
 %0A   
@@ -2916,32 +2916,34 @@
      %7D%0A%0A%0A    %7D%0A%0A
+//
     private bool
@@ -3059,32 +3059,34 @@
 stemException %7B%0A
+//
         if (oaut
@@ -3118,24 +3118,26 @@
 erUsed()) %7B%0A
+//
             
@@ -3209,32 +3209,34 @@
 ponse.SC_FOUND)%0A
+//
                 
@@ -3276,24 +3276,26 @@
 irectURI())%0A
+//
             
@@ -3349,24 +3349,26 @@
 ClientId())%0A
+//
             
@@ -3392,25 +3392,29 @@
 NMessage();%0A
-%0A
+//%0A//
             
@@ -3503,16 +3503,18 @@
 tId());%0A
+//
         
@@ -3567,32 +3567,34 @@
 oAuthResponse);%0A
+//
             retu
@@ -3602,16 +3602,18 @@
 n true;%0A
+//
         
@@ -3614,16 +3614,18 @@
       %7D%0A
+//
         
@@ -3638,16 +3638,18 @@
  false;%0A
+//
     %7D%0A%0A 

Comment BASIC auth