global variables added and implenented with login/logout

This commit is contained in:
LilleBRG 2024-08-23 12:34:38 +02:00
parent 2d197614f8
commit 57d52c3fd7
6 changed files with 90 additions and 40 deletions

View File

@ -3,6 +3,9 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'dart:convert'; import 'dart:convert';
import 'base/variables.dart';
enum ApiService { enum ApiService {
auth, auth,
app, app,
@ -61,7 +64,10 @@ Future<bool> isLoggedIn(BuildContext context) async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final token = prefs.getString('token'); final token = prefs.getString('token');
if (token == null) return false; if (token == null){
loggedIn = false;
return false;
}
try { try {
String base64 = token.split('.')[1]; String base64 = token.split('.')[1];

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:mobile/api.dart' as api; import 'package:mobile/api.dart' as api;
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:google_fonts/google_fonts.dart'; import 'package:google_fonts/google_fonts.dart';
import 'variables.dart';
class SideMenu extends StatefulWidget { class SideMenu extends StatefulWidget {
@ -15,7 +16,6 @@ class SideMenu extends StatefulWidget {
} }
class _SideMenuState extends State<SideMenu> { class _SideMenuState extends State<SideMenu> {
bool _isLoggedIn = false;
late int _selectedIndex; late int _selectedIndex;
@override @override
@ -28,7 +28,10 @@ class _SideMenuState extends State<SideMenu> {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
prefs.remove('token'); prefs.remove('token');
setState(() => _isLoggedIn = false); setState(() {
loggedIn = false;
});
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@ -43,8 +46,12 @@ class _SideMenuState extends State<SideMenu> {
super.didChangeDependencies(); super.didChangeDependencies();
api api
.isLoggedIn(context) .isLoggedIn(context).then((value) {
.then((value) => setState(() => _isLoggedIn = value)); setState(() {
loggedIn = value; // Update the second variable here
});
});
} }
@override @override
@ -114,7 +121,7 @@ Widget build(BuildContext context) {
thickness: 2, thickness: 2,
indent: 40, indent: 40,
), ),
...(_isLoggedIn ...(loggedIn
? [ ? [
ListTile( ListTile(
title: const Text('Log out'), title: const Text('Log out'),

View File

@ -0,0 +1,6 @@
import 'package:mobile/models.dart';
//Global variables
bool loggedIn = false;
User? user;

View File

@ -1,7 +1,10 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:mobile/base/sidemenu.dart'; import 'package:mobile/base/sidemenu.dart';
import 'package:mobile/base/variables.dart';
import 'package:mobile/models.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:google_fonts/google_fonts.dart'; import 'package:google_fonts/google_fonts.dart';
import 'dart:convert';
import 'api.dart' as api; import 'api.dart' as api;
class LoginPage extends StatefulWidget { class LoginPage extends StatefulWidget {
@ -16,16 +19,28 @@ class _LoginPageState extends State<LoginPage> {
final passwordInput = TextEditingController(); final passwordInput = TextEditingController();
Future<void> _login() async { Future<void> _login() async {
final token = await api final token = await api
.request(context, api.ApiService.auth, 'POST', '/api/Users/login', { .request(context, api.ApiService.auth, 'POST', '/api/Users/login', {
'email': emailInput.text, 'email': emailInput.text,
'password': passwordInput.text, 'password': passwordInput.text,
}); });
if (token == null) return; if (token == null) return;
// Assuming token is a JSON string
Map<String, dynamic> json = jsonDecode(token);
User jsonUser = User.fromJson(json);
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
prefs.setString('token', token); prefs.setString('token', jsonUser.token);
prefs.setString('id', jsonUser.id);
setState(()
{user = jsonUser;
loggedIn == true;
});
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(

View File

@ -7,9 +7,23 @@ class Favorite {
Favorite(this.id, this.userId, this.lat, this.lng); Favorite(this.id, this.userId, this.lat, this.lng);
} }
class Login { class User {
String id;
String token; String token;
String id;
String email;
String username;
DateTime createdAt;
User(this.token, this.id, this.email, this.username, this.createdAt);
factory User.fromJson(Map<String, dynamic> json) {
return User(
json['token'],
json['id'],
json['email'],
json['username'],
DateTime.parse(json['createdAt']),
);
}
}
Login(this.id, this.token);
}

View File

@ -1,44 +1,46 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:mobile/base/variables.dart';
import 'package:mobile/models.dart';
import 'base/sidemenu.dart'; import 'base/sidemenu.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:mobile/base/variables.dart';
import 'api.dart' as api;
class ProfilePage extends StatefulWidget { class ProfilePage extends StatefulWidget {
final String id;
const ProfilePage({super.key, required this.id}); const ProfilePage({super.key});
//const ProfilePage({super.key, required this.id});
@override @override
State<ProfilePage> createState() => _ProfilePageState(); State<ProfilePage> createState() => _ProfilePageState();
} }
class _ProfilePageState extends State<ProfilePage> { class _ProfilePageState extends State<ProfilePage> {
late String _id; late User userData;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_id = widget.id; // Initialize _selectedIndex with the value from the widget
}
Future<void> _getUser() async { // Check if the user is logged in when the page is entered
final token = await api if (loggedIn == false) {
.request(context, api.ApiService.auth, 'GET', '/api/Users/$_id', { WidgetsBinding.instance.addPostFrameCallback((_) {
}); ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Please log in')));
if (token == null) return; Navigator.pushReplacementNamed(context, '/login');
});
final prefs = await SharedPreferences.getInstance();
prefs.setString('token', token);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Successfully logged in')));
Navigator.pushReplacementNamed(context, '/home');
} }
setState(() {
userData = user!;
});
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return SideMenu( return SideMenu(