1
0

[API] Improve login (#83)

This commit is contained in:
Mikołaj Pich
2018-04-20 20:30:39 +02:00
committed by Rafał Borcz
parent b7a6b71a4d
commit 2fd5b0f6ee
26 changed files with 1025 additions and 254 deletions

View File

@ -3,19 +3,21 @@ package io.github.wulkanowy.data.db.dao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.github.yuweiguocn.library.greendao.MigrationHelper;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.StandardDatabase;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import io.github.wulkanowy.BuildConfig;
import io.github.wulkanowy.data.db.dao.entities.AccountDao;
import io.github.wulkanowy.api.Vulcan;
import io.github.wulkanowy.data.db.dao.entities.DaoMaster;
import io.github.wulkanowy.data.db.dao.entities.GradeDao;
import io.github.wulkanowy.data.db.dao.entities.SubjectDao;
import io.github.wulkanowy.data.db.dao.entities.DaoSession;
import io.github.wulkanowy.data.db.dao.migrations.Migration23;
import io.github.wulkanowy.data.db.shared.SharedPrefContract;
import io.github.wulkanowy.di.annotations.ApplicationContext;
import io.github.wulkanowy.di.annotations.DatabaseInfo;
@ -24,29 +26,16 @@ import io.github.wulkanowy.utils.LogUtils;
@Singleton
public class DbHelper extends DaoMaster.OpenHelper {
private SharedPrefContract sharedPref;
private final SharedPrefContract sharedPref;
private final Vulcan vulcan;
@Inject
DbHelper(@ApplicationContext Context context, @DatabaseInfo String dbName,
SharedPrefContract sharedPref) {
SharedPrefContract sharedPref, Vulcan vulcan) {
super(context, dbName);
this.sharedPref = sharedPref;
}
@Override
@SuppressWarnings("unchecked")
public void onUpgrade(Database db, int oldVersion, int newVersion) {
MigrationHelper.DEBUG = BuildConfig.DEBUG;
MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {
@Override
public void onCreateAllTables(Database db, boolean ifNotExists) {
DaoMaster.createAllTables(db, ifNotExists);
}
@Override
public void onDropAllTables(Database db, boolean ifExists) {
DaoMaster.dropAllTables(db, ifExists);
}
}, AccountDao.class, SubjectDao.class, GradeDao.class);
this.vulcan = vulcan;
}
@Override
@ -55,7 +44,49 @@ public class DbHelper extends DaoMaster.OpenHelper {
DaoMaster.dropAllTables(database, true);
onCreate(database);
sharedPref.setCurrentUserId(0);
LogUtils.info("Cleaning user data oldVersion=" + oldVersion + " newVersion=" + newVersion);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
List<Migration> migrations = getMigrations();
// Only run migrations past the old version
for (Migration migration : migrations) {
if (oldVersion < migration.getVersion()) {
try {
LogUtils.info("Applying migration to db schema v" + migration.getVersion() + "...");
migration.runMigration(db, sharedPref, vulcan);
LogUtils.info("Migration " + migration.getVersion() + " complete");
} catch (Exception e) {
e.printStackTrace();
DaoMaster.dropAllTables(db, true);
sharedPref.setCurrentUserId(0);
break;
}
}
}
}
private List<Migration> getMigrations() {
List<Migration> migrations = new ArrayList<>();
migrations.add(new Migration23());
// Sorting just to be safe, in case other people add migrations in the wrong order.
Comparator<Migration> migrationComparator = new Comparator<Migration>() {
@Override
public int compare(Migration m1, Migration m2) {
return m1.getVersion().compareTo(m2.getVersion());
}
};
Collections.sort(migrations, migrationComparator);
return migrations;
}
public interface Migration {
Integer getVersion();
void runMigration(Database db, SharedPrefContract sharedPref, Vulcan vulcan) throws Exception;
}
}

View File

@ -4,6 +4,8 @@ import org.greenrobot.greendao.DaoException;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Index;
import org.greenrobot.greendao.annotation.JoinProperty;
import org.greenrobot.greendao.annotation.Property;
import org.greenrobot.greendao.annotation.ToMany;
@ -18,20 +20,29 @@ public class Account {
@Id(autoincrement = true)
private Long id;
@Index(unique = true)
@Property(nameInDb = "REAL_ID")
private String realId;
@Property(nameInDb = "SYMBOL")
private String symbol;
@Property(nameInDb = "SCHOOL_ID")
private String schoolId;
@Property(nameInDb = "NAME")
private String name;
@Property(nameInDb = "E-MAIL")
@Property(nameInDb = "E_MAIL")
private String email;
@Property(nameInDb = "PASSWORD")
private String password;
@Property(nameInDb = "SYMBOL")
private String symbol;
@Property(nameInDb = "SNPID")
private String snpId;
@ToMany(joinProperties = {
@JoinProperty(name = "realId", referencedName = "studentId")
})
private List<Diary> diaryList;
@ToMany(referencedJoinProperty = "userId")
private List<Subject> subjectList;
@ -54,15 +65,16 @@ public class Account {
@Generated(hash = 335469827)
private transient AccountDao myDao;
@Generated(hash = 735765217)
public Account(Long id, String name, String email, String password, String symbol,
String snpId) {
@Generated(hash = 727721142)
public Account(Long id, String realId, String symbol, String schoolId, String name,
String email, String password) {
this.id = id;
this.realId = realId;
this.symbol = symbol;
this.schoolId = schoolId;
this.name = name;
this.email = email;
this.password = password;
this.symbol = symbol;
this.snpId = snpId;
}
@Generated(hash = 882125521)
@ -78,6 +90,15 @@ public class Account {
return this;
}
public String getRealId() {
return realId;
}
public Account setRealId(String realId) {
this.realId = realId;
return this;
}
public String getName() {
return name;
}
@ -114,15 +135,83 @@ public class Account {
return this;
}
public String getSnpId() {
return this.snpId;
public String getSchoolId() {
return schoolId;
}
public Account setSnpId(String snpId) {
this.snpId = snpId;
public Account setSchoolId(String schoolId) {
this.schoolId = schoolId;
return this;
}
public Account setDiaryList(List<Diary> diaryList) {
this.diaryList = diaryList;
return this;
}
public Account setSubjectList(List<Subject> subjectList) {
this.subjectList = subjectList;
return this;
}
public Account setGradeList(List<Grade> gradeList) {
this.gradeList = gradeList;
return this;
}
public Account setDayList(List<Day> dayList) {
this.dayList = dayList;
return this;
}
public DaoSession getDaoSession() {
return daoSession;
}
public Account setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
return this;
}
public AccountDao getMyDao() {
return myDao;
}
public Account setMyDao(AccountDao myDao) {
this.myDao = myDao;
return this;
}
/**
* To-many relationship, resolved on first access (and after reset).
* Changes to to-many relations are not persisted, make changes to the target entity.
*/
@Generated(hash = 1472214466)
public List<Diary> getDiaryList() {
if (diaryList == null) {
final DaoSession daoSession = this.daoSession;
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
DiaryDao targetDao = daoSession.getDiaryDao();
List<Diary> diaryListNew = targetDao._queryAccount_DiaryList(realId);
synchronized (this) {
if (diaryList == null) {
diaryList = diaryListNew;
}
}
}
return diaryList;
}
/**
* Resets a to-many relationship, making the next get call to query for a fresh result.
*/
@Generated(hash = 1078514341)
public synchronized void resetDiaryList() {
diaryList = null;
}
/**
* To-many relationship, resolved on first access (and after reset).
* Changes to to-many relations are not persisted, make changes to the target entity.
@ -183,6 +272,36 @@ public class Account {
gradeList = null;
}
/**
* To-many relationship, resolved on first access (and after reset).
* Changes to to-many relations are not persisted, make changes to the target entity.
*/
@Generated(hash = 300459794)
public List<Day> getDayList() {
if (dayList == null) {
final DaoSession daoSession = this.daoSession;
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
DayDao targetDao = daoSession.getDayDao();
List<Day> dayListNew = targetDao._queryAccount_DayList(id);
synchronized (this) {
if (dayList == null) {
dayList = dayListNew;
}
}
}
return dayList;
}
/**
* Resets a to-many relationship, making the next get call to query for a fresh result.
*/
@Generated(hash = 1010399236)
public synchronized void resetDayList() {
dayList = null;
}
/**
* Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}.
* Entity must attached to an entity context.
@ -219,36 +338,6 @@ public class Account {
myDao.update(this);
}
/**
* To-many relationship, resolved on first access (and after reset).
* Changes to to-many relations are not persisted, make changes to the target entity.
*/
@Generated(hash = 300459794)
public List<Day> getDayList() {
if (dayList == null) {
final DaoSession daoSession = this.daoSession;
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
DayDao targetDao = daoSession.getDayDao();
List<Day> dayListNew = targetDao._queryAccount_DayList(id);
synchronized (this) {
if (dayList == null) {
dayList = dayListNew;
}
}
}
return dayList;
}
/**
* Resets a to-many relationship, making the next get call to query for a fresh result.
*/
@Generated(hash = 1010399236)
public synchronized void resetDayList() {
dayList = null;
}
/** called by internal mechanisms, do not call yourself. */
@Generated(hash = 1812283172)
public void __setDaoSession(DaoSession daoSession) {

View File

@ -0,0 +1,161 @@
package io.github.wulkanowy.data.db.dao.entities;
import org.greenrobot.greendao.DaoException;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;
@Entity(
nameInDb = "Diaries",
active = true
)
public class Diary {
@Id(autoincrement = true)
private Long id;
@Property(nameInDb = "STUDENT_ID")
private String studentId;
@Property(nameInDb = "NAME")
private String name;
@Property(nameInDb = "VALUE")
private String value;
@Property(nameInDb = "IS_CURRENT")
private boolean isCurrent;
/**
* Used to resolve relations
*/
@Generated(hash = 2040040024)
private transient DaoSession daoSession;
/**
* Used for active entity operations.
*/
@Generated(hash = 21166549)
private transient DiaryDao myDao;
@Generated(hash = 459332202)
public Diary(Long id, String studentId, String name, String value,
boolean isCurrent) {
this.id = id;
this.studentId = studentId;
this.name = name;
this.value = value;
this.isCurrent = isCurrent;
}
@Generated(hash = 112123061)
public Diary() {
}
public Long getId() {
return id;
}
public Diary setId(Long id) {
this.id = id;
return this;
}
public String getStudentId() {
return studentId;
}
public Diary setStudentId(String studentId) {
this.studentId = studentId;
return this;
}
public String getName() {
return name;
}
public Diary setName(String name) {
this.name = name;
return this;
}
public String getValue() {
return value;
}
public Diary setValue(String value) {
this.value = value;
return this;
}
public boolean getIsCurrent() {
return isCurrent;
}
public Diary setIsCurrent(boolean current) {
isCurrent = current;
return this;
}
public DaoSession getDaoSession() {
return daoSession;
}
public Diary setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
return this;
}
public DiaryDao getMyDao() {
return myDao;
}
public Diary setMyDao(DiaryDao myDao) {
this.myDao = myDao;
return this;
}
/**
* Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}.
* Entity must attached to an entity context.
*/
@Generated(hash = 128553479)
public void delete() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.delete(this);
}
/**
* Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}.
* Entity must attached to an entity context.
*/
@Generated(hash = 1942392019)
public void refresh() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.refresh(this);
}
/**
* Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}.
* Entity must attached to an entity context.
*/
@Generated(hash = 713229351)
public void update() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.update(this);
}
/** called by internal mechanisms, do not call yourself. */
@Generated(hash = 629297785)
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getDiaryDao() : null;
}
}

