Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restore hardcoded jwt #5

Merged
merged 3 commits into from
Feb 21, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,25 @@

<config-file target="res/xml/config.xml" parent="/*">
<feature name="ServerComm">
<param name="android-package" value="edu.berkeley.eecs.emission.cordova.comm.CommunicationHelper"/>
<param name="android-package" value="edu.berkeley.eecs.emission.cordova.comm.CommunicationHelperPlugin"/>
</feature>
</config-file>

<source-file src="src/android/CommunicationHelper.java" target-dir="src/edu/berkeley/eecs/emission/cordova/comm"/>
<source-file src="src/android/CommunicationHelperPlugin.java" target-dir="src/edu/berkeley/eecs/emission/cordova/comm"/>
</platform>

<platform name="ios">

<config-file target="config.xml" parent="/*">
<feature name="ServerComm">
<param name="ios-package" value="BEMCommunicationHelper" />
<param name="ios-package" value="BEMCommunicationHelperPlugin" />
</feature>
</config-file>

<header-file src="src/ios/BEMCommunicationHelper.h"/>
<source-file src="src/ios/BEMCommunicationHelper.m"/>
<header-file src="src/ios/BEMCommunicationHelperPlugin.h"/>
<source-file src="src/ios/BEMCommunicationHelperPlugin.m"/>
</platform>
</plugin>
50 changes: 50 additions & 0 deletions src/android/CommunicationHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,56 @@ public static String readResults(Context ctxt, String cacheControlProperty)
return rawHTML;
}

/*
* The other methods here take in a fullURL and return a string,
* respectively. The plugin interface passes in a relative URL and returns
* a JSONObject. For now, let us have this be consistent with the other
* calls here, and glue things together in the plugin.
*/
public static String pushGetJSON(Context ctxt, String fullURL,
JSONObject filledJsonObject)
throws IOException, JSONException {

// Initialize the message
String result = "";
HttpPost msg = new HttpPost(fullURL);
System.out.println("Posting data to " + msg.getURI());
msg.setHeader("Content-Type", "application/json");

// Fill in the object
final String userName = UserProfile.getInstance(ctxt).getUserEmail();
final String userToken = GoogleAccountManagerAuth.getServerToken(ctxt, userName);
filledJsonObject.put("user", userToken);
msg.setEntity(new StringEntity(filledJsonObject.toString()));

// Perform the operation
AndroidHttpClient connection = AndroidHttpClient.newInstance(ctxt.getString(R.string.app_name));
HttpResponse response = connection.execute(msg);
StatusLine statusLine = response.getStatusLine();
Log.i(ctxt, TAG, "Got response "+response+" with status "+statusLine);
int statusCode = statusLine.getStatusCode();

if(statusCode == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String currLine = null;
while ((currLine = in.readLine()) != null) {
builder.append(currLine+"\n");
}
result = builder.toString();
System.out.println("Result Summary JSON = "+
result.substring(0, Math.min(200, result.length())) + " length "+result.length());
Log.i(ctxt, TAG, "Result Summary JSON = "+
result.substring(0, Math.min(200, result.length())) + " length "+result.length());
in.close();
} else {
Log.e(ctxt, R.class.toString(),"Failed to get JSON object");
throw new IOException();
}
connection.close();
return result;
}

public static void pushJSON(Context ctxt, String fullURL, String userToken,
String objectLabel, Object jsonObjectOrArray)
throws IOException, JSONException {
Expand Down
35 changes: 35 additions & 0 deletions src/android/CommunicationHelperPlugin.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package edu.berkeley.eecs.emission.cordova.comm;

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import edu.berkeley.eecs.emission.cordova.comm.CommunicationHelper;
import edu.berkeley.eecs.emission.cordova.connectionsettings.ConnectionSettings;

public class CommunicationHelperPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
if (action.equals("pushGetJSON")) {
try {
Context ctxt = cordova.getActivity();
String relativeURL = data.getString(0);
JSONObject filledMessage = data.getJSONObject(1);

String commuteTrackerHost = ConnectionSettings.getConnectURL(ctxt);
String fullURL = commuteTrackerHost + relativeURL;

String resultString = CommunicationHelper.pushGetJSON(ctxt, fullURL, filledMessage);
callbackContext.success(new JSONObject(resultString));
} catch (Exception e) {
callbackContext.error("While pushing/getting from server "+e.getMessage());
}
return true;
} else {
return false;
}
}
}

1 change: 1 addition & 0 deletions src/ios/BEMCommunicationHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
+(void)phone_to_server:(NSArray*) entriesToPush completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;;

// Generic GET and POST methods
+(void)pushGetJSON:(NSDictionary*)toSend toURL:(NSString*)relativeURL completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
+(void)getData:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
-(id)initPost:(NSURL *)url data:(NSMutableDictionary*)jsonDict completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;

