Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encryption of User data #43

Open
wants to merge 1 commit into
base: mvvm
Choose a base branch
from
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import com.college.collegeconnect.ContributeActivity;
import com.college.collegeconnect.R;
import com.college.collegeconnect.datamodels.FirebaseUserInfo;
import com.college.collegeconnect.datamodels.SaveSharedPreference;
import com.college.collegeconnect.datamodels.User;

Expand All @@ -30,12 +31,13 @@
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.ListenerRegistration;

import java.util.ArrayList;

import kotlin.Unit;

public class StepTwoSignUp extends AppCompatActivity {

public static final String EXTRA_NAME = "name";
Expand All @@ -51,9 +53,7 @@ public class StepTwoSignUp extends AppCompatActivity {
private Spinner collegeSpinner;
private TextView contribute;
private String receivedPRev;
private FirebaseFirestore firebaseFirestore;
DocumentReference documentReference;
ListenerRegistration listener;
private ListenerRegistration listener;
ValueEventListener valueListener;

@Override
Expand All @@ -75,9 +75,6 @@ protected void onCreate(Bundle savedInstanceState) {
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
collegeSpinner.setAdapter(spinnerArrayAdapter);

firebaseFirestore = FirebaseFirestore.getInstance();
documentReference = firebaseFirestore.collection("users").document(mAuth.getCurrentUser().getUid());

databaseReference = firebaseDatabase.getReference("Colleges");
databaseReference.addListenerForSingleValueEvent(valueListener = new ValueEventListener() {
@Override
Expand Down Expand Up @@ -163,29 +160,24 @@ public void onClick(View v) {
college = collegeSpinner.getSelectedItem().toString();

if (receivedPRev == null) {//google

User.addUser(roll, mAuth.getCurrentUser().getEmail(), mAuth.getCurrentUser().getDisplayName(), branch, college);
uploadUserInfo(roll, mAuth.getCurrentUser().getDisplayName(), branch, college);
SaveSharedPreference.setUserName(getApplicationContext(), mAuth.getCurrentUser().getEmail());
startActivity(new Intent(getApplicationContext(), Navigation.class));
finish();
} else {//email
SaveSharedPreference.setUploaded(StepTwoSignUp.this, true);
if (SaveSharedPreference.getUser(StepTwoSignUp.this).equals("")) {
listener = documentReference.addSnapshotListener((documentSnapshot, error) -> {
listener = FirebaseUserInfo.INSTANCE.getUserInfo(StepTwoSignUp.this, user -> {
try {
assert documentSnapshot != null;
String name = documentSnapshot.getString("name");
User.addUser(roll, mAuth.getCurrentUser().getEmail(), name, branch, college);
Log.d(TAG, "Details Uploaded!");
SaveSharedPreference.setUser(StepTwoSignUp.this, name);
SaveSharedPreference.setUser(StepTwoSignUp.this, user.getName());
Intent intent = new Intent(StepTwoSignUp.this, MainActivity.class);
startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
finish();
} catch (Exception ignored) {
}
} catch (Exception ignored) { }
return Unit.INSTANCE;
});
} else {
User.addUser(roll, mAuth.getCurrentUser().getEmail(), SaveSharedPreference.getUser(StepTwoSignUp.this), branch, college);
uploadUserInfo(roll, SaveSharedPreference.getUser(StepTwoSignUp.this), branch, college);
Log.d(TAG, "Details Uploaded!");
Intent intent = new Intent(StepTwoSignUp.this, MainActivity.class);
startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
Expand Down Expand Up @@ -268,5 +260,11 @@ protected void onDestroy() {
listener.remove();
super.onDestroy();
}

private void uploadUserInfo(String roll, String name, String branch, String college) {
if (mAuth.getCurrentUser() == null) return;
User user = new User(roll, mAuth.getCurrentUser().getEmail(), name, branch, college);
FirebaseUserInfo.INSTANCE.uploadUserInfo(user, this);
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.college.collegeconnect.datamodels

import android.content.Context
import android.util.Log
import com.college.collegeconnect.security.Security
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ListenerRegistration
import com.google.firebase.firestore.MetadataChanges

object FirebaseUserInfo {
private const val TAG = "UserInfoUpload"

fun uploadUserInfo(user: User, ctx: Context) {
val firebaseUser = FirebaseAuth.getInstance().currentUser ?: return
FirebaseFirestore.getInstance()
.collection("users")
.document(firebaseUser.uid)
.set(user.encrypt(ctx))
.addOnSuccessListener { Log.d(TAG, "Account Created") }
.addOnFailureListener { Log.e(TAG, "Uploading user info failed" + it.message) }
}

fun getUserInfo(ctx: Context, callback: (User) -> Unit): ListenerRegistration? {
val firebaseUser = FirebaseAuth.getInstance().currentUser ?: return null
return FirebaseFirestore.getInstance()
.collection("users")
.document(firebaseUser.uid)
.addSnapshotListener(MetadataChanges.INCLUDE) { document, exception ->
if (exception != null) {
Log.e(TAG, exception.message ?: exception.code.name)
} else {
document?.let { callback(it.decrypt(ctx)) }
}
}
}

private fun User.encrypt(ctx: Context): User = User(
Security.encrypt(rollNo, ctx),
Security.encrypt(email, ctx),
Security.encrypt(name, ctx),
Security.encrypt(branch, ctx),
Security.encrypt(college, ctx)
)

private fun DocumentSnapshot.decrypt(ctx: Context): User = User(
Security.decrypt(getString("rollNo").orEmpty(), ctx),
Security.decrypt(getString("email").orEmpty(), ctx),
Security.decrypt(getString("name").orEmpty(), ctx),
Security.decrypt(getString("branch").orEmpty(), ctx),
Security.decrypt(getString("college").orEmpty(), ctx)
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public class SaveSharedPreference {
private static final String ATTENDANCE_CRITERIA = "attendance_criteria";
private static final String POP = "pop";
private static final String DETAILS_UPLOADED = "uploaded";
private static final String ENCRYPTION_KEY = "encryption_key";

public static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
Expand Down Expand Up @@ -107,6 +108,10 @@ public static void setPop(Context ctx, int pop) {
editor.apply();
}

public static void setEncryptionKey(Context ctx, String key) {
getSharedPreferences(ctx).edit().putString(ENCRYPTION_KEY, key).apply();
}

public static int getAttendanceCriteria(Context ctx) {
return getSharedPreferences(ctx).getInt(ATTENDANCE_CRITERIA, 75);
}
Expand Down Expand Up @@ -159,6 +164,10 @@ public static int getPop(Context ctx) {
return getSharedPreferences(ctx).getInt(POP, 1);
}

public static String getEncryptionKey(Context ctx) {
return getSharedPreferences(ctx).getString(ENCRYPTION_KEY, null);
}

//Clear data on logout
public static void clearUserName(Context ctx) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
Expand Down
65 changes: 8 additions & 57 deletions app/src/main/java/com/college/collegeconnect/datamodels/User.java
Original file line number Diff line number Diff line change
@@ -1,30 +1,15 @@
package com.college.collegeconnect.datamodels;

import android.util.Log;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;

public class User {

public String rollno;
public String email;
public String name;
public String branch;
public String college;
public static FirebaseFirestore firebaseFirestore;
public static FirebaseDatabase firebaseDatabase;
public static FirebaseAuth auth;
private String rollNo;
private String email;
private String name;
private String branch;
private String college;

public String getRollno() {
return rollno;
public String getRollNo() {
return rollNo;
}

public String getEmail() {
Expand All @@ -44,48 +29,14 @@ public String getCollege() {
}

public User() {
rollno = null;
email = null;
name = null;
branch = null;
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}

public User(String rollNo, String email, String name, String branch, String college) {
this.rollno = rollNo;
this.rollNo = rollNo;
this.email = email;
this.name = name;
this.branch = branch;
this.college = college;
}

public static boolean addUser(String username, String email, String name, String branch, String college) {
User user = new User(username, email, name, branch, college);

//Get user id
firebaseFirestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;

CollectionReference collectionReference = firebaseFirestore.collection("users");
collectionReference.document(firebaseUser.getUid()).set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d("User", "onSuccess: Account Created");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d("User", "onFailure: Account failed :" + e.getMessage());
}
});
// String userId = firebaseUser.getUid();
// firebaseDatabase=FirebaseDatabase.getInstance();
// DatabaseReference myRef = firebaseDatabase.getReference("users");
// int dot = email.indexOf(".");
// String str = email.replace(".","@");
// myRef.child(userId).setValue(user);
return true;
}
}
Original file line number Diff line number Diff line change
@@ -1,92 +1,31 @@
package com.college.collegeconnect.models

import android.app.Application
import android.util.Log
import androidx.lifecycle.*
import com.google.firebase.auth.FirebaseAuth
import com.college.collegeconnect.datamodels.FirebaseUserInfo
import com.google.firebase.firestore.*

class HomeViewModel(application: Application): AndroidViewModel(application) {

private var firebaseFirestore: FirebaseFirestore? = null
var documentReference: DocumentReference? = null
var registered: ListenerRegistration? = null
var nameLive : MutableLiveData<String>?= null
var rollNoLive:MutableLiveData<String>?= null
var branchLive:MutableLiveData<String>?= null
// var tot: MutableLiveData<List<Int>>?= null

fun returnName(): LiveData<String> {
if (nameLive == null) {
nameLive = MutableLiveData()
loadData()
}
return nameLive!!
}

fun returnRoll(): LiveData<String> {
if (rollNoLive == null) {
rollNoLive = MutableLiveData()
loadData()
}
return rollNoLive!!
}


fun returnBranch(): LiveData<String> {
if (branchLive == null) {
branchLive = MutableLiveData()
loadData()
}
return branchLive!!
}
// fun returnTot(): MutableLiveData<List<Int>> {
// if (tot == null) {
// tot = MutableLiveData()
// atten()
// }
// return tot!!
// }
val nameLive: MutableLiveData<String> = MutableLiveData()
val rollNoLive: MutableLiveData<String> = MutableLiveData()
val branchLive: MutableLiveData<String> = MutableLiveData()

// fun atten(){
// viewModelScope.launch { tot?.postValue(listOf( AttendanceDatabase(getApplication()).getAttendanceDao().getAttended(),
// AttendanceDatabase(getApplication()).getAttendanceDao().getMissed()) )
// }
// }

fun loadData(){
firebaseFirestore = FirebaseFirestore.getInstance()
documentReference = firebaseFirestore!!.collection("users").document(FirebaseAuth.getInstance().currentUser?.uid.toString())
val settings = FirebaseFirestoreSettings.Builder()
fun loadData(): ListenerRegistration? {
FirebaseFirestore.getInstance().firestoreSettings = FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build()
firebaseFirestore!!.firestoreSettings = settings

registered = documentReference!!.addSnapshotListener(MetadataChanges.INCLUDE) { documentSnapshot, error ->
try {
val name = documentSnapshot!!.getString("name")
val rollNo = documentSnapshot.getString("rollno")
val strbranch = documentSnapshot.getString("branch")
nameLive?.postValue(name)
rollNoLive?.postValue(rollNo)
branchLive?.postValue(strbranch)
// SaveSharedPreference.setUser(mcontext, name)
// nameField.setText(SaveSharedPreference.getUser(mcontext))
// enrollNo.setText(rollNo)
// branch.setText(strbranch)
// val space = name!!.indexOf(" ")
// val color = Navigation.generatecolor()
// drawable = TextDrawable.builder().beginConfig()
// .width(150)
// .height(150)
// .bold()
// .endConfig()
// .buildRound(name!!.substring(0, 1) + name!!.substring(space + 1, space + 2), color)
// prfileImage.setImageDrawable(drawable)
} catch (e: Exception) {
Log.d("Home", "onEvent: " + e.message)
}
// if (uri != null) Picasso.get().load(uri).into(prfileImage)
return FirebaseUserInfo.getUserInfo(getApplication()) { user ->
nameLive.postValue(user.name)
rollNoLive.postValue(user.rollNo)
branchLive.postValue(user.branch)
}
}
}
Loading