Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created Session Management. #2362

Merged
merged 13 commits into from
Feb 11, 2024
7 changes: 7 additions & 0 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 @@ -75,6 +76,9 @@ final organizationService = locator<OrganizationService>();
///creating GetIt for ImageService.
final imageService = locator<ImageService>();

///creating GetIt for SessionManager.
Azad99-9 marked this conversation as resolved.
Show resolved Hide resolved
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"]);
}
}
13 changes: 13 additions & 0 deletions lib/services/database_mutation_functions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,19 @@ class DataBaseMutationFunctions {
_query = Queries();
}

/// initializes [clientNonAuth] function.
Azad99-9 marked this conversation as resolved.
Show resolved Hide resolved
///
/// **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
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
2 changes: 1 addition & 1 deletion lib/splash_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
setState(() => _initialUri = null);
}

final bool userLoggedIn = await userConfig.userLoggedIn();
final bool userLoggedIn = userConfig.loggedIn;

Check warning on line 76 in lib/splash_screen.dart

View check run for this annotation

Codecov / codecov/patch

lib/splash_screen.dart#L76

Added line #L76 was not covered by tests
Azad99-9 marked this conversation as resolved.
Show resolved Hide resolved
_initialUri = null;
_latestUri = null;
if (_latestUri == null && _initialUri == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,6 @@ class CreateEventViewModel extends BaseModel {
navigationService.pushDialog(
const CustomProgressDialog(key: Key('EventCreationProgress')),
);
final tokenResult = await databaseFunctions
.refreshAccessToken(userConfig.currentUser.refreshToken!);
print(tokenResult);
// invoke the `gqlAuthMutation` function of `databaseFunctions`
// service along with the mutation query and variable map.
final result = await databaseFunctions.gqlAuthMutation(
Expand Down
2 changes: 1 addition & 1 deletion pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ packages:
source: hosted
version: "7.0.0"
fake_async:
dependency: transitive
dependency: "direct dev"
description:
name: fake_async
sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ dependencies:
dev_dependencies:
build_runner: ^2.4.7
custom_lint: 0.5.8
fake_async: ^1.3.1
flutter_test:
sdk: flutter
hive_generator: ^2.0.1
Expand Down
9 changes: 9 additions & 0 deletions test/helpers/test_helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,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 All @@ -55,6 +56,7 @@ 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';
import '../service_tests/image_service_test.dart';
import '../service_tests/user_config_test.dart';
import '../views/main_screen_test.dart';
import 'test_helpers.mocks.dart';

Expand Down Expand Up @@ -175,6 +177,13 @@ CommentService getAndRegisterCommentService() {
return service;
}

SessionManager getAndRegisterSessionManager() {
_removeRegistrationIfExists<SessionManager>();
final service = MockSessionManger();
locator.registerSingleton<SessionManager>(service);
return service;
}

ChatService getAndRegisterChatService() {
_removeRegistrationIfExists<ChatService>();
final service = MockChatService();
Expand Down
1 change: 1 addition & 0 deletions test/model_tests/user/user_info_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ final testDataFromOrg = <String, dynamic>{
/// Test Data Not From Organization.
final testDataNotFromOrg = {
"user": {
"id": "1234567890",
"firstName": "ravidi",
"lastName": "sheikh",
"email": "[email protected]",
Expand Down
1 change: 1 addition & 0 deletions test/service_tests/database_mutations_function_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ void main() async {
registerServices();
functionsClass = DataBaseMutationFunctions();
functionsClass.init();
functionsClass.initClientNonAuth();
});

group('Database Mutation Functions Tests', () {
Expand Down
4 changes: 4 additions & 0 deletions test/service_tests/event_service_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import 'package:talawa/utils/task_queries.dart';

import '../helpers/test_helpers.dart';
import '../helpers/test_locator.dart';
import '../model_tests/user/user_info_test.dart';

void main() {
testSetupLocator();
Expand Down Expand Up @@ -162,6 +163,9 @@ void main() {
"name": "Organization Name",
"description": "Sample organization description.",
},
"registrants": [
testDataNotFromOrg,
],
}
],
},
Expand Down
7 changes: 2 additions & 5 deletions test/service_tests/post_service_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,10 @@ void main() {

group('Test PostService', () {
test('Test refreshFeed method', () async {
final dataBaseMutationFunctions = locator<DataBaseMutationFunctions>();
final service = PostService();
// Populating refreshing feed
await service.refreshFeed();
verify(dataBaseMutationFunctions.refreshAccessToken('testtoken'))
.called(2);
verify(service.getPosts()).called(2);
});

test('Test addNewPost method', () async {
Expand Down Expand Up @@ -306,8 +304,7 @@ void main() {
); // Adjust the delay as needed

// Verify that refresh token was called to check getPost method was called correctly.
verify(dataBaseMutationFunctions.refreshAccessToken('testtoken'))
.called(3);
verify(service.getPosts()).called(1);

// Close the stream controller to avoid memory leaks
await orgInfoStreamController.close();
Expand Down
Loading
Loading