athrainsky преди 8 месеца
родител
ревизия
07f45dc47c
променени са 6 файла, в които са добавени 176 реда и са изтрити 12 реда
  1. 3 1
      lib/head.dart
  2. 78 0
      lib/intercept.dart
  3. 4 1
      lib/main.dart
  4. 0 0
      lib/platform/listmember.dart
  5. 17 10
      lib/test.dart
  6. 74 0
      lib/token.dart

+ 3 - 1
lib/head.dart

@@ -1,6 +1,8 @@
 import 'package:dropdown_button2/dropdown_button2.dart';
 import 'package:flutter/material.dart';
 import 'package:go_router/go_router.dart';
+import 'package:namer_app/test.dart';
+import 'package:namer_app/token.dart';
 
 class CustomAppbar extends StatefulWidget implements PreferredSizeWidget {
   final bool? isBack;
@@ -134,7 +136,7 @@ class _CustomAppbarState extends State<CustomAppbar> {
                   child: Text('Log Out'),
                 )
               ],
-              onChanged: null,
+              onChanged: callAPI,
             ),
           ),
         ),

+ 78 - 0
lib/intercept.dart

@@ -0,0 +1,78 @@
+import 'package:dio/dio.dart';
+import 'package:flutter/material.dart';
+
+class DioPage extends StatefulWidget {
+  @override
+  State<StatefulWidget> createState() {
+    return _DioPageState();
+  }
+}
+
+class _DioPageState extends State<DioPage> {
+
+Dio dio = Dio(
+  BaseOptions(
+    baseUrl: 'http://localhost:8080/api/v1',
+    connectTimeout: Durations.short4,
+    receiveTimeout: Durations.short3,
+  ),
+);
+
+Future<void> fetchData() async {
+  try {
+    Response response = await dio.get('http://localhost:8080/api/v1');
+    print(response.data);
+  } on DioException catch (e) {
+    print(e.message);
+  }
+}
+
+Future<void> postData() async {
+  try {
+    Response response = await dio.post(
+      'http://localhost:8080/api/v1',
+      data: {'key': 'value'},
+    );
+    print(response.data);
+  } on DioException catch (e) {
+    print(e.message);
+  }
+}
+
+Future<String> refreshToken() async {
+  // Perform a request to the refresh token endpoint and return the new access token.
+  // You can replace this with your own implementation.
+  return 'your_new_access_token';
+}
+
+  @override
+  Widget build(BuildContext context) {
+    Function(dynamic options, dynamic handler) onRequest;
+    Future Function(DioException e, dynamic handler) onError;
+    dio.interceptors.add(
+  InterceptorsWrapper(
+    onRequest:  onRequest = (options, handler) {
+      // Add the access token to the request header
+      options.headers['Authorization'] = 'Bearer your_access_token';
+      return handler.next(options);
+    },
+    onError:  onError = (DioException e, handler) async {
+      if (e.response?.statusCode == 401) {
+        // If a 401 response is received, refresh the access token
+        String newAccessToken = await refreshToken();
+
+        // Update the request header with the new access token
+        e.requestOptions.headers['Authorization'] = 'Bearer $newAccessToken';
+
+        // Repeat the request with the updated header
+        return handler.resolve(await dio.fetch(e.requestOptions));
+      }
+      return handler.next(e);
+    },
+  ),
+);
+    throw UnimplementedError();
+  }
+
+
+}

+ 4 - 1
lib/main.dart

@@ -4,12 +4,13 @@ import 'package:namer_app/bug/addbug.dart';
 import 'package:namer_app/platform/addplatform.dart';
 import 'package:namer_app/bug/editbug.dart';
 import 'package:namer_app/platform/editplatform.dart';
+import 'package:namer_app/token.dart';
 import 'package:namer_app/user/edituser.dart';
 import 'package:namer_app/footer.dart';
 import 'package:namer_app/head.dart';
 import 'package:namer_app/bug/listbug.dart';
 import 'package:namer_app/bug/listcomment.dart';
-import 'package:namer_app/listmember.dart';
+import 'package:namer_app/platform/listmember.dart';
 import 'package:namer_app/platform/listplatform.dart';
 import 'package:namer_app/listtable.dart';
 import 'package:namer_app/user/listuser.dart';
@@ -78,6 +79,8 @@ final _router = GoRouter(
         path: 'addplatform',
         builder: (context, state) => AddPlatformPage(),
       ),
+      GoRoute(path: 'token',
+      builder: (context, state) => TokenPage(),)
     ]),
   ],
 );

lib/listmember.dart → lib/platform/listmember.dart


+ 17 - 10
lib/test.dart

@@ -1,14 +1,21 @@
 import 'dart:convert';
+import 'package:http/http.dart';
 
-import 'package:dio/dio.dart';
+var username = 'user';
+var password = 'password';
+var auth = 'Basic ${base64Encode(utf8.encode('$username:$password'))}';
 
-final dio = Dio();
+Map<String, String> headers = {
+    'content-type': 'application/json',
+    'accept': 'application/json',
+    'authorization': auth
+ };
 
-void getHttp() async {
-  String username = 'user';
-  String password = 'password';
-  String basicAuth =
-      'Basic ${base64.encode(utf8.encode('$username:$password'))}';
-  final response = await dio.get('http://localhost:8080/api/v1/projects',options:Options(headers: <String,String>{'authorization': basicAuth}));
-  print(response);
-}
+Future<Response> callAPI(param) async {
+    
+    Response r = await get(Uri.parse('http://localhost:8080/api/v1/projects'),
+      headers: {'authorization': auth});
+  print(r.statusCode);
+  print(r.body);
+  return r;
+  }

+ 74 - 0
lib/token.dart

@@ -0,0 +1,74 @@
+import 'dart:convert';
+import 'package:flutter/material.dart';
+import 'package:http/http.dart' as http;
+import 'package:dio/dio.dart';
+
+class TokenPage extends StatefulWidget {
+  @override
+  State<StatefulWidget> createState() {
+    return _TokenPageState();
+  }
+}
+
+class _TokenPageState extends State<TokenPage> {
+
+  TextEditingController usernameController = TextEditingController();
+  TextEditingController  passwordController = TextEditingController();
+
+Future<String> authorization() async {
+    var request = http.MultipartRequest(
+        'GET', Uri.parse('http://localhost:8080/api/v1/projects'));
+    request.fields.addAll({
+      'grant_type': 'info',
+      'client_id': 'info',
+      'username': usernameController.text, 
+      'password': passwordController.text, 
+    });
+
+
+    http.StreamedResponse response = await request.send();
+
+    if (response.statusCode == 200) {
+      Map<String, dynamic> auth =
+          jsonDecode(await response.stream.bytesToString());
+
+      return auth['access_token'];
+    } else {
+      return "";
+    }
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      appBar: AppBar(
+        title: Text('Login'),
+        backgroundColor: Colors.green,
+      ),
+      body: Column(
+        children: [
+          Padding(
+            padding: EdgeInsets.all(8.0),
+            child: TextField(
+              decoration: InputDecoration(labelText: 'username'),
+              controller: usernameController,
+            ),
+          ),
+          Padding(
+            padding: EdgeInsets.all(8.0),
+            child: TextField(
+              decoration: InputDecoration(labelText: 'password'),
+              controller: passwordController,
+            ),
+          ),          
+          ElevatedButton(
+            onPressed: () async {
+              String token = await authorization();
+              print(token); //This will be your token.
+            },
+            child: Text('Login'),),
+        ],
+      ),
+    );
+  }
+}