2
0
mirror of https://github.com/inventree/inventree-app.git synced 2025-04-27 21:16:48 +00:00

Make the API a singleton class

Also add some simple URL validation
This commit is contained in:
Oliver Walters 2019-06-25 22:38:11 +10:00
parent 6b58ccb844
commit 6e807cbed1
2 changed files with 54 additions and 7 deletions

View File

@ -6,14 +6,47 @@ import 'package:path/path.dart' as path;
import 'package:http/http.dart' as http;
class InventreeAPI {
class InvenTreeAPI {
InventreeAPI(this._username, this._password) {
_secureToken();
// Ensure we only ever create a single instance of the API class
static final InvenTreeAPI _api = new InvenTreeAPI._internal();
factory InvenTreeAPI() {
return _api;
}
InvenTreeAPI._internal();
void connect(String address, String username, String password) async {
address = address.trim();
username = username.trim();
if (!address.endsWith("api/") || !address.endsWith("api")) {
address = path.join(address, "api");
}
if (!address.endsWith('/')) {
address = address + '/';
}
_base_url = address;
_username = username;
_password = password;
_connected = false;
print("Connecting to " + address + " -> " + username + ":" + password);
await _tryConnection();
await _secureToken();
}
bool _connected = false;
// Base URL for InvenTree API
String _base_url = "http://10.0.0.7:8000/api/";
String _base_url = "http://127.0.0.1:8000/api/";
String _username = "";
String _password = "";
@ -30,9 +63,18 @@ class InventreeAPI {
return _token.isNotEmpty;
}
// Request the raw /api/ endpoing to see if there is an InvenTree server listening
void _tryConnection() async {
final response = get("");
}
// Request an API token from the server.
// A valid username/password combination must be provided
void _secureToken() async {
if (_token.isNotEmpty) {
print("Discarding old token - " + _token);
}
_token = "";
var _url = _makeUrl("user/token/");

View File

@ -1,6 +1,8 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'api.dart';
class InvenTreeLoginSettingsWidget extends StatefulWidget {
@override
@ -22,6 +24,10 @@ class _InvenTreeLoginSettingsState extends State<InvenTreeLoginSettingsWidget> {
return 'Server cannot be empty';
}
if (!value.startsWith("http:") && !value.startsWith("https:")) {
return 'Server must start with http[s]';
}
return null;
}
@ -48,9 +54,6 @@ class _InvenTreeLoginSettingsState extends State<InvenTreeLoginSettingsWidget> {
@override
Widget build(BuildContext context) {
print("here we are");
print("Server: " + _addr);
final Size screenSize = MediaQuery.of(context).size;
@ -135,6 +138,8 @@ class _InvenTreeLoginSettingsState extends State<InvenTreeLoginSettingsWidget> {
await prefs.setString('server', _addr);
await prefs.setString('username', _user);
await prefs.setString('password', _pass);
InvenTreeAPI().connect(_addr, _user, _pass);
}
}
}