Fix connection.

This commit is contained in:
sfigato 2019-08-30 01:29:15 +02:00
parent b677865c21
commit 1e976224cb
Signed by: blallo
GPG Key ID: 0CBE577C9B72DC3F

View File

@ -2,7 +2,6 @@ import 'package:http/http.dart';
import 'package:logger/logger.dart';
import 'dart:convert';
final log = Logger();
const defaultRoutes = {
"login": "/api/login",
@ -14,10 +13,10 @@ const defaultRoutes = {
"ping": "/api/ping",
};
class Connection {
// Connection constructor.
Connection(this.username, this.password, this.baseAddress, [this.routes = defaultRoutes]);
Connection(this.username, this.password, this.baseAddress,
[this.routes = defaultRoutes]);
// baseAddress contains the base address to the BotZ server
final Uri baseAddress;
// Username is the username to autenticate against the foreign
@ -42,10 +41,11 @@ class Connection {
bool isLoggedIn() => this._loggedIn;
// FIXME: THIS IS WRONG! We might be yet checked in.
bool isCheckedIn() => this._checkedIn;
// Perform the login and obtain the cookie.
void login() async {
Future<void> login() async {
var targetUri = this.baseAddress.toString() + this.routes['login'];
var payload = jsonEncode({
"username": this.username,
@ -62,16 +62,20 @@ class Connection {
handleResponse(resp);
var body = jsonDecode(resp.body);
log.d("[login] Response: $body");
this.updateState(resp.headers['cookies'], body['logged_in']);
var rawCookie = resp.headers['set-cookie'];
if (rawCookie == null) {
rawCookie = resp.headers['cookie'];
}
this.updateState(rawCookie, body['logged_in']);
}
// Perform the logout.
void logout() async {
Future<void> logout() async {
var targetUri = this.baseAddress.toString() + this.routes['logout'];
var resp = await post(
targetUri,
headers: {'cookies': this._cookies},
headers: {'cookie': this._cookies},
);
log.d("[logout] Post sent to: $targetUri");
@ -82,7 +86,7 @@ class Connection {
}
// Perform the checkin if possible.
void checkin() async {
Future<void> checkin() async {
if (!this._loggedIn) {
throw UnacceptableInvocationException("Not logged in");
}
@ -103,7 +107,7 @@ class Connection {
}
// Perform the checkout if possible.
void checkout() async {
Future<void> checkout() async {
if (!this._loggedIn) {
throw UnacceptableInvocationException("Not logged in");
}
@ -152,27 +156,23 @@ class Connection {
}
}
class UnauthorizedException implements ClientException {
UnauthorizedException(this.uri);
final String message = "Unauthorized";
final Uri uri;
}
class NotFoundException implements ClientException {
NotFoundException(this.uri);
final String message = "Resource not found";
final Uri uri;
}
class UnacceptableInvocationException implements Exception {
UnacceptableInvocationException(this.message);
final String message;
}
Response handleResponse(Response resp) {
final c = resp.statusCode;
if (c >= 200 && c < 400) {