Commit 7bbbabfd authored by Andy Trevorah's avatar Andy Trevorah
Browse files

added oauth (broken)

parent 258997d2
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" assert-keyword="true" jdk-15="true" project-jdk-name="JDK" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
......
......@@ -78,10 +78,11 @@
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
</content>
<orderEntry type="jdk" jdkName="Android API 20 Platform" jdkType="Android SDK" />
<orderEntry type="jdk" jdkName="Android API 19 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" exported="" name="support-annotations-20.0.0" level="project" />
<orderEntry type="library" exported="" name="support-v4-20.0.0" level="project" />
<orderEntry type="library" exported="" name="scribe-1.3.5" level="project" />
</component>
</module>
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
compileSdkVersion 19
buildToolsVersion "21.1.0"
defaultConfig {
applicationId "im.gitter.gitter"
minSdkVersion 15
targetSdkVersion 20
minSdkVersion 19
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
......@@ -19,7 +19,13 @@ android {
}
}
repositories {
mavenCentral()
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:20.0.0'
compile 'org.scribe:scribe:1.3.5'
// compile "com.google.android.gms:play-services:3.1.+"
}
......@@ -2,13 +2,16 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="im.gitter.gitter" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Chat"
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
......
......@@ -20,8 +20,8 @@ import android.widget.TextView;
public class Chat extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
// implements NavigationDrawerFragment.NavigationDrawerCallbacks {
{
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
......@@ -47,14 +47,14 @@ public class Chat extends Activity
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
// @Override
// public void onNavigationDrawerItemSelected(int position) {
// // update the main content by replacing fragments
// FragmentManager fragmentManager = getFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
// .commit();
// }
public void onSectionAttached(int number) {
switch (number) {
......@@ -143,4 +143,6 @@ public class Chat extends Activity
}
}
}
package im.gitter.gitter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class GetAccessToken {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public GetAccessToken() {
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
Map<String, String> mapn;
DefaultHttpClient httpClient;
HttpPost httpPost;
public JSONObject gettoken(String address,String token,String client_id,String client_secret,String redirect_uri,String grant_type) {
// Making HTTP request
try {
// DefaultHttpClient
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(address);
params.add(new BasicNameValuePair("code", token));
params.add(new BasicNameValuePair("client_id", client_id));
params.add(new BasicNameValuePair("client_secret", client_secret));
params.add(new BasicNameValuePair("redirect_uri", redirect_uri));
params.add(new BasicNameValuePair("grant_type", grant_type));
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSONStr", json);
} catch (Exception e) {
e.getMessage();
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Parse the String to a JSON Object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return JSON String
return jObj;
}
}
package im.gitter.gitter;
import org.json.JSONException;
import org.json.JSONObject;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.Api;
import org.scribe.builder.api.DefaultApi20;
import org.scribe.model.OAuthConfig;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import org.scribe.utils.OAuthEncoder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URI;
import im.gitter.gitter.auth.OAuthServiceFactory;
import im.gitter.gitter.auth.OAuthTokenExchangeService;
public class MainActivity extends Activity {
private static String CLIENT_ID = "842537427973-a381vrch0t5cgrgvtr02lik77a5bc8o7.apps.googleusercontent.com";
//Use your own client id
private static String CLIENT_SECRET ="EEOeMFHQpLtaHDU4Rr8k-l3N";
//Use your own client secret
private static String REDIRECT_URI="http://localhost";
private static String GRANT_TYPE="authorization_code";
private static String TOKEN_URL ="https://accounts.google.com/o/oauth2/token";
private static String OAUTH_URL ="https:/gitter.im/login";
private static String OAUTH_SCOPE="https://www.googleapis.com/auth/urlshortener";
//Change the Scope as you need
WebView web;
Button auth;
SharedPreferences pref;
TextView Access;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final OAuthService service = new OAuthServiceFactory().create();
// Token requestToken = service.getRequestToken();
String authUrl = service.getAuthorizationUrl(null);
Log.d("auth url", authUrl);
setContentView(R.layout.auth_dialog);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
Access =(TextView)findViewById(R.id.Access);
// // TODO Auto-generated method stub
// auth_dialog = new Dialog(MainActivity.this);
// auth_dialog.setContentView(R.layout.auth_dialog);
Log.d("", "hey there");
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
// cookieManager.setAcceptCookie(false);
web = (WebView)this.findViewById(R.id.webv);
web.clearCache(true);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(authUrl);
web.setWebViewClient(new WebViewClient() {
boolean authComplete = false;
Intent resultIntent = new Intent();
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
Log.d("started", url);
if (url.contains("?code=")) {
Uri uri = Uri.parse(url);
authCode = uri.getQueryParameter("code");
Log.i("", "CODE: " + authCode);
authComplete = true;
resultIntent.putExtra("code", authCode);
MainActivity.this.setResult(Activity.RESULT_OK, resultIntent);
setResult(Activity.RESULT_CANCELED, resultIntent);
SharedPreferences.Editor edit = pref.edit();
edit.putString("Code", authCode);
edit.commit();
x(authCode);
// mServiceIntent.setData(Uri.parse(dataUrl));
// auth_dialog.dismiss();
// new TokenGet().execute();
// Verifier verifier = new Verifier(authCode);
// Token accessToken = service.getAccessToken(null, verifier);
// service.getAccessToken()
Toast.makeText(getApplicationContext(),"Authorization Code is: " +authCode + ", token is: " + accessToken, Toast.LENGTH_LONG).show();
}else if(url.contains("error=access_denied")){
Log.i("", "ACCESS_DENIED_HERE");
resultIntent.putExtra("code", authCode);
authComplete = true;
setResult(Activity.RESULT_CANCELED, resultIntent);
Toast.makeText(getApplicationContext(), "Error Occured", Toast.LENGTH_SHORT).show();
// auth_dialog.dismiss();
}
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
Log.d("overr", url);
return false;
}
String authCode;
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d("url", url);
}
});
// auth_dialog.show();
// auth_dialog.setTitle("Authorize Learn2Crack");
// auth_dialog.setCancelable(true);
}
private void x(String token) {
Intent intent = new Intent("custom-event-name");
intent.putExtra("request-token", token);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private class TokenGet extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String Code;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Contacting Google ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
Code = pref.getString("Code", "");
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
GetAccessToken jParser = new GetAccessToken();
JSONObject json = jParser.gettoken(TOKEN_URL,Code,CLIENT_ID,CLIENT_SECRET,REDIRECT_URI,GRANT_TYPE);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
if (json != null){
try {
String tok = json.getString("access_token");
String expire = json.getString("expires_in");
String refresh = json.getString("refresh_token");
Log.d("Token Access", tok);
Log.d("Expire", expire);
Log.d("Refresh", refresh);
auth.setText("Authenticated");
Access.setText("Access Token:"+tok+"nExpires:"+expire+"nRefresh Token:"+refresh);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}
}
}
\ No newline at end of file
package im.gitter.gitter.auth;
import org.scribe.builder.api.DefaultApi20;
import org.scribe.model.OAuthConfig;
public class GitterAuthApi extends DefaultApi20 {
@Override
public String getAccessTokenEndpoint() {
return "https://gitter.im/login/oauth/token";
}
@Override
public String getAuthorizationUrl(OAuthConfig config) {
// Log.d("config", config.toString());config.
// return "https://gitter.im/login/oauth/authorize?" +
// "client_id=" + config.getApiKey();
//
return "https://gitter.im/login/oauth/authorize?client_id=ios-prod-dev&redirect_uri=https%3A%2F%2Fgitter.im%2Flogin%2Foauth%2Fcallback&response_type=code&scope=https%3A%2F%2Fgitter.im%2Flogin%2Foauth%2Fcallback";
// String authorizeUrl = "https://gitter.im/login/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=%s&scope=%s";
// return String.format(authorizeUrl, config.getApiKey(), OAuthEncoder.encode(config.getCallback()), "code", OAuthEncoder.encode(config.getCallback()));
// return "https://gitter.im/login/oauth/authorize";
}
}
package im.gitter.gitter.auth;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.DefaultApi20;
import org.scribe.model.OAuthConfig;
import org.scribe.oauth.OAuthService;
/**
* Created by trevorah on 04/11/14.
*/
public class OAuthServiceFactory {
public OAuthService create() {
final OAuthService service = new ServiceBuilder()
.provider(new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return "https://gitter.im/login/oauth/token";
}
@Override
public String getAuthorizationUrl(OAuthConfig config) {
// Log.d("config", config.toString());config.
// return "https://gitter.im/login/oauth/authorize?" +
// "client_id=" + config.getApiKey();
//
return "https://gitter.im/login/oauth/authorize?client_id=ios-prod-dev&redirect_uri=https%3A%2F%2Fgitter.im%2Flogin%2Foauth%2Fcallback&response_type=code&scope=https%3A%2F%2Fgitter.im%2Flogin%2Foauth%2Fcallback";
// String authorizeUrl = "https://gitter.im/login/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=%s&scope=%s";
// return String.format(authorizeUrl, config.getApiKey(), OAuthEncoder.encode(config.getCallback()), "code", OAuthEncoder.encode(config.getCallback()));
// return "https://gitter.im/login/oauth/authorize";
}
})
.apiKey("ios-prod")
.apiSecret("***REMOVED***")
.build();
return service;
}
}
package im.gitter.gitter.auth;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
public class OAuthTokenExchangeService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public OAuthTokenExchangeService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
String requestToken = intent.getDataString();
OAuthService service = new OAuthServiceFactory().create();
Verifier verifier = new Verifier(requestToken);
// blocking call that makes a GET request
Token accessTokenObj = service.getAccessToken(null, verifier);
String accessToken = accessTokenObj.getToken();
Intent localIntent = new Intent("hey");
localIntent.putExtra("token", accessToken);
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="25sp"
android:text="Google OAuth2 WebView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/auth"
android:text="Sign in with Google" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/Access"
android:autoLink="all"
android:textIsSelectable="true"
android:layout_gravity="center"
android:textSize="10sp"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webv"/>
</LinearLayout>
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment