Skip to content

Commit

Permalink
Created Session Management. (PalisadoesFoundation#2362)
Browse files Browse the repository at this point in the history
* feat: efficient session management

* chore: run check ignore

* Revert "chore: run check ignore"

This reverts commit be7e49f.

* chore fix: run check ignore

* feat: added new package fake_async

* chore: fixed codecov drop

* Update README.md

* Deprecate Google Maps Integration (PalisadoesFoundation#2363)

* Post comments were invisible in Individual Post Page with Image (PalisadoesFoundation#2350)

* Fixed Comment

* Fixed Comment

* Fixed Comment

* Fixed Comment

* Fixed Comment

* Bump syncfusion_flutter_datepicker from 24.1.47 to 24.2.3 (PalisadoesFoundation#2365)

Bumps [syncfusion_flutter_datepicker](https://github.com/syncfusion/flutter-widgets/tree/master/packages) from 24.1.47 to 24.2.3.
- [Release notes](https://github.com/syncfusion/flutter-widgets/releases)
- [Commits](https://github.com/syncfusion/flutter-widgets/commits/HEAD/packages)

---
updated-dependencies:
- dependency-name: syncfusion_flutter_datepicker
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Bump syncfusion_flutter_calendar from 24.1.45 to 24.2.3 (PalisadoesFoundation#2367)

Bumps [syncfusion_flutter_calendar](https://github.com/syncfusion/flutter-widgets/tree/master/packages) from 24.1.45 to 24.2.3.
- [Release notes](https://github.com/syncfusion/flutter-widgets/releases)
- [Commits](https://github.com/syncfusion/flutter-widgets/commits/HEAD/packages)

---
updated-dependencies:
- dependency-name: syncfusion_flutter_calendar
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* fixed requested changes

* pulled latest upstream

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: Peter Harrison <[email protected]>
Co-authored-by: Parag Gupta <[email protected]>
Co-authored-by: Shivam Gupta <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
  • Loading branch information
5 people authored Feb 11, 2024
1 parent 1110aef commit 69e6513
Show file tree
Hide file tree
Showing 21 changed files with 227 additions and 82 deletions.
27 changes: 17 additions & 10 deletions lib/locator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import 'package:talawa/services/image_service.dart';
import 'package:talawa/services/navigation_service.dart';
import 'package:talawa/services/org_service.dart';
import 'package:talawa/services/post_service.dart';
import 'package:talawa/services/session_manager.dart';
import 'package:talawa/services/size_config.dart';
import 'package:talawa/services/task_service.dart';
import 'package:talawa/services/third_party_service/multi_media_pick_service.dart';
Expand Down Expand Up @@ -44,37 +45,40 @@ import 'package:talawa/view_model/widgets_view_models/custom_drawer_view_model.d
import 'package:talawa/view_model/widgets_view_models/like_button_view_model.dart';
import 'package:talawa/view_model/widgets_view_models/progress_dialog_view_model.dart';

// Creating an instance of GetIt and storing it in a global variable
// Instance of GetIt and storing it in a global variable
/// Intializaing the locator.
GetIt locator = GetIt.instance;

///creating GetIt for UserConfig.
///GetIt for UserConfig.
final userConfig = locator<UserConfig>();

///creating GetIt for NavigationService.
///GetIt for NavigationService.
final navigationService = locator<NavigationService>();

///creating GetIt for DataBaseMutationFunctions.
///GetIt for DataBaseMutationFunctions.
final databaseFunctions = locator<DataBaseMutationFunctions>();

///creating GetIt for GraphqlConfig.
///GetIt for GraphqlConfig.
final graphqlConfig = locator<GraphqlConfig>();

///creating GetIt for SizeConfig.
///GetIt for SizeConfig.
final sizeConfig = locator<SizeConfig>();

///creating GetIt for Queries.
///GetIt for Queries.
final queries = locator<Queries>();

///creating GetIt for Connectivity.
///GetIt for Connectivity.
final connectivity = locator<Connectivity>();

///creating GetIt for OrganizationService.
///GetIt for OrganizationService.
final organizationService = locator<OrganizationService>();

///creating GetIt for ImageService.
///GetIt for ImageService.
final imageService = locator<ImageService>();

///GetIt for SessionManager.
final sessionManager = locator<SessionManager>();

/// This function registers the widgets/objects in "GetIt".
///
/// **params**:
Expand All @@ -94,6 +98,9 @@ void setupLocator() {
//userConfig
locator.registerSingleton(UserConfig());

//sessionManager
locator.registerSingleton(SessionManager());

//Services
locator.registerLazySingleton(() => PostService());
locator.registerLazySingleton(() => EventService());
Expand Down
2 changes: 1 addition & 1 deletion lib/plugins/fetch_plugin_list.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ class FetchPluginList {
),
);
box = Hive.box('pluginBox');
box.put('plugins', result.data!["getPlugins"]);
box.put('plugins', result.data?["getPlugins"]);
}
}
35 changes: 24 additions & 11 deletions lib/services/database_mutation_functions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class DataBaseMutationFunctions {
/// Query passed by fucntion calling this function.
late Queries _query;

/// initialization function.
/// Initialization function.
///
/// **params**:
/// None
Expand All @@ -39,6 +39,19 @@ class DataBaseMutationFunctions {
_query = Queries();
}

/// Initializes [clientNonAuth] function.
///
/// **params**:
/// None
///
/// **returns**:
/// None
void initClientNonAuth() {
graphqlConfig.getOrgUrl();
clientNonAuth = graphqlConfig.clientToQuery();
_query = Queries();
}

/// Graphql error for handling.
GraphQLError userNotFound = const GraphQLError(message: 'User not found');

Expand Down Expand Up @@ -86,7 +99,7 @@ class DataBaseMutationFunctions {
OperationException exception, {
bool showSnackBar = true,
}) {
// if server link is wrong.
// If server link is wrong.
if (exception.linkException != null) {
debugPrint(exception.linkException.toString());
if (showSnackBar) {
Expand All @@ -100,7 +113,7 @@ class DataBaseMutationFunctions {
return false;
}

/// looping through graphQL errors.
/// Looping through graphQL errors.
debugPrint(exception.graphqlErrors.toString());
for (int i = 0; i < exception.graphqlErrors.length; i++) {
// if the error message is "Access Token has expired. Please refresh session.: Undefined location"
Expand All @@ -116,7 +129,7 @@ class DataBaseMutationFunctions {
return true;
}

/// if the error message is "User is not authenticated"
/// If the error message is "User is not authenticated"
if (exception.graphqlErrors[i].message == userNotAuthenticated.message) {
print('client refreshed');
refreshAccessToken(userConfig.currentUser.refreshToken!).then(
Expand All @@ -127,7 +140,7 @@ class DataBaseMutationFunctions {
return true;
}

/// if the error message is "User not found"
/// If the error message is "User not found"
if (exception.graphqlErrors[i].message == userNotFound.message) {
if (showSnackBar) {
WidgetsBinding.instance.addPostFrameCallback(
Expand All @@ -140,7 +153,7 @@ class DataBaseMutationFunctions {
return false;
}

/// if the error message is "Membership Request already exists"
/// If the error message is "Membership Request already exists"
if (exception.graphqlErrors[i].message == memberRequestExist.message) {
if (showSnackBar) {
WidgetsBinding.instance.addPostFrameCallback(
Expand All @@ -153,7 +166,7 @@ class DataBaseMutationFunctions {
return false;
}

/// if the error message is "Invalid credentials"
/// If the error message is "Invalid credentials"
if (exception.graphqlErrors[i].message == wrongCredentials.message) {
if (showSnackBar) {
WidgetsBinding.instance.addPostFrameCallback(
Expand All @@ -166,7 +179,7 @@ class DataBaseMutationFunctions {
return false;
}

/// if the error message is "Organization not found"
/// If the error message is "Organization not found"
if (exception.graphqlErrors[i].message == organizationNotFound.message) {
if (showSnackBar) {
WidgetsBinding.instance.addPostFrameCallback(
Expand All @@ -179,7 +192,7 @@ class DataBaseMutationFunctions {
return false;
}

/// if the error message is "Email address already exists"
/// If the error message is "Email address already exists"
if (exception.graphqlErrors[i].message == emailAccountPresent.message) {
if (showSnackBar) {
WidgetsBinding.instance.addPostFrameCallback(
Expand All @@ -192,7 +205,7 @@ class DataBaseMutationFunctions {
return false;
}
}
// if the error is unknown
// If the error is unknown

WidgetsBinding.instance.addPostFrameCallback(
(_) => navigationService.showTalawaErrorDialog(
Expand Down Expand Up @@ -250,7 +263,7 @@ class DataBaseMutationFunctions {
variables: variables ?? <String, dynamic>{},
),
);
// if there is an error or exception in [result]
// If there is an error or exception in [result]
if (result.hasException) {
final exception = encounteredExceptionOrError(result.exception!);
if (exception!) {
Expand Down
14 changes: 0 additions & 14 deletions lib/services/event_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,6 @@ class EventService {
/// **returns**:
/// None
Future<void> getEvents() async {
// refresh user's access token
await _dbFunctions.refreshAccessToken(userConfig.currentUser.refreshToken!);
_dbFunctions.init();

// get current organization id
final String currentOrgID = _currentOrg.id!;
// mutation to fetch the events
Expand Down Expand Up @@ -102,7 +98,6 @@ class EventService {
/// **returns**:
/// * `Future<dynamic>`: Information about event registrants.
Future<dynamic> fetchRegistrantsByEvent(String eventId) async {
await _dbFunctions.refreshAccessToken(userConfig.currentUser.refreshToken!);
final result = await _dbFunctions.gqlAuthQuery(
EventQueries().registrantsByEvent(eventId),
);
Expand All @@ -117,9 +112,6 @@ class EventService {
/// **returns**:
/// * `Future<dynamic>`: Information about the event registration.
Future<dynamic> registerForAnEvent(String eventId) async {
final tokenResult = await _dbFunctions
.refreshAccessToken(userConfig.currentUser.refreshToken!);
debugPrint(tokenResult.toString());
final Map<String, dynamic> variables = {'eventId': eventId};
final result = await _dbFunctions.gqlAuthMutation(
EventQueries().registerForEvent(),
Expand All @@ -139,9 +131,6 @@ class EventService {
navigationService.pushDialog(
const CustomProgressDialog(key: Key('DeleteEventProgress')),
);
final tokenResult = await _dbFunctions
.refreshAccessToken(userConfig.currentUser.refreshToken!);
debugPrint(tokenResult.toString());
final result = await _dbFunctions.gqlAuthMutation(
EventQueries().deleteEvent(eventId),
);
Expand All @@ -166,9 +155,6 @@ class EventService {
key: Key('EditEventProgress'),
),
);
final tokenResult = await _dbFunctions
.refreshAccessToken(userConfig.currentUser.refreshToken!);
debugPrint(tokenResult.toString());
final result = await _dbFunctions.gqlAuthMutation(
EventQueries().updateEvent(eventId: eventId),
variables: variables,
Expand Down
5 changes: 0 additions & 5 deletions lib/services/graphql_config.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
// ignore_for_file: talawa_api_doc
// ignore_for_file: talawa_good_doc_comments

import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:hive/hive.dart';
import 'package:http/http.dart' as http;
Expand Down Expand Up @@ -39,8 +36,6 @@ class GraphqlConfig {
orgURI = url ?? ' ';
displayImgRoute = imgUrl ?? ' ';
httpLink = HttpLink(orgURI!);
clientToQuery();
authClient();
}

GraphQLClient clientToQuery() {
Expand Down
2 changes: 0 additions & 2 deletions lib/services/post_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,6 @@ class PostService {
/// **returns**:
/// * `Future<void>`: returns future void
Future<void> getPosts() async {
await _dbFunctions.refreshAccessToken(userConfig.currentUser.refreshToken!);
_dbFunctions.init();
// variables
final String currentOrgID = _currentOrg.id!;
final String query = PostQueries().getPostsById(currentOrgID);
Expand Down
52 changes: 52 additions & 0 deletions lib/services/session_manager.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import 'dart:async';

import 'package:talawa/locator.dart';

/// Manages user sessions and periodically refreshes access tokens.
class SessionManager {
SessionManager() {
initializeSessionRefresher();
}

/// returns refresh interval of Session Manager.
int get refreshInterval => _refreshInterval;

/// refresh interval in seconds.
static const int _refreshInterval = 600;

/// Initializes as session refresher.
///
/// Invokes [refreshSession] periodically at regular
/// refresh intervals.
///
/// **params**:
/// None
///
/// **returns**:
/// * `Timer`: refresh timer.
Timer initializeSessionRefresher() {
return Timer.periodic(
const Duration(seconds: _refreshInterval),
(Timer timer) async {
refreshSession();
},
);
}

/// Asynchronously refreshes the user session.
///
/// **params**:
/// None
///
/// **returns**:
/// * `Future<bool>`: indicates if session refresh was
/// successful.
Future<bool> refreshSession() async {
if (userConfig.loggedIn && userConfig.currentUser.refreshToken != null) {
final refreshed = await databaseFunctions
.refreshAccessToken(userConfig.currentUser.refreshToken!);
return refreshed;
}
return false;
}
}
10 changes: 0 additions & 10 deletions lib/services/task_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ class TaskService {
/// **returns**:
/// None
Future<void> getTasksForEvent(String eventId) async {
await _databaseMutationFunctions
.refreshAccessToken(_userConfig.currentUser.refreshToken!);
final res = await _databaseMutationFunctions
.gqlNonAuthQuery(TaskQueries.eventTasks(eventId));

Expand All @@ -57,8 +55,6 @@ class TaskService {
/// **returns**:
/// None
Future<void> getTasksByUser() async {
await _databaseMutationFunctions
.refreshAccessToken(_userConfig.currentUser.refreshToken!);
final res = await _databaseMutationFunctions
.gqlNonAuthQuery(TaskQueries.userTasks(_userConfig.currentUser.id!));

Expand Down Expand Up @@ -89,8 +85,6 @@ class TaskService {
required String deadline,
required String taskId,
}) async {
_databaseMutationFunctions
.refreshAccessToken(_userConfig.currentUser.refreshToken!);
final res = await _databaseMutationFunctions.gqlAuthMutation(
TaskQueries.editTask(
title: title,
Expand Down Expand Up @@ -135,8 +129,6 @@ class TaskService {
required String deadline,
required String eventId,
}) async {
_databaseMutationFunctions
.refreshAccessToken(_userConfig.currentUser.refreshToken!);
final res = await _databaseMutationFunctions.gqlAuthMutation(
TaskQueries.addTask(
title: title,
Expand Down Expand Up @@ -166,8 +158,6 @@ class TaskService {
/// None
Future<void> deleteTask(String taskId, String creatorId) async {
if (creatorId == _userConfig.currentUser.id) {
await _databaseMutationFunctions
.refreshAccessToken(_userConfig.currentUser.refreshToken!);
final res = await _databaseMutationFunctions
.gqlAuthMutation(TaskQueries.deleteTask(taskId));
if (res != null) _tasks.removeWhere((task) => task.id == taskId);
Expand Down
4 changes: 3 additions & 1 deletion lib/services/user_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,11 @@ class UserConfig {
_currentUser = User(id: 'null', authToken: 'null');
return false;
}

databaseFunctions.initClientNonAuth();
await sessionManager.refreshSession();
// generate access token
graphqlConfig.getToken().then((value) async {
databaseFunctions.init();
try {
final QueryResult result = await databaseFunctions.gqlAuthQuery(
queries.fetchUserInfo,
Expand Down
Loading

0 comments on commit 69e6513

Please sign in to comment.