View File

@ -0,0 +1,114 @@
package io.github.wulkanowy.data.db.dao.migrations;
import android.database.Cursor;
import android.os.AsyncTask;
import org.greenrobot.greendao.database.Database;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.github.wulkanowy.api.Diary;
import io.github.wulkanowy.api.Vulcan;
import io.github.wulkanowy.data.db.dao.DbHelper;
import io.github.wulkanowy.data.db.shared.SharedPrefContract;
import io.github.wulkanowy.utils.security.Scrambler;
public class Migration23 implements DbHelper.Migration {
@Override
public Integer getVersion() {
return 23;
}
@Override
public void runMigration(final Database db, final SharedPrefContract sharedPref, final Vulcan vulcan) throws Exception {
createDiaryTable(db);
migrateAccountsTable(db);
final Map<String, String> user = getAccountData(db);
vulcan.setCredentials(
user.get("email"),
Scrambler.decrypt(user.get("email"), user.get("password")),
user.get("symbol"),
user.get("school_id"),
"", // inserted in code bellow
""
);
AsyncTask.execute(new Runnable() {
@Override
public void run() {
try {
insertDiaries(db, vulcan.getStudentAndParent().getDiaries());
updateAccount(db, vulcan.getStudentAndParent().getStudentID());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void createDiaryTable(Database db) {
db.execSQL("DROP TABLE IF EXISTS Diaries");
db.execSQL("CREATE TABLE IF NOT EXISTS \"Diaries\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"STUDENT_ID\" TEXT," + // 1: studentId
"\"NAME\" TEXT," + // 2: name
"\"VALUE\" TEXT," + // 3: value
"\"IS_CURRENT\" INTEGER NOT NULL );"); // 4: isCurrent
}
private void migrateAccountsTable(Database db) {
db.execSQL("DROP TABLE IF EXISTS tmp_account");
db.execSQL("ALTER TABLE Accounts RENAME TO tmp_account");
db.execSQL("CREATE TABLE IF NOT EXISTS \"Accounts\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"REAL_ID\" TEXT," + // 1: realId
"\"SYMBOL\" TEXT," + // 2: symbol
"\"SCHOOL_ID\" TEXT," + // 3: schoolId
"\"NAME\" TEXT," + // 4: name
"\"E_MAIL\" TEXT," + // 5: email
"\"PASSWORD\" TEXT);"); // 6: password
// Add Indexes
db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS IDX_Accounts_REAL_ID ON \"Accounts\" (\"REAL_ID\" ASC);");
db.execSQL("INSERT INTO Accounts(NAME, E_MAIL, PASSWORD, SYMBOL, SCHOOL_ID)" +
"SELECT `NAME`, `E-MAIL`, `PASSWORD`, `SYMBOL`, `SNPID` FROM tmp_account");
db.execSQL("DROP TABLE tmp_account");
}
private Map<String, String> getAccountData(Database db) {
Map<String, String> values = new HashMap<>();
Cursor cursor = db.rawQuery("SELECT SYMBOL, SCHOOL_ID, NAME, E_MAIL, PASSWORD FROM Accounts", null);
if (cursor.moveToFirst()) {
do {
values.put("symbol", cursor.getString(cursor.getColumnIndex("SYMBOL")));
values.put("school_id", cursor.getString(cursor.getColumnIndex("SCHOOL_ID")));
values.put("name", cursor.getString(cursor.getColumnIndex("NAME")));
values.put("email", cursor.getString(cursor.getColumnIndex("E_MAIL")));
values.put("password", cursor.getString(cursor.getColumnIndex("PASSWORD")));
} while (cursor.moveToNext());
}
cursor.close();
return values;
}
private void insertDiaries(Database db, List<Diary> list) {
for (Diary diary : list) {
db.execSQL("INSERT INTO Diaries(STUDENT_ID, NAME, VALUE, IS_CURRENT) VALUES(" +
"\"" + diary.getStudentId() + "\"," +
"\"" + diary.getName() + "\"," +
"\"" + diary.getId() + "\"," +
"\"" + (diary.isCurrent() ? "1" : "0") + "\"" +
")");
}
}
private void updateAccount(Database db, String realId) {
db.execSQL("UPDATE Accounts SET REAL_ID = ?", new String[]{realId});
}
}

View File

@ -3,6 +3,9 @@ package io.github.wulkanowy.data.sync.account;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
@ -11,8 +14,11 @@ import io.github.wulkanowy.api.Vulcan;
import io.github.wulkanowy.api.VulcanException;
import io.github.wulkanowy.data.db.dao.entities.Account;
import io.github.wulkanowy.data.db.dao.entities.DaoSession;
import io.github.wulkanowy.data.db.dao.entities.Diary;
import io.github.wulkanowy.data.db.dao.entities.DiaryDao;
import io.github.wulkanowy.data.db.shared.SharedPrefContract;
import io.github.wulkanowy.di.annotations.ApplicationContext;
import io.github.wulkanowy.utils.DataObjectConverter;
import io.github.wulkanowy.utils.LogUtils;
import io.github.wulkanowy.utils.security.CryptoException;
import io.github.wulkanowy.utils.security.Scrambler;
@ -43,22 +49,27 @@ public class AccountSync implements AccountSyncContract {
LogUtils.debug("Register new user email=" + email);
vulcan.setCredentials(email, password, symbol, null);
vulcan.setCredentials(email, password, symbol, null, null, null);
Account account = new Account()
.setName(vulcan.getBasicInformation().getPersonalData().getFirstAndLastName())
.setEmail(email)
.setPassword(Scrambler.encrypt(email, password, context))
.setSymbol(vulcan.getSymbol())
.setSnpId(vulcan.getStudentAndParent().getId());
.setSchoolId(vulcan.getStudentAndParent().getSchoolID())
.setRealId(vulcan.getStudentAndParent().getStudentID());
List<Diary> diaryList = DataObjectConverter.diariesToDiaryEntities(
vulcan.getStudentAndParent().getDiaries());
daoSession.getAccountDao().insert(account);
daoSession.getDiaryDao().insertInTx(diaryList);
sharedPref.setCurrentUserId(account.getId());
}
@Override
public void initLastUser() throws VulcanException, IOException, CryptoException {
public void initLastUser() throws IOException, CryptoException {
long userId = sharedPref.getCurrentUserId();
@ -73,6 +84,10 @@ public class AccountSync implements AccountSyncContract {
vulcan.setCredentials(account.getEmail(),
Scrambler.decrypt(account.getEmail(), account.getPassword()),
account.getSymbol(),
account.getSnpId());
account.getSchoolId(),
account.getRealId(),
daoSession.getDiaryDao().queryBuilder()
.where(DiaryDao.Properties.IsCurrent.eq(true)).unique().getValue()
);
}
}

View File

@ -6,6 +6,7 @@ import java.util.List;
import io.github.wulkanowy.data.db.dao.entities.AttendanceLesson;
import io.github.wulkanowy.data.db.dao.entities.Day;
import io.github.wulkanowy.data.db.dao.entities.Diary;
import io.github.wulkanowy.data.db.dao.entities.Grade;
import io.github.wulkanowy.data.db.dao.entities.Subject;
import io.github.wulkanowy.data.db.dao.entities.TimetableLesson;
@ -17,8 +18,22 @@ public final class DataObjectConverter {
throw new IllegalStateException("Utility class");
}
public static List<Subject> subjectsToSubjectEntities(List<io.github.wulkanowy.api.grades.Subject> subjectList) {
public static List<Diary> diariesToDiaryEntities(List<io.github.wulkanowy.api.Diary> diaryList) {
List<Diary> diaryEntityList = new ArrayList<>();
for (io.github.wulkanowy.api.Diary diary : diaryList) {
Diary diaryEntity = new Diary()
.setValue(diary.getId())
.setName(diary.getName())
.setStudentId(diary.getStudentId())
.setIsCurrent(diary.isCurrent());
diaryEntityList.add(diaryEntity);
}
return diaryEntityList;
}
public static List<Subject> subjectsToSubjectEntities(List<io.github.wulkanowy.api.grades.Subject> subjectList) {
List<Subject> subjectEntityList = new ArrayList<>();
for (io.github.wulkanowy.api.grades.Subject subject : subjectList) {
@ -33,7 +48,6 @@ public final class DataObjectConverter {
}
public static List<Grade> gradesToGradeEntities(List<io.github.wulkanowy.api.grades.Grade> gradeList) {
List<Grade> gradeEntityList = new ArrayList<>();
for (io.github.wulkanowy.api.grades.Grade grade : gradeList) {
@ -67,7 +81,6 @@ public final class DataObjectConverter {
public static List<Day> daysToDaysEntities(List<io.github.wulkanowy.api.generic.Day> dayList) {
List<Day> dayEntityList = new ArrayList<>();
for (io.github.wulkanowy.api.generic.Day day : dayList) {
@ -110,7 +123,6 @@ public final class DataObjectConverter {
}
public static List<TimetableLesson> lessonsToTimetableLessonsEntities(List<io.github.wulkanowy.api.generic.Lesson> lessonList) {
List<TimetableLesson> lessonEntityList = new ArrayList<>();
for (io.github.wulkanowy.api.generic.Lesson lesson : lessonList) {
@ -120,7 +132,6 @@ public final class DataObjectConverter {
}
public static List<AttendanceLesson> lessonsToAttendanceLessonsEntities(List<io.github.wulkanowy.api.generic.Lesson> lessonList) {
List<AttendanceLesson> lessonEntityList = new ArrayList<>();
for (io.github.wulkanowy.api.generic.Lesson lesson : lessonList) {