고원빈

[frontend] login authorization 문제 해결

......@@ -82,3 +82,5 @@ appbar 관련 디자인은 추후 구현 예정
+ 메인 페이지 데이터 출력 완료
### 2021-05-25
+ 로그인 권한 문제 해결
\ No newline at end of file
......
......@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:intl/intl.dart';
import 'models/Bottle.dart';
import 'models/Medicine.dart';
......@@ -28,6 +29,7 @@ class _DashBoardState extends State<DashBoard> {
Bottle _bottleinformation = new Bottle();
int _selectedIndex = 0;
Medicine _medicineInformation = new Medicine();
Widget build(BuildContext context) {
_selectedIndex = widget.pageNumber;
_medicineInformation = widget.medicineInformation;
......@@ -125,17 +127,6 @@ class _DashBoardState extends State<DashBoard> {
}
Widget mainpage(BuildContext context, Medicine medicineInformation) {
Future<String> getHubList() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
http.Response response =
await http.get(Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'));
print(response.statusCode);
}
//현재 접속 중인 허브 리스트 id와 약병 리스트 id 출력
//약 상세 정보 가져오기 --> 이건 Detail Medicine에서 가져 오면 됨
final Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.white,
......@@ -578,7 +569,8 @@ Widget ineerInformationpage(BuildContext context, Bottle bottleinformation) {
child: Text(
bottleinformation.recentOpen == null
? '-'
: bottleinformation.recentOpen,
: DateFormat.Hm()
.format(bottleinformation.recentOpen),
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
......@@ -676,9 +668,9 @@ Widget outerInformationpage(BuildContext context, Bottle bottleinformation) {
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
bottleinformation.toString() == null
bottleinformation.dosage == null
? '-'
: bottleinformation.toString(),
: bottleinformation.dosage.toString(),
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
......
......@@ -6,6 +6,7 @@ import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/Bottle.dart';
import '../DashBoard.dart';
import '../models/Medicine.dart';
import '../../utils/user_secure_stoarge.dart';
class BottleList extends StatefulWidget {
List<Bottle> bottlelist;
......@@ -21,10 +22,12 @@ class _BottleListState extends State<BottleList> {
Medicine _medicineinformation = new Medicine();
Future<Bottle> getbottle(int index) async {
http.Response response = await http.get(Uri.encodeFull(
DotEnv().env['SERVER_URL'] +
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.get(
Uri.encodeFull(DotEnv().env['SERVER_URL'] +
'bottle/' +
widget.bottlelist[index].bottleId.toString()));
widget.bottlelist[index].bottleId.toString()),
headers: {"authorization": usertoken});
if (response.statusCode == 200) {
Map<String, dynamic> jsonData = jsonDecode(response.body);
......@@ -34,10 +37,13 @@ class _BottleListState extends State<BottleList> {
}
Future<Bottle> getmedicine(int index) async {
http.Response medicineresponse = await http.get(Uri.encodeFull(
DotEnv().env['SERVER_URL'] +
'medicine/' +
widget.bottlelist[index].medicineId.toString()));
String usertoken = await UserSecureStorage.getUserToken();
http.Response medicineresponse = await http.get(
Uri.encodeFull(DotEnv().env['SERVER_URL'] +
'medicine/' +
widget.bottlelist[index].medicineId.toString()),
headers: {"authorization": usertoken},
);
if (medicineresponse.statusCode == 200) {
Map<String, dynamic> data = jsonDecode(medicineresponse.body);
_medicineinformation = Medicine.fromJson(data);
......@@ -80,32 +86,31 @@ class _BottleListState extends State<BottleList> {
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(border: Border.all()),
child: ListTile(
title: Text(
'BOTTLE ID : ' +
'${widget.bottlelist[index].bottleId}',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
trailing: Icon(Icons.arrow_forward),
onTap: () async {
getbottle(index);
getmedicine(index);
print(_bottleinformation);
print(_medicineinformation);
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => DashBoard(
pageNumber: 1,
bottleInformation: _bottleinformation,
medicineInformation: _medicineinformation,
),
));
}),
title: Text(
'BOTTLE ID : ' +
'${widget.bottlelist[index].bottleId}',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
trailing: Icon(Icons.arrow_forward),
onTap: () async {
await getbottle(index);
await getmedicine(index);
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => DashBoard(
pageNumber: 1,
bottleInformation: _bottleinformation,
medicineInformation: _medicineinformation,
),
),
);
},
),
);
},
separatorBuilder: (BuildContext contetx, int index) =>
......
......@@ -6,6 +6,7 @@ import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/Medicine.dart';
import '../../utils/user_secure_stoarge.dart';
class DetailMedicine extends StatefulWidget {
Medicine searchMedicine;
......@@ -20,10 +21,14 @@ class _DetailMedicineState extends State<DetailMedicine> {
final medicineDosageController = TextEditingController();
//약 등록
Future<String> patchMedcine() async {
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.patch(
Uri.encodeFull(
DotEnv().env['SERVER_URL'] + 'bottle/' + widget.bottleId),
headers: {"Content-Type": "application/json"},
headers: {
"Content-Type": "application/json",
"authorization": usertoken
},
body: jsonEncode({
'medicineId': widget.searchMedicine.medicineId,
'dosage': medicineDosageController.text
......
......@@ -7,6 +7,7 @@ import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'RegisterBottle.dart';
import '../models/Bottle.dart';
import 'BottleList.dart';
import '../../utils/user_secure_stoarge.dart';
class HubList extends StatefulWidget {
List<int> hublist;
......@@ -20,8 +21,13 @@ class _HubListState extends State<HubList> {
List<Bottle> _bottleList = new List<Bottle>();
//Get BottleList
Future<String> getBottleList(int hubid) async {
http.Response response = await http.get(Uri.encodeFull(
DotEnv().env['SERVER_URL'] + 'bottle/hub/' + hubid.toString()));
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.get(
Uri.encodeFull(
DotEnv().env['SERVER_URL'] + 'bottle/hub/' + hubid.toString()),
headers: {"authorization": usertoken},
);
print(response.body);
if (_bottleList.length != 0) {
_bottleList.clear();
}
......
......@@ -6,6 +6,7 @@ import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'SearchMedicine.dart';
import '../../utils/user_secure_stoarge.dart';
class RegisterBottle extends StatefulWidget {
final String hubid;
......@@ -18,9 +19,13 @@ class _RegisterBottleState extends State<RegisterBottle> {
final medicineBottleIDController = TextEditingController();
Future<String> registerhub_Validate() async {
String usertoken = await UserSecureStorage.getUserToken();
http.Response bottleresponse = await http.post(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle'),
headers: {"Content-Type": "application/json"},
headers: {
"Content-Type": "application/json",
"authorization": usertoken
},
body: jsonEncode({
'bottleId': medicineBottleIDController.text,
'hubId': widget.hubid
......
......@@ -5,6 +5,7 @@ import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'RegisterBottle.dart';
import '../../utils/user_secure_stoarge.dart';
class RegisterHub extends StatefulWidget {
@override
......@@ -18,14 +19,18 @@ class _RegisterHubState extends State<RegisterHub> {
final medicineHubHostController = TextEditingController();
Future<String> registerhub_Validate() async {
http.Response hubresponse =
await http.post(Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'),
headers: {"Content-Type": "application/json"},
body: jsonEncode({
'hubId': medicineHubIDController.text,
'host': medicineHubHostController.text,
'port': medicineHubPortController.text,
}));
String usertoken = await UserSecureStorage.getUserToken();
http.Response hubresponse = await http.post(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'),
headers: {
"Content-Type": "application/json",
"authorization": usertoken
},
body: jsonEncode({
'hubId': medicineHubIDController.text,
'host': medicineHubHostController.text,
'port': medicineHubPortController.text,
}));
if (hubresponse.statusCode == 201) {
return "허브 등록 완료";
......
......@@ -5,6 +5,7 @@ import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/Medicine.dart';
import 'DetailMedicine.dart';
import '../../utils/user_secure_stoarge.dart';
class SearchMedicine extends StatefulWidget {
String bottleId;
......@@ -19,13 +20,17 @@ class _SearchMedicineState extends State<SearchMedicine> {
final medicineCompanyController = TextEditingController();
Future<String> postMeicineList() async {
http.Response response =
await http.post(Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'medicine'),
headers: {"Content-Type": "application/json"},
body: jsonEncode({
'name': medicineNameController.text,
'company': medicineCompanyController.text,
}));
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.post(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'medicine'),
headers: {
"Content-Type": "application/json",
"authorization": usertoken
},
body: jsonEncode({
'name': medicineNameController.text,
'company': medicineCompanyController.text,
}));
if (_medicineList.length != 0) {
_medicineList.clear();
......
......@@ -3,10 +3,11 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../DashBoard.dart';
import '../../utils/user_secure_stoarge.dart';
import 'HubList.dart';
import 'RegsiterHub.dart';
import '../models/User.dart';
class SignInPage extends StatefulWidget {
@override
......@@ -18,22 +19,30 @@ class _SignInPageState extends State<SignInPage> {
bool passwordVisible = false;
bool _validateEmail = false;
bool _validatePassword = false;
final emailController = TextEditingController();
final passwordController = TextEditingController();
User user;
List<int> _hublist = new List<int>(); //허브이름을 만들어야 할 것 같은데 임시로 허브 id만 고르게 함
//Login 함수
Future<String> login(String _email, String _password) async {
http.Response response = await http.post(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'auth/login'),
headers: {"Content-Type": "application/json"},
body: jsonEncode({
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'auth/login'),
headers: {"Content-Type": "application/json"},
body: jsonEncode(
{
'userId': _email,
'password': _password,
}));
},
),
);
if (response.statusCode == 200) {
Map<String, dynamic> data = jsonDecode(response.body);
user = User.fromJson(data);
print(user);
return "로그인 성공";
} else if (response.statusCode == 400) {
return "올바르지 않은 아이디 및 패스워드";
......@@ -44,11 +53,14 @@ class _SignInPageState extends State<SignInPage> {
//Get Bottle List 함수
Future<String> getHubList() async {
http.Response response =
await http.get(Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'));
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.get(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'),
headers: {"authorization": usertoken},
);
List<dynamic> values = new List<dynamic>();
print(values);
if (_hublist.length != 0) {
_hublist.clear();
}
......@@ -228,6 +240,8 @@ class _SignInPageState extends State<SignInPage> {
RegisterHub(),
));
} else if (result == "get완료") {
UserSecureStorage.setUserToken(
user.token);
Navigator.push(
context,
MaterialPageRoute(
......
......@@ -3,7 +3,7 @@ class Bottle {
final int temperature;
final int humidity;
final int balance;
final String recentOpen;
final DateTime recentOpen;
final int medicineId;
final int hubId;
final int dosage;
......@@ -24,7 +24,7 @@ class Bottle {
temperature: parsedJson['temperature'],
humidity: parsedJson['humidity'],
balance: parsedJson['balance'],
recentOpen: parsedJson['recentOpen'],
recentOpen: DateTime.parse(parsedJson['recentOpen']),
medicineId: parsedJson['medicineId'],
hubId: parsedJson['hubId'],
dosage: parsedJson['dosage'],
......
class User {
final String userId;
final String token;
User({this.userId, this.token});
factory User.fromJson(Map<String, dynamic> parsedJson) {
return User(
userId: parsedJson['userId'],
token: parsedJson['token'],
);
}
Map<String, dynamic> toJson() => {
"userId": userId,
"token": token,
};
}
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class UserSecureStorage {
static final _storage = FlutterSecureStorage();
static const _keyToken = 'usertoken';
static const _keyUserId = 'userid';
static Future setUserId(String userid) async =>
await _storage.write(key: _keyUserId, value: userid);
static Future<String> getUserID() async =>
await _storage.read(key: _keyUserId);
static Future setUserToken(String userToken) async =>
await _storage.write(key: _keyToken, value: userToken);
static Future<String> getUserToken() async =>
await _storage.read(key: _keyToken);
}
......@@ -132,6 +132,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "0.7.0"
flutter_secure_storage:
dependency: "direct main"
description:
name: flutter_secure_storage
url: "https://pub.dartlang.org"
source: hosted
version: "3.3.5"
flutter_test:
dependency: "direct dev"
description: flutter
......@@ -415,4 +422,4 @@ packages:
version: "0.1.2"
sdks:
dart: ">=2.10.0-110 <2.11.0"
flutter: ">=1.12.13+hotfix.6 <2.0.0"
flutter: ">=1.20.0 <2.0.0"
......
......@@ -38,6 +38,7 @@ dependencies:
http: ^0.12.0+4
flutter_dotenv: ^2.1.0
numberpicker: ^1.3.0
flutter_secure_storage: ^3.3.5
dev_dependencies:
flutter_test:
......