storage cookie from shared preferences

This commit is contained in:
Valentin CZERYBA 2022-09-17 22:41:21 +02:00
parent fa90ba8c21
commit 463aa47a52
2 changed files with 35 additions and 34 deletions

View File

@ -1,10 +1,11 @@
// ignore_for_file: unnecessary_brace_in_string_interps
import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(const MyApp());
@ -57,40 +58,13 @@ class _MyHomePageState extends State<MyHomePage> {
String listUser = "";
Future<void> _incrementCounter() async {
var url = Uri.parse("http://localhost:8083/api/token");
String credentials = "peter93:toto";
Codec<String, String> stringToBase64 = utf8.fuse(base64);
String encoded = stringToBase64.encode(credentials);
var response = await http.get(url, headers: {
HttpHeaders.authorizationHeader: 'Basic $encoded',
});
var user = "";
var jwt = "";
var cookies = response.headers["set-cookie"].toString().split(";");
for (var cookie in cookies) {
var cookiesMany = cookie.split(",");
for (var cookie2 in cookiesMany) {
switch (cookie2.split("=")[0]) {
case "jwt":
{
jwt = cookie2.toString();
}
break;
case "user":
{
user = cookie2.toString();
}
break;
default:
break;
}
}
}
SharedPreferences prefs = await SharedPreferences.getInstance();
var user = prefs.getString("user");
var jwt = prefs.getString("jwt");
String former = "";
stderr.writeln("User ${user}");
stderr.writeln("Jwt ${jwt}");
stderr.writeln('Response status: ${response.statusCode}');
stderr.writeln('Response body: ${response.body}');
var urlGet = Uri.parse("http://localhost:8083/api/users");
var responseGet = await http

View File

@ -1,9 +1,12 @@
import 'package:flutter/material.dart';
import 'MyHomePage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:io';
import 'MyHomePage.dart';
import 'classes/alert.dart';
void main() {
@ -42,6 +45,30 @@ class _LoginDemoState extends State<LoginDemo> with ShowErrorDialog {
});
if ((response.statusCode == 200) || (response.statusCode == 201)) {
SharedPreferences prefs = await SharedPreferences.getInstance();
var cookies = response.headers["set-cookie"].toString().split(";");
prefs.remove("jwt");
prefs.remove("user");
for (var cookie in cookies) {
var cookiesMany = cookie.split(",");
for (var cookie2 in cookiesMany) {
switch (cookie2.split("=")[0]) {
case "jwt":
{
prefs.setString("jwt", cookie2);
}
break;
case "user":
{
prefs.setString("user", cookie2);
}
break;
default:
break;
}
}
}
Navigator.push(
context,
MaterialPageRoute(