Перенес хранение информации о сессии (токен, din, posid) в базу данных

This commit is contained in:
Ivan Murashov
2017-09-06 17:19:11 +03:00
parent 60090ea437
commit 569c69e268
9 changed files with 162 additions and 127 deletions

View File

@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:intl/intl.dart';
import 'dart:async';
@@ -9,7 +10,7 @@ import 'network.dart';
import 'consts.dart';
import 'registration.dart';
import 'finish_registration.dart';
import 'strings.dart';
import 'db.dart';
class SplashScreen extends StatelessWidget {
@@ -18,7 +19,7 @@ class SplashScreen extends StatelessWidget {
// Появляется splash screen, проверяется токен.
new Future.delayed(const Duration(milliseconds: 500), () {
platform.invokeMethod("getLocale").then((locale) {
platform.invokeMethod('getLocale').then((locale) {
Intl.defaultLocale = locale;
print(Intl.defaultLocale);
showNextScreen(context);
@@ -49,19 +50,24 @@ class SplashScreen extends StatelessWidget {
/// Запуск следующего экрана приложения.
showNextScreen(BuildContext context) async {
String token = await platform.invokeMethod('getToken');
SqliteHelper helper = new SqliteHelper();
await helper.open();
String token = await helper.getToken();
// В случае, если в приложении отсутствует токен,
// необходимо запустить регистрацию кассы.
if (token == null) {
await helper.close();
pushRoute(context, new RegistrationScreen());
} else {
if (await platform.invokeMethod('isOnline')) {
checkTokenStatus(token).then((statusResponse) {
handleStatusResponse(context, statusResponse);
handleStatusResponse(context, statusResponse, helper);
}).catchError((error) {
print(error.toString());
return false;
helper.close().then((_) {
print(error.toString());
return false;
});
});
}
}
@@ -70,14 +76,15 @@ class SplashScreen extends StatelessWidget {
/// Обработка ответа.
/// В случае, если токен был удален может прийти active: false, либо 404.
/// Если токен не активен, попробовать создать его еще раз.
handleStatusResponse(BuildContext context, var statusResponse) async {
handleStatusResponse(BuildContext context, var statusResponse, SqliteHelper helper) async {
int code = statusResponse.statusCode;
print('resp: ${code}');
if (code == 404) {
platform.invokeMethod('removeKeys').then((result) {
print('try to start registration');
pushRoute(context, new RegistrationScreen());
helper.clear().then((result) {
helper.close().then((_) {
pushRoute(context, new RegistrationScreen());
});
});
} else {
@@ -88,7 +95,7 @@ class SplashScreen extends StatelessWidget {
startScanner(context);
} else {
if (await platform.invokeMethod('isOnline')) {
_createToken(context);
_createToken(context, helper);
}
}
}
@@ -101,24 +108,34 @@ class SplashScreen extends StatelessWidget {
///
/// Если вернулся код 200, значит токен был ранее удален и только что снова создался.
/// Нужно удалить его и направить пользователя на экран регистрации.
_createToken(BuildContext ctx) async {
String merchantID = await platform.invokeMethod('getMerchantID');
String posID = await platform.invokeMethod('getPosID');
_createToken(BuildContext ctx, SqliteHelper helper) async {
String merchantID = await helper.getMerchantID();
String posID = await helper.getPosID();
createToken(merchantID, posID).then((response) {
if (response.statusCode == 409) {
helper.close();
pushRoute(ctx, new FinishRegistrationScreen());
} else if (response.statusCode == 201) {
platform.invokeMethod('removeKeys').then((result) {
Map parsedMap = JSON.decode(result);
deleteToken(parsedMap['token']).then((response) {
print(response.body);
Navigator.of(ctx).pop(); // Убираем текущий route
pushRoute(ctx, new RegistrationScreen()); // Запускаем регистрацию
}).catchError((error) {
print(error.toString());
});
});
clearToken(response, ctx, helper);
}
}).catchError((error) => print(error.toString()));
}
/// Очищаем бд, делаем запрос на удаление токена.
void clearToken(Response response, BuildContext ctx, SqliteHelper helper) {
helper.clear().then((_) {
Map parsedMap = JSON.decode(response.body);
deleteToken(parsedMap['token']).then((_) {
helper.close();
Navigator.of(ctx).pop(); // Убираем текущий route
pushRoute(ctx, new RegistrationScreen()); // Запускаем регистрацию
}).catchError((error) {
helper.close();
print(error.toString());
});
});
}
}