Skip to content

Commit

Permalink
Merge pull request #973 from AmaliMatharaarachchi/improve-code
Browse files Browse the repository at this point in the history
Rename micro-gw-default.conf template and Refactor code
  • Loading branch information
Rajith90 authored Feb 7, 2020
2 parents ac905e1 + 0686a7f commit 33666ef
Show file tree
Hide file tree
Showing 19 changed files with 68 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ public void setApiResponseInterceptor(String responseInterceptor) {

public void setSecuritySchemas(String schemas) {
//update the Resource auth providers property only if there is no security scheme provided during instantiation
if (this.authProviders.size() < 1) {
if (this.authProviders.isEmpty()) {
authProviders = OpenAPICodegenUtils.getAuthProviders(schemas);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -981,7 +981,7 @@ public static List<String> getAuthProviders(String schemas) {
}
}
}
if (authProviders.size() < 1) {
if (authProviders.isEmpty()) {
authProviders.add(APISecurity.oauth2.name());
authProviders.add(APISecurity.jwt.name());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import ballerina/http;
import ballerina/reflect;
import wso2/gateway;
import ballerina/log;

@http:ServiceConfig {
basePath:"/authorize",
Expand Down Expand Up @@ -36,15 +35,15 @@ service authorizeService on tokenListenerEndpoint, apiSecureListener {
if(response is http:Response) {
forwardedResponse = response;
} else {
log:printError("Error occurred while invoking the authorize endpoint", err = response);
gateway:printError(gateway:TOKEN_SERVICE, "Error occurred while invoking the authorize endpoint", response);
http:Response errorResponse = new;
json errMsg = { "error": "error occurred while invoking the authorize endpoint" };
errorResponse.setJsonPayload(errMsg);
forwardedResponse = errorResponse;
}
var result = caller->respond(forwardedResponse);
if (result is error) {
log:printError("Error when responding during the authorize endpoint request", err = result);
gateway:printError(gateway:TOKEN_SERVICE, "Error when responding during the authorize endpoint request", result);
}

}
Expand Down Expand Up @@ -83,15 +82,15 @@ service revokeService on tokenListenerEndpoint, apiSecureListener {
if(response is http:Response) {
forwardedResponse = response;
} else {
log:printError("Error occurred while invoking the revoke endpoint", err = response);
gateway:printError(gateway:TOKEN_SERVICE, "Error occurred while invoking the revoke endpoint", response);
http:Response errorResponse = new;
json errMsg = { "error": "error occurred while invoking the revoke endpoint" };
errorResponse.setJsonPayload(errMsg);
forwardedResponse = errorResponse;
}
var result = caller->respond(forwardedResponse);
if (result is error) {
log:printError("Error when responding during the revoke endpoint request", err = result);
gateway:printError(gateway:TOKEN_SERVICE, "Error when responding during the revoke endpoint request", result);
}

}
Expand Down Expand Up @@ -130,15 +129,15 @@ service tokenService on tokenListenerEndpoint, apiSecureListener {
if(response is http:Response) {
forwardedResponse = response;
} else {
log:printError("Error occurred while invoking the token endpoint", err = response);
gateway:printError(gateway:TOKEN_SERVICE, "Error occurred while invoking the token endpoint", response);
http:Response errorResponse = new;
json errMsg = { "error": "error occurred while invoking the token endpoint" };
errorResponse.setJsonPayload(errMsg);
forwardedResponse = errorResponse;
}
var result = caller->respond(forwardedResponse);
if (result is error) {
log:printError("Error when responding during the token endpoint request", err = result);
gateway:printError(gateway:TOKEN_SERVICE, "Error when responding during the token endpoint request", result);
}
}
}
Expand Down Expand Up @@ -173,12 +172,10 @@ service apiKeyService on apiSecureListener {
if (apikey is string) {
error? result = caller->respond(apikey);
if (result is error) {
gateway:printError(gateway:TOKEN_SERVICE, "Error when responding during the token endpoint request");
gateway:printFullError(gateway:TOKEN_SERVICE, result);
gateway:printError(gateway:TOKEN_SERVICE, "Error when responding during the token endpoint request", result);
}
} else {
gateway:printError(gateway:TOKEN_SERVICE, "Error while generating API Key token");
gateway:printFullError(gateway:TOKEN_SERVICE, apikey);
gateway:printError(gateway:TOKEN_SERVICE, "Error while generating API Key token", apikey);
http:Response errorResponse = new;
json errMsg = { "error": "error occurred while generating API Key token" };
errorResponse.setJsonPayload(errMsg);
Expand Down Expand Up @@ -220,15 +217,15 @@ service userInfoService on tokenListenerEndpoint, apiSecureListener {
if(response is http:Response) {
forwardedResponse = response;
} else {
log:printError("Error occurred while invoking the userinfo endpoint", err = response);
gateway:printError(gateway:TOKEN_SERVICE, "Error occurred while invoking the userinfo endpoint", response);
http:Response errorResponse = new;
json errMsg = { "error": "error occurred while invoking the user info endpoint" };
errorResponse.setJsonPayload(errMsg);
forwardedResponse = errorResponse;
}
var result = caller->respond(forwardedResponse);
if (result is error) {
log:printError("Error when responding during the user info endpoint request", err = result);
gateway:printError(gateway:TOKEN_SERVICE, "Error when responding during the user info endpoint request", result);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ function sendFileRotatingEvent() returns error? {
if (result is string) {
printInfo(KEY_ROTATE_TASK, "File rotated successfully.");
} else {
printFullError(KEY_ROTATE_TASK, result);
printError(KEY_ROTATE_TASK, "File rotation failed.", result);
}
return;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function multipartSender(string location, string file, string username, s
string errorMessage = "Error occurred while sending multipart request: SC 500";
response.setPayload(errorMessage);
response.statusCode = 500;
printFullError(KEY_UPLOAD_TASK, returnResponse);
printError(KEY_UPLOAD_TASK, errorMessage, returnResponse);
return response;
} else {
var responseString = returnResponse.getTextPayload();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,11 @@ public type AnalyticsRequestFilter object {
eventStream.publish(eventDTO);
printDebug(KEY_ANALYTICS_FILTER, "File upload throttle stream data published." + eventDTO.streamId);
} else {
printError(KEY_ANALYTICS_FILTER, "Error while creating throttle analytics event");
printFullError(KEY_ANALYTICS_FILTER, eventDTO);
printError(KEY_ANALYTICS_FILTER, "Error while creating throttle analytics event", eventDTO);
}
}
} else {
printError(KEY_ANALYTICS_FILTER, "Error while populating throttle analytics event data");
printFullError(KEY_ANALYTICS_FILTER, throttleAnalyticsEventDTO);
printError(KEY_ANALYTICS_FILTER, "Error while populating throttle analytics event data", throttleAnalyticsEventDTO);
}
} else {
if (!filterFailed) {
Expand All @@ -84,8 +82,7 @@ function doFilterRequest(http:Request request, http:FilterContext context) {
printDebug(KEY_ANALYTICS_FILTER, "doFilterRequest Mehtod called");
error? result = trap setRequestAttributesToContext(request, context);
if (result is error) {
printError(KEY_ANALYTICS_FILTER, "Error while setting analytics data in request path");
printFullError(KEY_ANALYTICS_FILTER, result);
printError(KEY_ANALYTICS_FILTER, "Error while setting analytics data in request path", result);
}
}

Expand All @@ -107,12 +104,10 @@ function doFilterFault(http:FilterContext context, string errorMessage) {
eventStream.publish(eventDTO);
}
} else {
printError(KEY_ANALYTICS_FILTER, "Error while genaratting analytics data for fault event");
printFullError(KEY_ANALYTICS_FILTER, eventDTO);
printError(KEY_ANALYTICS_FILTER, "Error while genaratting analytics data for fault event", eventDTO);
}
} else {
printError(KEY_ANALYTICS_FILTER, "Error while populating analytics fault event data");
printFullError(KEY_ANALYTICS_FILTER, faultDTO);
printError(KEY_ANALYTICS_FILTER, "Error while populating analytics fault event data", faultDTO);
}
}

Expand All @@ -136,12 +131,10 @@ function doFilterResponseData(http:Response response, http:FilterContext context
eventStream.publish(event);
}
} else {
printError(KEY_ANALYTICS_FILTER, "Error while genarating analytics data event");
printFullError(KEY_ANALYTICS_FILTER, event);
printError(KEY_ANALYTICS_FILTER, "Error while genarating analytics data event", event);
}
} else {
printError(KEY_ANALYTICS_FILTER, "Error while publishing analytics data");
printFullError(KEY_ANALYTICS_FILTER, requestResponseExecutionDTO);
printError(KEY_ANALYTICS_FILTER, "Error while publishing analytics data", requestResponseExecutionDTO);
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ returns boolean {
setAPIKeyAuth(inName, name);
authHeader = AUTH_SCHEME_API_KEY;
break;
} else if (stringutils:equalsIgnoreCase(QUERY, inName) && request.getQueryParamValue(name) is string) {
} else if (stringutils:equalsIgnoreCase(QUERY, inName)
&& request.getQueryParamValue(name) is string) {
printDebug(KEY_PRE_AUTHN_FILTER, "Request has apikey query : " + name);
isAPIKeyAuth = true;
setAPIKeyAuth(inName, name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ function doSubscriptionFilterRequest(http:Caller caller, http:Request request,
sendErrorResponse(caller, request, <@untainted>filterContext);
return false;
}
subscriptionValidated = handleSubscribedAPIs(jwtToken, payload, subscribedAPIList, subscriptionValEnabled);
subscriptionValidated = handleSubscribedAPIs(jwtToken, payload, subscribedAPIList,
subscriptionValEnabled);
if (subscriptionValidated || !subscriptionValEnabled) {
printDebug(KEY_SUBSCRIPTION_FILTER, "Subscriptions validated.");
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ public type APIKeyHandlerWrapper object {
int startingTime = getCurrentTime();
map<string> | () gaugeTags = gaugeTagDetails_authn(req, FILTER_AUTHENTICATION);
observe:Gauge | () localGauge = initializeGauge(PER_REQ_DURATION, REQ_FLTER_DURATION, gaugeTags);
observe:Gauge | () localGaugeTotal = initializeGauge(REQ_DURATION_TOTAL, FILTER_TOTAL_DURATION, {"Category": FILTER_AUTHENTICATION});
observe:Gauge | () localGaugeTotal =
initializeGauge(REQ_DURATION_TOTAL, FILTER_TOTAL_DURATION, {"Category": FILTER_AUTHENTICATION});
boolean | http:AuthenticationError result = self.apiKeyHandler.process(req);
float | () latency = setGaugeDuration(startingTime);
updateGauge(localGauge, latency);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ public function getAuthHandlers() returns http:InboundAuthHandler[] {
http:BearerAuthHandler bearerAuthOutboundHandler = new (oauth2Provider);
auth = {authHandler: bearerAuthOutboundHandler};
} else {
printFullError(KEY_GW_LISTNER, oauth2Provider);
printError(KEY_GW_LISTNER, "Failed to get oauth2 outbound provider", oauth2Provider);
}
} else {
printWarn(KEY_GW_LISTNER, "Key validation service security confogurations not enabled.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,32 +75,27 @@ public function startSubscriberService() returns @tainted jms:MessageConsumer |

});
if (connection is error) {
printError(KEY_THROTTLE_UTIL, "Error while creating the jms connection.");
printFullError(KEY_THROTTLE_UTIL, connection);
printError(KEY_THROTTLE_UTIL, "Error while creating the jms connection.", connection);
return connection;
} else {
jms:Session | error session = trap connection->createSession({acknowledgementMode: "AUTO_ACKNOWLEDGE"});
if (session is error) {
printError(KEY_THROTTLE_UTIL, "Error while creating the jms session.");
printFullError(KEY_THROTTLE_UTIL, session);
printError(KEY_THROTTLE_UTIL, "Error while creating the jms session.", session);
return session;
} else {
jms:Destination dest = check session->createTopic("throttleData");
jms:MessageConsumer | error subscriberEndpoint = trap session->createDurableSubscriber(dest, "sub-1");
if (subscriberEndpoint is error) {
printError(KEY_THROTTLE_UTIL, "Error while creating the jms subscriber.");
printFullError(KEY_THROTTLE_UTIL, subscriberEndpoint);
printError(KEY_THROTTLE_UTIL, "Error while creating the jms subscriber.", subscriberEndpoint);
} else {
var attachResult = subscriberEndpoint.__attach(messageServ);
if (attachResult is error) {
printError(KEY_THROTTLE_UTIL, "Message consumer hasn't been attached to the service.");
printFullError(KEY_THROTTLE_UTIL, attachResult);
printError(KEY_THROTTLE_UTIL, "Message consumer hasn't been attached to the service.", attachResult);
return attachResult;
}
var startResult = subscriberEndpoint.__start();
if (startResult is error) {
printError(KEY_THROTTLE_UTIL, "Starting the task is failed.");
printFullError(KEY_THROTTLE_UTIL, startResult);
printError(KEY_THROTTLE_UTIL, "Starting the task is failed.", startResult);
return startResult;
}
printDebug(KEY_THROTTLE_UTIL, "Successfully created jms connection");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,16 @@ public function generateAPIKey(http:Request req) returns string | error {

public function getExpiryTime(http:Request req) returns @tainted (int) {
var payload = req.getJsonPayload();
int expiryTime = getConfigIntValue(API_KEY_ISSUER_TOKEN_CONFIG, API_KEY_VALIDITY_TIME, DEFAULT_API_KEY_VALIDITY_TIME);
int expiryTime =
getConfigIntValue(API_KEY_ISSUER_TOKEN_CONFIG, API_KEY_VALIDITY_TIME, DEFAULT_API_KEY_VALIDITY_TIME);
printDebug(API_KEY_UTIL, "Validity Period in config: " + expiryTime.toString());

if (payload is json) {
map<json> payloadMap = <map<json>>payload;
if (payloadMap.hasKey(API_KEY_VALIDITY_TIME)) {
var expiryTimefromPayload = ints:fromString(payloadMap[API_KEY_VALIDITY_TIME].toString());
if (expiryTimefromPayload is int && expiryTimefromPayload > 0 && (expiryTime < 0 || expiryTime > expiryTimefromPayload)) {
if (expiryTimefromPayload is int && expiryTimefromPayload > 0
&& (expiryTime < 0 || expiryTime > expiryTimefromPayload)) {
expiryTime = expiryTimefromPayload;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
import ballerina/jwt;
import ballerina/runtime;

public function handleSubscribedAPIs(string apiKeyToken, jwt:JwtPayload payload, json[] subscribedAPIList, boolean validateAllowedAPIs) returns boolean {
public function handleSubscribedAPIs(string apiKeyToken, jwt:JwtPayload payload, json[] subscribedAPIList,
boolean validateAllowedAPIs) returns boolean {

runtime:InvocationContext invocationContext = runtime:getInvocationContext();
//invocation context
Expand Down Expand Up @@ -81,7 +82,8 @@ public function handleSubscribedAPIs(string apiKeyToken, jwt:JwtPayload payload,
var subscription = subscribedAPIList[index];
if (subscription.name.toString() == apiName && subscription.'version.toString() == apiVersion) {
authenticationContext.authenticated = true;
printDebug(JWT_UTIL, "Found a matching allowed api with name:" + subscription.name.toString() + " version:" + subscription.'version.toString());
printDebug(JWT_UTIL, "Found a matching allowed api with name:" + subscription.name.toString()
+ " version:" + subscription.'version.toString());

//set throttling attribs if present
if (subscription.subscriptionTier is json) {
Expand All @@ -97,7 +99,8 @@ public function handleSubscribedAPIs(string apiKeyToken, jwt:JwtPayload payload,
authenticationContext.apiPublisher = subscription.publisher.toString();
}
if (subscription.subscriberTenantDomain is json) {
printDebug(JWT_UTIL, "set subscriberTenantDomain to " + subscription.subscriberTenantDomain.toString());
printDebug(JWT_UTIL, "set subscriberTenantDomain to "
+ subscription.subscriberTenantDomain.toString());
authenticationContext.subscriberTenantDomain = subscription.subscriberTenantDomain.toString();
}
invocationContext.attributes[AUTHENTICATION_CONTEXT] = authenticationContext;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@
// printDebug(KEY_TOKEN_REVOCATION_ETCD_UTIL, msg.reason());
// }
// } else {
// printDebug(KEY_TOKEN_REVOCATION_ETCD_UTIL, "Error object obtained");
// printFullError(KEY_TOKEN_REVOCATION_ETCD_UTIL, response);
// printError(KEY_TOKEN_REVOCATION_ETCD_UTIL, "Error object obtained", response);
// }
// return finalResponse;
// }
Expand Down
Loading

0 comments on commit 33666ef

Please sign in to comment.