PPaste!

Auth Service

Home - All the pastes - Authored by Thooms

Raw version

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package co.polylearn.toeic;

import android.accounts.Account;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.common.Scopes;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * helper methods.
 */
public class AuthService extends IntentService {
    public static final int SUCCESS_AUTH = 1;
    public static final int ERROR_AUTH = 2;
    public static final String KEY_STATUS_CODE = "co.polylearn.toeic.extra.STATUS_CODE";
    public static final String KEY_NETWORK_RESPONSE = "co.polylearn.toeic.extra.NETWORK_RESPONSE";
    private static final String ACTION_FACEBOOK_LOGIN = "co.polylearn.toeic.action.FACEBOOK_LOGIN";
    private static final String ACTION_GOOGLE_LOGIN = "co.polylearn.toeic.action.GOOGLE_LOGIN";
    private static final String ACTION_REGISTER = "co.polylearn.toeic.action.REGISTER";
    private static final String ACTION_PASSWORD_LOGIN = "co.polylearn.toeic.action.PASSWORD_LOGIN";
    private static final String EXTRA_ACCESS_TOKEN = "co.polylearn.toeic.extra.ACCESS_TOKEN";
    private static final String EXTRA_RECEIVER = "co.polylearn.toeic.extra.RECEIVER";
    private static final String EXTRA_EMAIL = "co.polylearn.toeic.extra.EMAIL";
    private static final String EXTRA_PASSWORD = "co.polylearn.toeic.extra.PASSWORD";



    public AuthService() {
        super("AuthService");
    }

    /**
     * Starts this service to perform action Facebook Login with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    public static void startActionFacebookLogin(Context context, String token, ResultReceiver resultReceiver) {
        Intent intent = new Intent(context, AuthService.class);
        intent.setAction(ACTION_FACEBOOK_LOGIN);
        intent.putExtra(EXTRA_ACCESS_TOKEN, token);
        intent.putExtra(EXTRA_RECEIVER, resultReceiver);
        context.startService(intent);
    }

    /**
     * Starts this service to perform action Google Login with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    public static void startActionGoogleLogin(Context context, String email, ResultReceiver resultReceiver) {
        Intent intent = new Intent(context, AuthService.class);
        intent.setAction(ACTION_GOOGLE_LOGIN);
        intent.putExtra(EXTRA_EMAIL, email);
        intent.putExtra(EXTRA_RECEIVER, resultReceiver);
        context.startService(intent);
    }

    /**
     * Starts this service to perform action Register Login with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    public static void startActionRegister(Context context, String email, String password, ResultReceiver resultReceiver) {
        Intent intent = new Intent(context, AuthService.class);
        intent.setAction(ACTION_REGISTER);
        intent.putExtra(EXTRA_EMAIL, email);
        intent.putExtra(EXTRA_PASSWORD, password);
        intent.putExtra(EXTRA_RECEIVER, resultReceiver);
        context.startService(intent);
    }

    public static void startActionPasswordLogin(Context context, String email, String password, ResultReceiver resultReceiver) {
        Intent intent = new Intent(context, AuthService.class);
        intent.setAction(ACTION_PASSWORD_LOGIN);
        intent.putExtra(EXTRA_EMAIL, email);
        intent.putExtra(EXTRA_PASSWORD, password);
        intent.putExtra(EXTRA_RECEIVER, resultReceiver);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_RECEIVER);
            if (ACTION_FACEBOOK_LOGIN.equals(action)) {
                final String token = intent.getStringExtra(EXTRA_ACCESS_TOKEN);
                handleActionFacebookLogin(token, receiver);
            } else if (ACTION_GOOGLE_LOGIN.equals(action)) {
                final String email = intent.getStringExtra(EXTRA_EMAIL);
                handleActionGoogleLogin(email, receiver);
            } else if (ACTION_PASSWORD_LOGIN.equals(action) || ACTION_REGISTER.equals(action)) {
                final String email = intent.getStringExtra(EXTRA_EMAIL);
                final String password = intent.getStringExtra(EXTRA_PASSWORD);
                if (ACTION_PASSWORD_LOGIN.equals(action)) {
                    handleActionPasswordLogin(email, password, receiver);
                } else {
                    handleActionRegister(email, password, receiver);
                }
            }
        }
    }

    /**
     * Handle action Password Login in the provided background thread with the provided
     * parameters.
     */
    private void handleActionPasswordLogin(final String email, final String password, final ResultReceiver receiver) {
        final String URL = "https://api.polylearn.co/login";

        sendWithCredentials(email, password, URL, receiver);
    }


    /**
     * Handle action Password Login in the provided background thread with the provided
     * parameters.
     */
    private void handleActionRegister(final String email, final String password, final ResultReceiver receiver) {
        final String URL = "https://api.polylearn.co/register";

        sendWithCredentials(email, password, URL, receiver);
    }

    private void sendWithCredentials(final String email, final String password, final String URL, final ResultReceiver receiver) {
        HashMap<String, String> params = new HashMap<>();
        params.put("username", email);
        params.put("password", password);

        VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(
                getTokenRequest(URL, params, receiver)
        );
    }

    /**
     * Handle action Facebook Login in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFacebookLogin(String token, final ResultReceiver receiver) {
        final String URL = "https://api.polylearn.co/facebook/auth";
        handleSocialLogin(URL, token, receiver);
    }

    /**
     * Handle action Google Login in the provided background thread with the provided
     * parameters.
     */
    private void handleActionGoogleLogin(String email, final ResultReceiver receiver) {
        final String URL = "https://api.polylearn.co/google/auth";
        String token = null;

        try {

            token = GoogleAuthUtil.getToken(getApplicationContext(), new Account(email, "com.google"), "oauth2:"
                    + Scopes.EMAIL);
        } catch (IOException | GoogleAuthException e) {
            e.printStackTrace();
        }

        handleSocialLogin(URL, token, receiver);
    }

    private void handleSocialLogin(final String URL, final String token, final ResultReceiver receiver) {
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", token);

        VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(
                getTokenRequest(URL, params, receiver)
        );
    }

    private JsonObjectRequest getTokenRequest(final String URL, final HashMap<String, String> params, final ResultReceiver receiver) {
        return new JsonObjectRequest(URL, new JSONObject(params),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        String token = null;
                        try {
                            token = (String) response.get("token");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        Bundle args = new Bundle();
                        args.putString("token", token);
                        receiver.send(SUCCESS_AUTH, args);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.e("Error: ", error.getMessage());
                Bundle args = new Bundle();
                args.putInt(KEY_STATUS_CODE, error.networkResponse.statusCode);
                args.putString(KEY_NETWORK_RESPONSE, new String(error.networkResponse.data, StandardCharsets.UTF_8));
                receiver.send(ERROR_AUTH, args);
            }
        });
    }
}