Expand Down
22 changes: 18 additions & 4 deletions src/ios/BEMCommunicationHelper.m
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,17 @@ +(void)phone_to_server:(NSArray *)entriesToPush completionHandler:(void (^)(NSDa
[executor execute];
}

+(void)pushGetJSON:(NSDictionary*)toSend toURL:(NSString*)relativeURL completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler {
NSMutableDictionary *toPush = [NSMutableDictionary dictionaryWithDictionary:toSend];

NSURL* kBaseURL = [[ConnectionSettings sharedInstance] getConnectUrl];
NSURL* absoluteURL = [NSURL URLWithString:relativeURL
relativeToURL:kBaseURL];

CommunicationHelper *executor = [[CommunicationHelper alloc] initPost:absoluteURL data:toPush completionHandler:completionHandler];
[executor execute];
}

+(void)getData:(NSURL*)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler {
NSURLSession *sharedSession = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [sharedSession dataTaskWithURL:url completionHandler:completionHandler];
Expand Down Expand Up @@ -149,7 +160,10 @@ -(void)execute {
GTMOAuth2Authentication* currAuth = [AuthCompletionHandler sharedInstance].currAuth;
if (currAuth == NULL) {
[self tryToAuthenticate:jsonData];
} else {
currAuth = [AuthCompletionHandler sharedInstance].currAuth;
}

if (currAuth != NULL) {
BOOL expired = ([currAuth.expirationDate compare:[NSDate date]] == NSOrderedAscending);
// The access token may not have expired, but the id token may not be available because the app has been restarted,
// so it is not in memory, and the ID token is not stored in the keychain. It is a real pain to store the ID token
Expand Down Expand Up @@ -215,7 +229,7 @@ -(void)execute {
}
}

- (void)tryToAuthenticate:(NSData*)jsonData {
- (BOOL)tryToAuthenticate:(NSData*)jsonData {
[LocalNotificationManager addNotification:[NSString stringWithFormat:
@"tryToAuthenticate called"] showUI:FALSE];
[[AuthCompletionHandler sharedInstance] registerFinishDelegate:self];
Expand All @@ -234,9 +248,8 @@ - (void)tryToAuthenticate:(NSData*)jsonData {
self.mCompletionHandler(jsonData, NULL, authError);
} else {
[LocalNotificationManager addNotification:[NSString stringWithFormat:
@"callback should be called, we will deal with it there"]
@"ready to authenticate, checking expiration"]
showUI:FALSE];
NSLog(@"callback should be called, we will deal with it there");
// So far, callback has not taken a long time...
// But callback may take a long time. In that case, we may want to return early.
// Also, callback will invoke mCompletionHandler in a separate thread, which won't
Expand All @@ -246,6 +259,7 @@ - (void)tryToAuthenticate:(NSData*)jsonData {
// So we will be called again, and won't have to invoke this call then
// mCompletionHandler(NULL, NULL, NULL);
}
return silentAuthResult;
}

- (void)postToHost {
Expand Down
7 changes: 7 additions & 0 deletions src/ios/BEMCommunicationHelperPlugin.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#import <Cordova/CDV.h>

@interface BEMCommunicationHelperPlugin: CDVPlugin <UINavigationControllerDelegate>

- (void) pushGetJSON:(CDVInvokedUrlCommand*)command;

@end
44 changes: 44 additions & 0 deletions src/ios/BEMCommunicationHelperPlugin.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#import "BEMCommunicationHelperPlugin.h"
#import "BEMCommunicationHelper.h"

@implementation BEMCommunicationHelperPlugin

- (void)pushGetJSON:(CDVInvokedUrlCommand *)command
{
NSString* callbackId = [command callbackId];

@try {
NSString* relativeURL = [[command arguments] objectAtIndex:0];
NSDictionary* filledMessage = [[command arguments] objectAtIndex:1];

[CommunicationHelper pushGetJSON:filledMessage toURL:relativeURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error != NULL) {
[self sendError:error callBackID:callbackId];
}
NSError *parseError;
NSDictionary *parsedResult = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error: &parseError];
if (parseError != NULL) {
[self sendError:parseError callBackID:callbackId];
}
CDVPluginResult* result = [CDVPluginResult
resultWithStatus:CDVCommandStatus_OK
messageAsDictionary:parsedResult];
[self.commandDelegate sendPluginResult:result callbackId:callbackId];
}];
}
@catch (NSException *exception) {
[self sendError:exception callBackID:callbackId];
}
}

- (void) sendError:(id) error callBackID:(NSString*)callbackID {
NSString* msg = [NSString stringWithFormat: @"During server call, error %@", error];
CDVPluginResult* result = [CDVPluginResult
resultWithStatus:CDVCommandStatus_ERROR
messageAsString:msg];
[self.commandDelegate sendPluginResult:result callbackId:callbackID];
}

@end
32 changes: 3 additions & 29 deletions www/servercomm.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,35 +21,9 @@ var ServerCommunication = {
* libraries from our javascript framework.
*/
pushGetJSON: function(relativeURL, messageFiller, successCallback, errorCallback) {
var request = new XMLHttpRequest();

request.onreadystatechange = function() {
if(request.readyState == request.DONE) {
if (request.status == 200) {
var resultObj = JSON.parse(request.responseText);
successCallback(resultObj);
} else {
errorCallback(request.statusText);
}
} else {
console.log("during HTTP post, state "+request.readyState);
}
};
window.cordova.plugins.BEMConnectionSettings.getSettings(function(settings) {
var fullURL = settings.connectURL + relativeURL;
window.cordova.plugins.BEMJWTAuth.getJWT(function(token) {
message = {};
message.user = token;
messageFiller(message);
request.open("POST", fullURL, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(JSON.stringify(message));
}, function(error) {
errorCallback(error);
})
}, function(error) {
errorCallback(error);
});
filledMessage = {};
messageFiller(filledMessage);
exec(successCallback, errorCallback, "ServerComm", "pushGetJSON", [relativeURL, filledMessage]);
},
pushJSON: function(relativeUrl, objectLabel, objectJSON, successCallback, errorCallback) {
var msgFiller = function(message) {
Expand Down