Base user workflow (create/update)
This commit is contained in:
parent
eb5d3e2b70
commit
45be2c80ff
8 changed files with 528 additions and 17 deletions
|
|
@ -6,6 +6,7 @@ import 'package:http/browser_client.dart';
|
|||
import 'package:http/http.dart';
|
||||
import 'package:tuuli_app/api/model/table_field_model.dart';
|
||||
import 'package:tuuli_app/api/model/tables_list_model.dart';
|
||||
import 'package:tuuli_app/api/model/user_model.dart';
|
||||
|
||||
class ErrorOrData<T> {
|
||||
final T? data;
|
||||
|
|
@ -292,6 +293,69 @@ class ApiClient {
|
|||
return ErrorOrData(ignored, error);
|
||||
}
|
||||
|
||||
FutureErrorOrData<bool> createUser(
|
||||
TableModel table, String username, String password) async {
|
||||
bool? ignored;
|
||||
Exception? error;
|
||||
|
||||
final response = await post(
|
||||
'/api/createUser',
|
||||
body: {
|
||||
"username": username,
|
||||
"password": password,
|
||||
},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
final body = json.decode(await response.stream.bytesToString());
|
||||
if (body['error'] != null) {
|
||||
error = Exception(body['error']);
|
||||
} else {
|
||||
ignored = true;
|
||||
}
|
||||
} else if (response.statusCode == 422) {
|
||||
error = Exception('Invalid request parameters');
|
||||
} else {
|
||||
error = Exception('HTTP ${response.statusCode}');
|
||||
}
|
||||
|
||||
return ErrorOrData(ignored, error);
|
||||
}
|
||||
|
||||
FutureErrorOrData<bool> updateUser(
|
||||
TableModel table, int userId, String password, String accessToken) async {
|
||||
bool? ignored;
|
||||
Exception? error;
|
||||
|
||||
final response = await post(
|
||||
'/api/updateUser',
|
||||
body: {
|
||||
"user_id": userId,
|
||||
"password": password,
|
||||
"access_token": accessToken,
|
||||
},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
final body = json.decode(await response.stream.bytesToString());
|
||||
if (body['error'] != null) {
|
||||
error = Exception(body['error']);
|
||||
} else {
|
||||
ignored = true;
|
||||
}
|
||||
} else if (response.statusCode == 422) {
|
||||
error = Exception('Invalid request parameters');
|
||||
} else {
|
||||
error = Exception('HTTP ${response.statusCode}');
|
||||
}
|
||||
|
||||
return ErrorOrData(ignored, error);
|
||||
}
|
||||
|
||||
// REGION: HTTP Methods implementation
|
||||
|
||||
Future<StreamedResponse> get(
|
||||
|
|
|
|||
27
lib/api/model/user_model.dart
Normal file
27
lib/api/model/user_model.dart
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
class UserModel {
|
||||
final int id;
|
||||
final String username;
|
||||
final String? password;
|
||||
final String? accessToken;
|
||||
|
||||
UserModel({
|
||||
required this.id,
|
||||
required this.username,
|
||||
this.password,
|
||||
this.accessToken,
|
||||
});
|
||||
|
||||
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
|
||||
id: json["id"],
|
||||
username: json["username"],
|
||||
password: json["password"],
|
||||
accessToken: json["access_token"],
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
"id": id,
|
||||
"username": username,
|
||||
"password": password,
|
||||
"access_token": accessToken,
|
||||
};
|
||||
}
|
||||
|
|
@ -47,7 +47,7 @@ class _CreateTableItemBottomSheetState
|
|||
formKey: _formKey,
|
||||
children: [
|
||||
Text(
|
||||
"Create new item",
|
||||
widget.existingItem == null ? "Create new item" : "Update item",
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
|
|
|||
217
lib/pages/bottomsheets/create_user_bottomsheet.dart
Normal file
217
lib/pages/bottomsheets/create_user_bottomsheet.dart
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_fast_forms/flutter_fast_forms.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:tuuli_app/api/api_client.dart';
|
||||
import 'package:tuuli_app/api/model/table_field_model.dart';
|
||||
import 'package:tuuli_app/api/model/tables_list_model.dart';
|
||||
import 'package:tuuli_app/api/model/user_model.dart';
|
||||
import 'package:tuuli_app/utils.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:uuid/uuid_util.dart';
|
||||
|
||||
class CreateUserResult {
|
||||
final String username;
|
||||
final String password;
|
||||
|
||||
CreateUserResult(this.username, this.password);
|
||||
}
|
||||
|
||||
class UpdateUserResult {
|
||||
final String username;
|
||||
final String password;
|
||||
final String accessToken;
|
||||
|
||||
UpdateUserResult(this.username, this.password, this.accessToken);
|
||||
}
|
||||
|
||||
// TODO: Add a way to change user's group
|
||||
class CreateUserBottomSheet extends StatefulWidget {
|
||||
final UserModel? existingUser;
|
||||
|
||||
const CreateUserBottomSheet({
|
||||
super.key,
|
||||
this.existingUser,
|
||||
});
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _CreateUserBottomSheetState();
|
||||
}
|
||||
|
||||
class _CreateUserBottomSheetState extends State<CreateUserBottomSheet> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
String? newUsername;
|
||||
String? newPassword;
|
||||
String? newAccessToken;
|
||||
|
||||
bool obscurePassword = true;
|
||||
bool obscureToken = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: FastForm(
|
||||
formKey: _formKey,
|
||||
children: [
|
||||
Text(
|
||||
widget.existingUser == null ? "Create new user" : "Update user",
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Card(
|
||||
margin: const EdgeInsets.all(8),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: FastTextField(
|
||||
name: "Username",
|
||||
labelText: "Username",
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return "Please enter a value";
|
||||
}
|
||||
return null;
|
||||
},
|
||||
readOnly: widget.existingUser != null,
|
||||
initialValue: widget.existingUser?.username,
|
||||
onChanged: (value) {
|
||||
newUsername = value;
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
Card(
|
||||
margin: const EdgeInsets.all(8),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Row(
|
||||
children: [
|
||||
Flexible(
|
||||
child: FastTextField(
|
||||
name: "Password",
|
||||
labelText: "Password",
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return "Please enter a value";
|
||||
}
|
||||
return null;
|
||||
},
|
||||
obscureText: obscurePassword,
|
||||
onChanged: (value) {
|
||||
newPassword = value;
|
||||
},
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
obscurePassword
|
||||
? Icons.visibility_off
|
||||
: Icons.visibility,
|
||||
),
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
obscurePassword = !obscurePassword;
|
||||
});
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (widget.existingUser != null)
|
||||
Card(
|
||||
margin: const EdgeInsets.all(8),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Row(
|
||||
children: [
|
||||
Flexible(
|
||||
child: FastTextField(
|
||||
name: "Access token",
|
||||
labelText: "Access token",
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return "Please enter a value";
|
||||
}
|
||||
return null;
|
||||
},
|
||||
obscureText: obscureToken,
|
||||
initialValue: newAccessToken ??
|
||||
widget.existingUser?.accessToken,
|
||||
readOnly: true,
|
||||
onChanged: (value) {
|
||||
newAccessToken = value;
|
||||
},
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.shuffle),
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
newAccessToken = randomHexString(64);
|
||||
});
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
obscurePassword
|
||||
? Icons.visibility_off
|
||||
: Icons.visibility,
|
||||
),
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
obscureToken = !obscureToken;
|
||||
});
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text("Cancel"),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
Navigator.of(context).pop(widget.existingUser == null
|
||||
? CreateUserResult(
|
||||
newUsername!,
|
||||
newPassword!,
|
||||
)
|
||||
: UpdateUserResult(
|
||||
newUsername!,
|
||||
newPassword!,
|
||||
newAccessToken!,
|
||||
));
|
||||
return;
|
||||
}
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text("Please fill in all fields"),
|
||||
),
|
||||
);
|
||||
},
|
||||
child:
|
||||
Text(widget.existingUser == null ? "Create" : "Update"),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -85,14 +85,14 @@ class _OpenTableBottomSheetState extends State<OpenTableBottomSheet> {
|
|||
DataCell(
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: () => _deleteItem(e),
|
||||
icon: const Icon(Icons.delete),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: () => _updateExistingItem(e),
|
||||
icon: const Icon(Icons.edit),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: () => _deleteItem(e),
|
||||
icon: const Icon(Icons.delete),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -31,6 +31,9 @@ class _HomePageState extends State<HomePage> with HomePageStateRef {
|
|||
final apiClient = Get.find<ApiClient>();
|
||||
TablesListModel tables = TablesListModel([]);
|
||||
|
||||
TableModel get usersTable =>
|
||||
tables.tables.firstWhere((element) => element.tableName == "users");
|
||||
|
||||
bool get isNarrow =>
|
||||
(MediaQuery.of(context).size.width - C.materialDrawerWidth) <= 600;
|
||||
|
||||
|
|
@ -142,7 +145,7 @@ class _HomePageState extends State<HomePage> with HomePageStateRef {
|
|||
case PageType.tables:
|
||||
return TablesListPanel(parent: this, tables: tables);
|
||||
case PageType.users:
|
||||
return const UsersListPanel();
|
||||
return UsersListPanel(usersTable: usersTable);
|
||||
case PageType.settings:
|
||||
return const SettingsPanel();
|
||||
case PageType.none:
|
||||
|
|
|
|||
|
|
@ -1,36 +1,225 @@
|
|||
import 'package:bottom_sheet/bottom_sheet.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:tuuli_app/api/api_client.dart';
|
||||
import 'package:tuuli_app/api/model/tables_list_model.dart';
|
||||
import 'package:tuuli_app/api/model/user_model.dart';
|
||||
import 'package:tuuli_app/pages/bottomsheets/create_user_bottomsheet.dart';
|
||||
|
||||
class UsersListPanel extends StatefulWidget {
|
||||
const UsersListPanel({super.key});
|
||||
final TableModel usersTable;
|
||||
|
||||
const UsersListPanel({super.key, required this.usersTable});
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _UsersListPanelState();
|
||||
}
|
||||
|
||||
class _UsersListPanelState extends State<UsersListPanel> {
|
||||
final apiClient = Get.find<ApiClient>();
|
||||
|
||||
final users = <UserModel>[];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
_refreshUsers();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
child: IntrinsicHeight(
|
||||
child: _buildBody(),
|
||||
return _buildUserList();
|
||||
}
|
||||
|
||||
Widget _buildUserCard(BuildContext ctx, UserModel user) {
|
||||
return Card(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: () => _openUser(user),
|
||||
child: Container(
|
||||
margin: const EdgeInsets.all(5),
|
||||
padding: const EdgeInsets.all(5),
|
||||
child: Stack(
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
user.username,
|
||||
style: const TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
"User id: ${user.id}",
|
||||
style: const TextStyle(
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBody() {
|
||||
return Column(
|
||||
children: [
|
||||
Text(
|
||||
'Users',
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
Widget get newUserCard => Card(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: _createNewUser,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.all(5),
|
||||
padding: const EdgeInsets.all(5),
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
Widget _buildUserList() {
|
||||
if (users.isEmpty) {
|
||||
return Center(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
"No users found",
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).disabledColor,
|
||||
fontSize: 24,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
"Maybe create one? Or maybe you don't have permission to view them?",
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).disabledColor,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton.icon(
|
||||
onPressed: _createNewUser,
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text("Create user"),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return GridView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: users.length + 1,
|
||||
itemBuilder: (ctx, i) =>
|
||||
i == 0 ? newUserCard : _buildUserCard(ctx, users[i - 1]),
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 5,
|
||||
childAspectRatio: 5 / 2,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _createNewUser() async {
|
||||
var result = await showFlexibleBottomSheet<CreateUserResult>(
|
||||
minHeight: 1,
|
||||
initHeight: 1,
|
||||
maxHeight: 1,
|
||||
context: context,
|
||||
builder: (_, __, ___) => const CreateUserBottomSheet(),
|
||||
anchors: [0, 0.5, 1],
|
||||
isSafeArea: true,
|
||||
isDismissible: false,
|
||||
);
|
||||
|
||||
if (result == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final response = await apiClient.createUser(
|
||||
widget.usersTable, result.username, result.password);
|
||||
response.unfold((data) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text("User created"),
|
||||
),
|
||||
);
|
||||
_refreshUsers();
|
||||
}, (error) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text("Error: $error"),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _openUser(UserModel user) async {
|
||||
final result = await showFlexibleBottomSheet<UpdateUserResult>(
|
||||
minHeight: 1,
|
||||
initHeight: 1,
|
||||
maxHeight: 1,
|
||||
context: context,
|
||||
builder: (_, __, ___) => CreateUserBottomSheet(existingUser: user),
|
||||
anchors: [0, 0.5, 1],
|
||||
isSafeArea: true,
|
||||
isDismissible: false,
|
||||
);
|
||||
|
||||
if (result == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final response = await apiClient.updateItem(widget.usersTable, {
|
||||
"username": result.username,
|
||||
"password": result.password,
|
||||
"access_token": result.accessToken,
|
||||
}, {
|
||||
"id": user.id,
|
||||
});
|
||||
response.unfold((data) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text("User updated"),
|
||||
),
|
||||
);
|
||||
_refreshUsers();
|
||||
}, (error) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text("Error: $error"),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _refreshUsers() async {
|
||||
final result = await apiClient.getTableItems(widget.usersTable);
|
||||
result.unfold((data) {
|
||||
setState(() {
|
||||
users.clear();
|
||||
users.addAll(data.map((e) => UserModel.fromJson(e)));
|
||||
});
|
||||
}, (error) {
|
||||
ScaffoldMessenger.of(context).hideCurrentSnackBar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text("Error: $error"),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
11
lib/utils.dart
Normal file
11
lib/utils.dart
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import 'dart:math';
|
||||
|
||||
Random _random = Random();
|
||||
|
||||
String randomHexString(int length) {
|
||||
StringBuffer sb = StringBuffer();
|
||||
for (var i = 0; i < length; i++) {
|
||||
sb.write(_random.nextInt(16).toRadixString(16));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue