mobileapplicationPassvault/lib/main.dart

404 lines
12 KiB
Dart

import 'dart:async';
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_passvault/api_provider/add_credentail_provider.dart';
import 'package:flutter_passvault/api_provider/api_provider_class.dart';
import 'package:flutter_passvault/api_provider/connectivty_provider.dart';
import 'package:flutter_passvault/api_provider/delete_provider.dart';
import 'package:flutter_passvault/api_provider/edit_credential_provider.dart';
import 'package:flutter_passvault/api_provider/share_credential_provider.dart';
import 'package:flutter_passvault/api_provider/sso_validation_provider.dart';
import 'package:flutter_passvault/api_provider/user_details_provider.dart';
import 'package:flutter_passvault/constant/constantfile.dart';
import 'package:flutter_passvault/custom_widgets/reuse_textview.dart';
import 'package:flutter_passvault/firebase_options.dart';
import 'package:flutter_passvault/hive_storage/add_creds_offline.dart';
import 'package:flutter_passvault/hive_storage/hive_repositary.dart';
import 'package:flutter_passvault/hive_storage/storedserlist.dart';
import 'package:flutter_passvault/hive_storage/test_hive.dart';
import 'package:flutter_passvault/hive_storage/store_credential_model.dart';
import 'package:flutter_passvault/view_pages/home_screen_page.dart';
import 'package:flutter_passvault/seesionManager/session_manager.dart';
import 'package:flutter_passvault/view_pages/shared_preferance.dart';
import 'package:hive_flutter/adapters.dart';
// import 'package:hive_flutter/hive_flutter.dart';
import 'package:openid_client/openid_client.dart';
import 'package:provider/provider.dart';
import 'api_provider/my_credential_provider.dart';
import 'routes/route_config.dart';
import 'sso_login/openid_io.dart'
if (dart.library.html) 'sso_login/openid_browser.dart';
var keycloakUri = ApiConstants.ssoUrl;
const scopes = ['profile'];
Credential? credential;
late final Client client;
Future<Client> getClient() async {
var uri = Uri.parse(keycloakUri);
if (!kIsWeb && Platform.isAndroid) uri = uri.replace(host: 'sso.konectar.io');
var clientId = 'appwildcard';
var clientSecret = 'fb812995-9c21-44dc-99ed-00b50dfa2dd5';
var issuer = await Issuer.discover(uri);
return Client(
issuer,
clientId,
clientSecret: clientSecret,
);
}
final messaging = FirebaseMessaging.instance;
Timer? timer;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
final settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
if (kDebugMode) {
print('Permission granted: ${settings.authorizationStatus}');
}
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
if (kDebugMode) {
print('Handling a foreground message: ${message.messageId}');
print('Message data: ${message.data}');
print('Message notification: ${message.notification?.title}');
print('Message notification: ${message.notification?.body}');
await showNotification(message);
}
});
if (!kIsWeb && Platform.isAndroid) {}
// timerrfun();
//hive
await Hive.initFlutter();
Hive.registerAdapter(StoredcredentialAdapter());
Hive.registerAdapter(AddofflinecredentialAdapter());
Hive.registerAdapter(AddtestofflinecredentialAdapter());
await Hive.openBox<Storedcredential>('credentialListBox');
await Hive.openBox<Addofflinecredential>('offlinedata');
await Hive.openBox<Storedcredential>('dataBox');
// }
client = await getClient();
credential = await getRedirectResult(client, scopes: scopes);
timerrfun();
runApp(MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => AddCredentialProvider(),
),
ChangeNotifierProvider(
create: (_) => APIProvider(),
),
ChangeNotifierProvider(
create: (_) => DelCredentialProvider(),
),
ChangeNotifierProvider(
create: (_) => EditCredentialProvider(),
),
ChangeNotifierProvider(
create: (_) => MyCredentialProvider(),
),
ChangeNotifierProvider(
create: (_) => ShareCredentialProvider(),
),
ChangeNotifierProvider(
create: (_) => LoginuserProvider(),
),
ChangeNotifierProvider(
create: (_) => ConnectivityProvider(),
),
ChangeNotifierProvider(create: (_) => SsoValidationProvider()),
ChangeNotifierProvider<HiveDataRepository>(
create: (_) => HiveDataRepository(
Hive.box<Storedcredential>('credentialListBox'))),
ChangeNotifierProvider<StoredDataRepository>(
create: (_) => StoredDataRepository(
Hive.box<Addofflinecredential>('offlinedata'))),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Passvault',
initialRoute: '/',
onGenerateRoute: RouteConfig.generateRoute,
routes: {
'/': (context) => FutureBuilder<bool>(
future: SessionManager().isLoggedIn(),
builder: (context, snapshot) {
// appContext = navigatorKey.currentContext;
print("Data_is : $snapshot");
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
final isLoggedIn = snapshot.data ?? false;
print("isLoggedIn_is : $isLoggedIn");
return isLoggedIn ? const Screen() : const MyApp();
}
},
),
},
),
));
}
Future<void> showNotification(RemoteMessage message) async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
final InitializationSettings initializationSettings =
InitializationSettings(android: initializationSettingsAndroid);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'channel_id',
'channel_name',
importance: Importance.max,
priority: Priority.high,
);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
message.notification!.title,
message.notification!.body,
platformChannelSpecifics,
);
}
void timerrfun() async {
const Duration timerInterval = Duration(minutes: 1);
timer = Timer.periodic(timerInterval, (timer) async {
print("Performing periodic actions...");
final Box<Storedcredential> hivebox =
Hive.box<Storedcredential>('credentialListBox');
final AddCredentialProvider result1 = AddCredentialProvider();
final DelCredentialProvider result2 = DelCredentialProvider();
final EditCredentialProvider result3 = EditCredentialProvider();
final ShareCredentialProvider result4 = ShareCredentialProvider();
final MyCredentialProvider result5 = MyCredentialProvider();
final APIProvider result6 = APIProvider();
final HiveDataRepository result7 = HiveDataRepository(hivebox);
//try {
await result1.postcredential();
print("result_addedProvider : ${result1.success}");
await result3.posteditcredential();
print("result_editProvider11 : $result3");
await result2.postdelcredential();
print("result_DelProvider11 : ${result1.success}");
await result4.postsharecredential();
print("result_shareProvider11 : $result4");
await result5.fetchMyCredential();
print("result_FeccthProvider11 : $result5");
await result6.fetchMessages();
print("result_getcredential1 : $result6");
await result6.getcredential1();
print("result_getcredential1 : $result6");
print("result_shareProvider11 : $result5");
result7.getAllDataFromHive();
// ... the rest of your code
// } else {
// print("Context is null. Timer callback skipped.");
// }
});
}
class MyApp extends StatefulWidget {
static BuildContext? appContext;
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// This widget is the root of your application.
UserInfo? userInfo;
String os = "";
@override
void initState() {
// TODO: implement initState
super.initState();
if (credential != null) {
print("client_is not null");
credential!.getUserInfo().then((userInfo) {
setState(() {
this.userInfo = userInfo;
});
});
}
}
@override
Widget build(BuildContext context) {
if (userInfo != null) {
dashboard();
}
return Scaffold(
appBar: AppBar(),
body: Consumer<ConnectivityProvider>(builder: (context, provider, _) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (userInfo == null)
provider.isConnected
? OutlinedButton(
child: const Text('Log in with SSO'),
onPressed: () async {
var credential = await authenticate(
client,
scopes: scopes,
);
var userInfo = await credential.getUserInfo();
setState(() {
this.userInfo = userInfo;
});
})
: ReusableTextView(
text: 'Please wait...',
),
],
),
);
}),
);
}
@override
Future<void> dispose() async {
// TODO: implement dispose
// Hive.close();
super.dispose();
timer?.cancel();
}
dashboard() async {
print("dashboarddd");
final ssoprovider =
Provider.of<SsoValidationProvider>(context, listen: false);
String username = userInfo!.name.toString();
String useremailid = userInfo!.email.toString();
String? token = await messaging.getToken();
if (kDebugMode) {
print('Registration Token=$token');
}
print("username : $username");
print("useremailid : $useremailid");
// String os = Platform.operatingSystem; //in your code
// print("OS_is: $os");
// if (Platform.isAndroid) {
// os = "android";
// } else {
// print("OS_is: hiiiii");
// os = "web";
// }
if (kIsWeb) {
// Web specific code
print('Running on web');
os = "web";
} else if (Platform.isAndroid) {
// Non-web (e.g., mobile) specific code
print('running on android');
os = "android";
} else if (Platform.isIOS) {
os = "ios";
} else {
os = "";
}
print("OS_is: $os");
await ssoprovider.ssovalidationrespose(username, useremailid, os, token!);
if (ssoprovider.message == null) {
// showAlertBox("Something went wrong,Please try again");
}
print("user_ssoprovider_response : ${ssoprovider.message!.success}");
print("user_ssoprovider_token : ${ssoprovider.message!.success.token}");
print("user_ssoprovider_name : ${ssoprovider.message!.success.name}");
print("user_ssoprovider_id : ${ssoprovider.message!.success.id}");
print("user_ssoprovider_email : ${ssoprovider.message!.success.email}");
await CustomSharedPreferences.setCustomValue(
ssoprovider.message!.success.token);
await CustomSharedPreferences.setname(ssoprovider.message!.success.email);
await CustomSharedPreferences.setuserid(
ssoprovider.message!.success.id.toString());
await CustomSharedPreferences.setusername(
ssoprovider.message!.success.name);
await SessionManager().setLoggedIn(true);
// ignore: use_build_context_synchronously
Navigator.pushReplacementNamed(context, '/MainPage');
}
}