astronote/lib/services/log_in_services.dart
2020-08-06 16:25:47 +02:00

64 lines
1.8 KiB
Dart

import 'dart:convert';
import 'package:astronote_app/models/user_datas.dart';
import 'package:astronote_app/models/credential.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
class LogIn with ChangeNotifier {
String _cookie;
Credential _userCredentials;
bool get isLog {
return token != null;
}
String get token {
if (_cookie != null) {
return _cookie;
}
return null;
}
Future<void> logIn(String url, String login, String password) async {
String urlApi = url + '/api/v1/login';
Map<String, String> headers = {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
};
var body = json.encode({"login": login, "password": password});
final response = await http.post(urlApi, headers: headers, body: body);
if (response.statusCode == 200) {
// If the server did return a 20 0 OK response,
_cookie = response.headers['set-cookie'];
_userCredentials = new Credential(url: url, login: login, password: password);
print(_userCredentials.toString());
return recoverUserDatas(urlApi);
} else{
_cookie = null;
_userCredentials = null;
}
notifyListeners();
}
Future<void> recoverUserDatas(String url) async {
Map<String, String> headers = {
"X-Requested-With": "XMLHttpRequest",
"Cookie": _cookie
};
final response = await http.get(url, headers: headers);
if (response.statusCode == 200) {
// If the server did return a 200 OK response then parse the JSON.
final responseJson = json.decode(response.body);
UserDatas userDatas = new UserDatas.fromJson(responseJson['datas']);
print(userDatas.companies[0].toString());
}
}
}