Page MenuHomec4science

LoginMain.java
No OneTemporary

File Metadata

Created
Thu, Jan 2, 22:38

LoginMain.java

package com.example.genomicprivacy;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.json.JSONException;
import org.json.JSONObject;
import FrameWork.MedUnit;
import FrameWork.Patient;
import FrameWork.Type;
import FrameWork.User;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import crypto.KeyGenerator;
/**
* Activity which displays a login screen to the user, offering registration as
* well.
*/
public class LoginMain extends Activity {
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
/**
* Username
*/
private String userName;
/**
* Passeword
*/
private String mPassword;
/**
* Field for entering the username
*/
private EditText usernameView;
/**
* Field for entering the password
*/
private EditText mPasswordView;
/**
* View that contains the field for the username, password and the button
*/
private View mLoginFormView;
/**
* View that contains the spinner.
*/
private View mLoginStatusView;
/**
* Text for the status of the login
*/
private TextView mLoginStatusMessageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_main);
//Try to create the file if they doesn't exist for storing the keys and the pdf reports
File createDir = new File(Environment.getExternalStorageDirectory()
.getPath() + "/GenomicPrivacy/P_keys");
createDir.mkdirs();
createDir = new File(Environment.getExternalStorageDirectory()
.getPath() + "/GenomicPrivacy/PDFReports");
createDir.mkdirs();
// Set up the login form.
usernameView = (EditText) findViewById(R.id.email);
usernameView.setText(userName);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.login_main, menu);
return true;
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
usernameView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
userName = usernameView.getText().toString();
mPassword = mPasswordView.getText().toString();
System.out.println("Hash of password : " + mPassword);
if (userName.isEmpty() || mPassword.isEmpty()) {
Toast toast = Toast.makeText(ContextApp.getContext(),
"You have to enter an userName and a password", 3000);
toast.show();
} else {
mPassword = hashString(mPassword);
System.out.println("Username : " + userName);
System.out.println("Hash of password : " + mPassword);
boolean cancel = false;
View focusView = null;
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mLoginStatusMessageView
.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute((Void) null);
}
}
}
/**
* Shows the progress UI and hides the login form.
*
* @param show
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* @param password
* @return the hash of the password
*/
public static String hashString(String s) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
md.update(s.getBytes());
byte[] hashByte = md.digest();
// convert the byte to hex format method 2
StringBuffer hash = new StringBuffer();
for (int i = 0; i < hashByte.length; i++) {
String hex = Integer.toHexString(0xff & hashByte[i]);
if (hex.length() == 1)
hash.append('0');
hash.append(hex);
}
return hash.toString();
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
@SuppressWarnings("resource")
@Override
protected Boolean doInBackground(Void... params) {
// 3 : create a JSON object and send it to server for verification
JSONObject loginJS = new JSONObject();
boolean connexionAccepted = false;
try {
loginJS.put("type", Type.LOGIN);
loginJS.put("username", userName);
loginJS.put("hash", mPassword);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User user = new User();
// take the keys file
System.out
.println("User created and ready to connect to the spu for login");
user.connexionToSPU();
System.out.println("LoginJS = " + loginJS.toString());
user.sendToSPU(loginJS);
// 4 : wait response
JSONObject loginResponseJS = user.receiveFromSPU();
Type type = null;
try {
type = (Type) loginResponseJS.get("type");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int id = -1;
switch (type) {
case ERROR:
connexionAccepted = false;
break;
case PATIENT:
// Patient p = (Patient) user.getProfil(Type.PATIENT);
try {
id = loginResponseJS.getInt("id");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Patient p = new Patient(id, null, user.getJsrSPU(),
user.getJswSPU(), null, null, null, null);
ContextApp.setP(p);
System.out.println("Welcome patient " + id);
// create the patient with the info from json (just id) => rest
// null
// If the key already exists, do nothgin, else create the
// keyfile
// and send part1,2 to MU and SPU
// If the key already exists, do nothing, else create the
// keyfile
// and send part1,2 to MU and SPU
String pathKey = "Environment.getExternalStorageDirectory().getPath()/GenomicPrivacy/P_keys/"
+ id + "keys.txt";
File f = new File(pathKey);
if (!f.exists()) {
}
// LAUNCH THE PATIENT GUI
Intent i = new Intent(ContextApp.getContext(), PatientGUI.class);
i.putExtra("id", id);
startActivity(i);
// }
connexionAccepted = true;
break;
case MEDICAL:
try {
id = loginResponseJS.getInt("id");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
MedUnit mu = new MedUnit(id, null, user.getJsrSPU(),
user.getJswSPU(), null);
ContextApp.setMu(mu);
// LAUNCH MU GUI
Intent i2 = new Intent(ContextApp.getContext(), MuGUI.class);
startActivity(i2);
connexionAccepted = true;
break;
}
// TODO: register the new account here.
return connexionAccepted;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
/*
new AlertDialog.Builder(ContextApp.getContext())
.setTitle("Keys!")
.setMessage("The Android application didn't find any keys. Did you already logged in " +
"by the desktop application? If yes please take the file : /P_Keys/Your_IDKeys.txt. Copy and paste it into your Android device " +
"at the following location : GenomicPrivacy/P_Keys/. And cancel the login. If it's the first you logged in then click OK")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).show();
KeyGenerator kg = new KeyGenerator(); kg.generateKeys();
String prvKeyMu = kg.getX1().toString(); String prvKeySPU
= kg.getX2().toString(); String pubKey =
kg.getN().toString() + "," + kg.getG().toString() + "," +
kg.getH().toString(); FileOutputStream fOut = null;
OutputStreamWriter myOutWriter = null; f = new
File(Environment.getExternalStorageDirectory().getPath()+
"/GenomicPrivacy/P_keys/"+id+"keys.txt"); f.mkdir(); try
{ f.createNewFile(); fOut = new FileOutputStream(f);
myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(prvKeyMu+"\n");
myOutWriter.append(prvKeySPU+"\n");
myOutWriter.append(pubKey); myOutWriter.close();
fOut.close(); } catch (IOException e) { // TODO
Auto-generated catch block e.printStackTrace(); }
// send public key and private key part1 to SPU
JSONObject jsonSPU = new JSONObject(); try {
jsonSPU.put("type", Type.KEYS); jsonSPU.put("halfprkey",
prvKeySPU); jsonSPU.put("pubkey", pubKey);
jsonSPU.put("id_p", p.getID()); } catch (JSONException e)
{ // TODO Auto-generated catch block e.printStackTrace();
} user.sendToSPU(jsonSPU); // send public Key private key
part 2 to SPU JSONObject jsonMU = new JSONObject(); try {
jsonMU.put("type", Type.KEYS); jsonMU.put("halfprkey",
prvKeyMu); jsonMU.put("pubkey", pubKey);
jsonMU.put("id_p", p.getID()); } catch (JSONException e)
{ // TODO Auto-generated catch block e.printStackTrace();
} // user.connexionToMU(); // user.sentToMU(jsonMU);
*/
finish();
} else {
mPasswordView
.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
// private void storeKeys(File f, String prvKeyMU, String prvKeySPU,
// String pubKey) {
//
// }
}

Event Timeline