Skip to content
Open
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ gen/
out/
build/
.idea/workspace.xml

parse/
*.iws
*.iml
*.ipr
Expand Down
13 changes: 8 additions & 5 deletions accountAuthenticator/build.gradle
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
apply plugin: 'com.android.library'

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
compileSdkVersion 28
buildToolsVersion "28.0.3"
useLibrary 'org.apache.http.legacy'

defaultConfig {
minSdkVersion 8
targetSdkVersion 23
minSdkVersion 26
targetSdkVersion 28
}

buildTypes {
Expand All @@ -19,5 +19,8 @@ android {
}

dependencies {
compile 'com.google.code.gson:gson:2.4'
implementation 'com.google.code.gson:gson:2.8.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support:support-annotations:28.0.0'
androidTestImplementation 'com.android.support.test:runner:0.5'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.udinic.accounts_authenticator_example.authentication;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

//Taken from stackOverflow , phew

public class AdvancedEncryptionStandard {
String key;
String initVector;

public AdvancedEncryptionStandard(String key, String initVector) {
this.key = key;
this.initVector = initVector;
}

public String encrypt(String value) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));

SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

byte[] encrypted = cipher.doFinal(value.getBytes());
String s = new String(Base64.getEncoder().encode(encrypted));
return s;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

public String decrypt(String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));

return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}

return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.udinic.accounts_authenticator_example.R;

import java.nio.charset.StandardCharsets;

import static com.udinic.accounts_authenticator_example.authentication.AccountGeneral.sServerAuthenticate;

/**
* The Authenticator activity.
*
* <p>
* Called by the Authenticator and in charge of identifing the user.
*
* <p>
* It sends back to the Authenticator the result.
*/
public class AuthenticatorActivity extends AccountAuthenticatorActivity {
Expand All @@ -36,6 +39,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity {

private final String TAG = this.getClass().getSimpleName();

AdvancedEncryptionStandard advancedEncryptionStandard;
private AccountManager mAccountManager;
private String mAuthTokenType;

Expand All @@ -45,6 +49,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
advancedEncryptionStandard = new AdvancedEncryptionStandard("Bar12345Bar12345", "RandomInitVector");
setContentView(R.layout.act_login);
mAccountManager = AccountManager.get(getBaseContext());

Expand All @@ -54,7 +59,7 @@ public void onCreate(Bundle savedInstanceState) {
mAuthTokenType = AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS;

if (accountName != null) {
((TextView)findViewById(R.id.accountName)).setText(accountName);
((TextView) findViewById(R.id.accountName)).setText(accountName);
}

findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {
Expand Down Expand Up @@ -130,29 +135,34 @@ protected void onPostExecute(Intent intent) {
}

private void finishLogin(Intent intent) {
Log.d("udinic", TAG + "> finishLogin");

String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));

if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
Log.d("udinic", TAG + "> finishLogin > addAccountExplicitly");
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
String authtokenType = mAuthTokenType;

// Creating the account on the device and setting the auth token we got
// (Not setting the auth token will cause another call to the server to authenticate the user)
mAccountManager.addAccountExplicitly(account, accountPassword, null);
mAccountManager.setAuthToken(account, authtokenType, authtoken);
} else {
Log.d("udinic", TAG + "> finishLogin > setPassword");
mAccountManager.setPassword(account, accountPassword);
}
try {
Log.d("udinic", TAG + "> finishLogin");

String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));

if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
Log.d("udinic", TAG + "> finishLogin > addAccountExplicitly" + accountPassword);
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
String authtokenType = mAuthTokenType;

Log.d("udinic", TAG + " auth token" + authtoken + " & encrypted auth tokens");
// Creating the account on the device and setting the auth token we got
// (Not setting the auth token will cause another call to the server to authenticate the user)
mAccountManager.addAccountExplicitly(account, accountPassword, null);
mAccountManager.setAuthToken(account, authtokenType, advancedEncryptionStandard.encrypt(authtoken));
} else {
Log.d("udinic", TAG + "> finishLogin > setPassword>" + accountPassword);
mAccountManager.setPassword(account, accountPassword);
}

setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);
finish();
setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);
finish();
} catch (Exception e) {
//
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.udinic.accounts_authenticator_example.authentication;

//Start a parse Server in heroku for running this example and add these values from the heroku server
//

class Config {
static public String APP_ID = "myAppId";
static public String APP_KEY = "myMasterKey";
static public String URL = "https://applicationauthenticator.herokuapp.com";
}
Original file line number Diff line number Diff line change
@@ -1,58 +1,69 @@
package com.udinic.accounts_authenticator_example.authentication;

import android.net.Uri;
import android.util.Log;

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;


import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


/**
* Handles the comminication with Parse.com
*
* <p>
* User: udinic
* Date: 3/27/13
* Time: 3:30 AM
*/
public class ParseComServerAuthenticate implements ServerAuthenticate{
public class ParseComServerAuthenticate implements ServerAuthenticate {
@Override
public String userSignUp(String name, String email, String pass, String authType) throws Exception {

String url = "https://api.parse.com/1/users";

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("X-Parse-Application-Id","XUafJTkPikD5XN5HxciweVuSe12gDgk2tzMltOhr");
httpPost.addHeader("X-Parse-REST-API-Key", "8L9yTQ3M86O4iiucwWb4JS7HkxoSKo7ssJqGChWx");
httpPost.addHeader("Content-Type", "application/json");

String user = "{\"username\":\"" + email + "\",\"password\":\"" + pass + "\",\"phone\":\"415-392-0202\"}";
HttpEntity entity = new StringEntity(user);
httpPost.setEntity(entity);

//https://api.parse.com/1/users
URL url = new URL(Config.URL + "/parse/users");
HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();

httpClient.addRequestProperty("X-Parse-Application-Id", Config.APP_ID);
httpClient.addRequestProperty("X-Parse-REST-API-Key", Config.APP_KEY);
httpClient.addRequestProperty("Content-Type", "application/json");
httpClient.setRequestMethod("POST");
JSONObject params = new JSONObject();
params.put("username", email);
params.put("password", pass);
params.put("phone", "999-999-9999");
OutputStreamWriter wr = new OutputStreamWriter(httpClient.getOutputStream());
wr.write(params.toString());
wr.flush();
String authtoken = null;
try {
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
String responseString = httpClient.getResponseMessage();

if (response.getStatusLine().getStatusCode() != 201) {
if (httpClient.getResponseCode() != 201) {
ParseComError error = new Gson().fromJson(responseString, ParseComError.class);
throw new Exception("Error creating user["+error.code+"] - " + error.error);
throw new Exception(responseString);
}

BufferedReader in = new BufferedReader(
new InputStreamReader(httpClient.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

User createdUser = new Gson().fromJson(responseString, User.class);
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
User createdUser = new Gson().fromJson(response.toString(), User.class);

authtoken = createdUser.sessionToken;

Expand All @@ -68,40 +79,45 @@ public String userSignIn(String user, String pass, String authType) throws Excep

Log.d("udini", "userSignIn");

DefaultHttpClient httpClient = new DefaultHttpClient();
String url = "https://api.parse.com/1/login";

//https://api.parse.com/1/
String tUrl = Config.URL + "/parse/login";

String query = null;
try {
query = String.format("%s=%s&%s=%s", "username", URLEncoder.encode(user, "UTF-8"), "password", pass);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
url += "?" + query;
tUrl += "?" + query;

URL url = new URL(tUrl);

HttpGet httpGet = new HttpGet(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");

httpGet.addHeader("X-Parse-Application-Id", "XUafJTkPikD5XN5HxciweVuSe12gDgk2tzMltOhr");
httpGet.addHeader("X-Parse-REST-API-Key", "8L9yTQ3M86O4iiucwWb4JS7HkxoSKo7ssJqGChWx");
httpURLConnection.setRequestProperty("X-Parse-Application-Id", Config.APP_ID);
httpURLConnection.setRequestProperty("X-Parse-REST-API-Key", Config.APP_KEY);

HttpParams params = new BasicHttpParams();
params.setParameter("username", user);
params.setParameter("password", pass);
httpGet.setParams(params);
// httpGet.getParams().setParameter("username", user).setParameter("password", pass);

String authtoken = null;
try {
HttpResponse response = httpClient.execute(httpGet);

String responseString = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() != 200) {
ParseComError error = new Gson().fromJson(responseString, ParseComError.class);
throw new Exception("Error signing-in ["+error.code+"] - " + error.error);
String responseString = httpURLConnection.getResponseMessage();
Log.d("here", responseString);
if (httpURLConnection.getResponseCode() != 200) {
//ParseComError error = new Gson().fromJson(httpURLConnection.getResponseMessage(), ParseComError.class);
throw new Exception(responseString);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

User loggedUser = new Gson().fromJson(responseString, User.class);
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
User loggedUser = new Gson().fromJson(response.toString(), User.class);
authtoken = loggedUser.sessionToken;

} catch (IOException e) {
Expand All @@ -116,6 +132,7 @@ private class ParseComError implements Serializable {
int code;
String error;
}

private class User implements Serializable {

private String firstName;
Expand Down
Loading