Commit fb23a1b8 authored by Sajal Narang's avatar Sajal Narang Committed by GitHub

Merge pull request #26 from yvsriram/master

Added code for receiving gcm id/token and managing sessions based on logged in status
parents 176a3754 c6e1a7de
......@@ -3,8 +3,6 @@
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/IITB-App.iml" filepath="$PROJECT_DIR$/IITB-App.iml" />
<module fileurl="file://$PROJECT_DIR$/IITBApp.iml" filepath="$PROJECT_DIR$/IITBApp.iml" />
<module fileurl="file://D:\IITB-App\IITBApp.iml" filepath="D:\IITB-App\IITBApp.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
</modules>
</component>
......
......@@ -28,6 +28,7 @@ ext {
appAuthVersion = '0.2.0'
retrofitVersion = '2.1.0'
okhttpVersion = '3.4.1'
}
dependencies {
......@@ -42,9 +43,11 @@ dependencies {
compile "com.google.android.gms:play-services-maps:${playServicesVersion}"
compile "com.android.support:support-v4:${supportLibVersion}"
compile "com.jakewharton:butterknife:${butterKnifeVersion}"
compile "com.google.android.gms:play-services-gcm:11.0.2"
annotationProcessor "com.jakewharton:butterknife-compiler:${butterKnifeVersion}"
compile "com.squareup.retrofit2:retrofit:${retrofitVersion}"
compile "com.squareup.retrofit2:converter-gson:${retrofitVersion}"
compile "com.squareup.okhttp3:okhttp:${okhttpVersion}"
compile "com.squareup.okhttp3:logging-interceptor:${okhttpVersion}"
}
apply plugin: 'com.google.gms.google-services'
{
"project_info": {
"project_number": "306601329049",
"firebase_url": "https://iitb-app-5c0aa.firebaseio.com",
"project_id": "iitb-app-5c0aa",
"storage_bucket": "iitb-app-5c0aa.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:306601329049:android:950a72a311331b9c",
"android_client_info": {
"package_name": "in.ac.iitb.gymkhana.iitbapp"
}
},
"oauth_client": [
{
"client_id": "306601329049-6v597vrdv0nbi15ehpehq8hiaek8unqp.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyC1oThCMZN3JMnK6MUTJRjkp47q1K_gnTA"
}
],
"services": {
"analytics_service": {
"status": 1
},
"appinvite_service": {
"status": 1,
"other_platform_oauth_client": []
},
"ads_service": {
"status": 2
}
}
}
],
"configuration_version": "1"
}
\ No newline at end of file
......@@ -4,6 +4,8 @@
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
......@@ -23,6 +25,7 @@
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:launchMode="singleTask"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
......@@ -30,17 +33,19 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity">
<activity
android:name=".LoginActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="HANDLE_AUTHORIZATION_RESPONSE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<!-- <intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
&lt;!&ndash;<category android:name="android.intent.category.LAUNCHER" />&ndash;&gt;
</intent-filter>-->
</activity>
<activity android:name="net.openid.appauth.RedirectUriReceiverActivity">
......@@ -56,6 +61,35 @@
</intent-filter>
</activity>
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<service
android:name="in.ac.iitb.gymkhana.iitbapp.gcm.MyGcmListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name="in.ac.iitb.gymkhana.iitbapp.gcm.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<service
android:name="in.ac.iitb.gymkhana.iitbapp.gcm.RegistrationIntentService"
android:exported="false"></service>
<provider
android:name="in.ac.iitb.gymkhana.iitbapp.data.IITBAppContentProvider"
android:authorities="in.ac.iitb.gymkhana.iitbapp"
......
......@@ -3,19 +3,26 @@ package in.ac.iitb.gymkhana.iitbapp;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.annotations.SerializedName;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import net.openid.appauth.AuthorizationException;
import net.openid.appauth.AuthorizationRequest;
......@@ -27,25 +34,66 @@ import in.ac.iitb.gymkhana.iitbapp.api.RetrofitInterface;
import in.ac.iitb.gymkhana.iitbapp.api.ServiceGenerator;
import in.ac.iitb.gymkhana.iitbapp.api.model.LoginRequest;
import in.ac.iitb.gymkhana.iitbapp.api.model.LoginResponse;
import in.ac.iitb.gymkhana.iitbapp.gcm.RegistrationIntentService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class LoginActivity extends AppCompatActivity {
public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer";
public static final String REGISTRATION_COMPLETE = "registrationComplete";
private static final String TAG = "LoginActivity";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private final String clientId = "pFcDDWtUUfzlAX2ibriV25lm1J2m92O5ynfT4SYk";
private final String clientSecret = "k56GXiN1qB4Dt7CnTVWjuwLJyWntNulitWOkL7Wddr6JHPiHqIZgSfgUplO6neTqumVr32zA14XgQmkuoC8y6y9jnaQT9tKDsq4jQklRb8MQNQglQ1H4YrmqOwPfaNyO";
private final Uri redirectUri = Uri.parse("https://redirecturi");
private final Uri mAuthEndpoint = Uri.parse("http://gymkhana.iitb.ac.in/sso/oauth/authorize/");
private final Uri mTokenEndpoint = Uri.parse("http://gymkhana.iitb.ac.in/sso/oauth/token/");
public String authCode = null;
SessionManager session;
Context mContext = this;
private AuthorizationService mAuthService;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private boolean isReceiverRegistered;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new SessionManager(mContext);
setContentView(R.layout.activity_login);
mAuthService = new AuthorizationService(this);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences
.getBoolean(SENT_TOKEN_TO_SERVER, false);
if (sentToken) {
String token = intent.getStringExtra("Token");
Log.d(TAG, "Going to login with :" + authCode + "\n" + token);
//************
//TODO Remove following 6 lines after the server is hosted
String gcmRegId = token;
session.createLoginSession(gcmRegId);
Intent i = new Intent(mContext, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
//**************
login(authCode, token);
} else {
}
}
};
registerReceiver();
Button ldapLogin = (Button) findViewById(R.id.ldap_login);
ldapLogin.setOnClickListener(new View.OnClickListener() {
......@@ -81,15 +129,17 @@ public class LoginActivity extends AppCompatActivity {
if (intent != null) {
Log.d(TAG, "Intent Received");
String action = intent.getAction();
switch (action) {
case "HANDLE_AUTHORIZATION_RESPONSE": {
handleAuthorizationResponse(intent);
if (action != null) {
switch (action) {
case "HANDLE_AUTHORIZATION_RESPONSE": {
handleAuthorizationResponse(intent);
}
break;
default:
Log.d(TAG, intent.getAction());
}
break;
default:
Log.d(TAG, intent.getAction());
}
}
}
}
......@@ -103,9 +153,17 @@ public class LoginActivity extends AppCompatActivity {
@Override
protected void onResume() {
super.onResume();
registerReceiver();
Log.d(TAG, "In Resume");
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
isReceiverRegistered = false;
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
......@@ -117,13 +175,19 @@ public class LoginActivity extends AppCompatActivity {
AuthorizationException error = AuthorizationException.fromIntent(intent);
if (response != null) {
Log.d(TAG, "Received AuthorizationResponse: " + "AuthCode: " + response.authorizationCode);
authCode = response.authorizationCode;
Log.d(TAG, "Received AuthorizationResponse: " + "AuthCode: " + authCode);
Toast.makeText(this,
"AuthCode: " + response.authorizationCode, Toast.LENGTH_SHORT)
"AuthCode: " + authCode, Toast.LENGTH_SHORT)
.show();
if (checkPlayServices()) {
Intent registerIntent = new Intent(this, RegistrationIntentService.class);
startService(registerIntent);
}
//
// TODO: Replace gcmId
login(response.authorizationCode, "xyz");
} else {
Log.i(TAG, "Authorization failed: " + error.getMessage());
Toast.makeText(this,
......@@ -169,12 +233,20 @@ public class LoginActivity extends AppCompatActivity {
}
private void login(String authorizationCode, String gcmId) {
final String gcmRegId = gcmId;
LoginRequest loginRequest = new LoginRequest(authorizationCode, gcmId);
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class);
retrofitInterface.login(loginRequest).enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response.isSuccessful()) {
Log.d(TAG, "Login request successful");
session.createLoginSession(gcmRegId);
Intent i = new Intent(mContext, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
//Save credentials in AccountManager to keep user logged in
//Go to MainActivity
}
......@@ -187,5 +259,31 @@ public class LoginActivity extends AppCompatActivity {
}
});
}
private void registerReceiver() {
if (!isReceiverRegistered) {
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(REGISTRATION_COMPLETE));
isReceiverRegistered = true;
}
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
}
......@@ -34,10 +34,17 @@ import in.ac.iitb.gymkhana.iitbapp.fragment.TimetableFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "MainActivity";
SessionManager session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
session.checkLogin();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
......@@ -50,6 +57,7 @@ public class MainActivity extends AppCompatActivity
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
......@@ -69,6 +77,7 @@ public class MainActivity extends AppCompatActivity
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
......@@ -155,8 +164,8 @@ public class MainActivity extends AppCompatActivity
transaction.replace(R.id.framelayout_for_fragment, fragment, fragment.getTag());
transaction.commit();
}
public void onRequestPermissionsResult(int requestCode,
public void onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
......
package in.ac.iitb.gymkhana.iitbapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class SessionManager {
private static final String PREF_NAME = "LoggedInPref";
private static final String IS_LOGIN = "IsLoggedIn";
private static final String GCM_ID = "GcmId";
SharedPreferences pref;
Editor editor;
Context context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this.context = context;
pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void checkLogin() {
if (!this.isLoggedIn()) {
Intent i = new Intent(context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
context.startActivity(i);
}
}
public void createLoginSession(String gcmId) {
Log.d("SessionManager", "GcmId being stored");
editor.putBoolean(IS_LOGIN, true);
editor.putString(GCM_ID, gcmId);
editor.commit();
}
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
package in.ac.iitb.gymkhana.iitbapp.gcm;
import com.google.android.gms.gcm.GcmListenerService;
public class MyGcmListenerService extends GcmListenerService {
}
package in.ac.iitb.gymkhana.iitbapp.gcm;
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;
public class MyInstanceIDListenerService extends InstanceIDListenerService {
@Override
public void onTokenRefresh() {
// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
package in.ac.iitb.gymkhana.iitbapp.gcm;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
@TargetApi(Build.VERSION_CODES.CUPCAKE)
public class RegistrationIntentService extends IntentService {
public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer";
public static final String REGISTRATION_COMPLETE = "registrationComplete";
private static final String TAG = "RegIntentService";
@RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public RegistrationIntentService() {
super(TAG);
}
@RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onHandleIntent(@Nullable Intent intent) {
String token = null;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
InstanceID instanceID = InstanceID.getInstance(this);
token = instanceID.getToken("306601329049",
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(TAG, "GCM Registration Token: " + token);
Toast.makeText(this, "GCM Registration Token: " + token, Toast.LENGTH_SHORT).show();
sharedPreferences.edit().putBoolean(SENT_TOKEN_TO_SERVER, true).apply();
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
sharedPreferences.edit().putBoolean(SENT_TOKEN_TO_SERVER, false).apply();
}
//Notify UI that registration is complete
Intent registrationComplete = new Intent(REGISTRATION_COMPLETE);
registrationComplete.putExtra("Token", token);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
}
......@@ -7,8 +7,9 @@ buildscript {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha6'
classpath 'com.android.tools.build:gradle:3.0.0-alpha6'
classpath 'com.google.gms:google-services:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
......
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