Skip to content

Feature integrae languade model into teh generic data route #32

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/src/config/app_dependencies.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class AppDependencies {
late final DataRepository<Topic> topicRepository;
late final DataRepository<Source> sourceRepository;
late final DataRepository<Country> countryRepository;
late final DataRepository<Language> languageRepository;
late final DataRepository<User> userRepository;
late final DataRepository<UserAppSettings> userAppSettingsRepository;
late final DataRepository<UserContentPreferences>
Expand Down Expand Up @@ -128,6 +129,13 @@ class AppDependencies {
toJson: (item) => item.toJson(),
logger: Logger('DataMongodb<Country>'),
);
final languageClient = DataMongodb<Language>(
connectionManager: _mongoDbConnectionManager,
modelName: 'languages',
fromJson: Language.fromJson,
toJson: (item) => item.toJson(),
logger: Logger('DataMongodb<Language>'),
);
final userClient = DataMongodb<User>(
connectionManager: _mongoDbConnectionManager,
modelName: 'users',
Expand Down Expand Up @@ -162,6 +170,7 @@ class AppDependencies {
topicRepository = DataRepository(dataClient: topicClient);
sourceRepository = DataRepository(dataClient: sourceClient);
countryRepository = DataRepository(dataClient: countryClient);
languageRepository = DataRepository(dataClient: languageClient);
userRepository = DataRepository(dataClient: userClient);
userAppSettingsRepository = DataRepository(
dataClient: userAppSettingsClient,
Expand Down
6 changes: 6 additions & 0 deletions lib/src/rbac/permissions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ abstract class Permissions {
static const String countryUpdate = 'country.update';
static const String countryDelete = 'country.delete';

// Language Permissions
static const String languageCreate = 'language.create';
static const String languageRead = 'language.read';
static const String languageUpdate = 'language.update';
static const String languageDelete = 'language.delete';

// User Permissions
// Allows reading any user profile (e.g., for admin or public profiles)
static const String userRead = 'user.read';
Expand Down
15 changes: 15 additions & 0 deletions lib/src/rbac/role_permissions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ final Set<String> _appGuestUserPermissions = {
Permissions.topicRead,
Permissions.sourceRead,
Permissions.countryRead,
Permissions.languageRead,
Permissions.userAppSettingsReadOwned,
Permissions.userAppSettingsUpdateOwned,
Permissions.userContentPreferencesReadOwned,
Expand All @@ -30,9 +31,20 @@ final Set<String> _appPremiumUserPermissions = {
// --- Dashboard Role Permissions ---

final Set<String> _dashboardPublisherPermissions = {
// Publishers need to read all content types to manage them effectively.
Permissions.headlineRead,
Permissions.topicRead,
Permissions.sourceRead,
Permissions.countryRead,
Permissions.languageRead,
Permissions.remoteConfigRead,

// Publishers can manage headlines.
Permissions.headlineCreate,
Permissions.headlineUpdate,
Permissions.headlineDelete,

// Core dashboard access and quality-of-life permissions.
Permissions.dashboardLogin,
Permissions.rateLimitingBypass,
};
Expand All @@ -48,6 +60,9 @@ final Set<String> _dashboardAdminPermissions = {
Permissions.countryCreate,
Permissions.countryUpdate,
Permissions.countryDelete,
Permissions.languageCreate,
Permissions.languageUpdate,
Permissions.languageDelete,
Permissions.userRead, // Allows reading any user's profile
Permissions.remoteConfigCreate,
Permissions.remoteConfigUpdate,
Expand Down
256 changes: 151 additions & 105 deletions lib/src/services/database_seeding_service.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import 'package:core/core.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/config/environment_config.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/services/mongodb_rate_limit_service.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/services/mongodb_token_blacklist_service.dart';
import 'package:flutter_news_app_api_server_full_source_code/src/services/mongodb_verification_code_storage_service.dart';
import 'package:logging/logging.dart';
Expand Down Expand Up @@ -28,20 +27,156 @@ class DatabaseSeedingService {

await _ensureIndexes();
await _seedOverrideAdminUser();
await _seedCollection<Country>(
collectionName: 'countries',
fixtureData: countriesFixturesData,
getId: (item) => item.id,
toJson: (item) => item.toJson(),
);
await _seedCollection<Language>(
collectionName: 'languages',
fixtureData: languagesFixturesData,
getId: (item) => item.id,
toJson: (item) => item.toJson(),
);
await _seedCollection<RemoteConfig>(
collectionName: 'remote_configs',
fixtureData: remoteConfigsFixturesData,
getId: (item) => item.id,
toJson: (item) => item.toJson(),
);

_log.info('Database seeding process completed.');
}

/// Seeds a specific collection from a given list of fixture data.
Future<void> _seedCollection<T>({
required String collectionName,
required List<T> fixtureData,
required String Function(T) getId,
required Map<String, dynamic> Function(T) toJson,
}) async {
_log.info('Seeding collection: "$collectionName"...');
try {
if (fixtureData.isEmpty) {
_log.info('No documents to seed for "$collectionName".');
return;
}

final collection = _db.collection(collectionName);
final operations = <Map<String, Object>>[];

for (final item in fixtureData) {
// Use the predefined hex string ID from the fixture to create a
// deterministic ObjectId. This is crucial for maintaining relationships
// between documents (e.g., a headline and its source).
final objectId = ObjectId.fromHexString(getId(item));
final document = toJson(item)..remove('id');

operations.add({
// Use updateOne with $set to be less destructive than replaceOne.
'updateOne': {
// Filter by the specific, deterministic _id.
'filter': {'_id': objectId},
// Set the fields of the document.
'update': {r'$set': document},
'upsert': true,
},
});
}

final result = await collection.bulkWrite(operations);
_log.info(
'Seeding for "$collectionName" complete. '
'Upserted: ${result.nUpserted}, Modified: ${result.nModified}.',
);
} on Exception catch (e, s) {
_log.severe('Failed to seed collection "$collectionName".', e, s);
rethrow;
}
}

/// Ensures that the necessary indexes exist on the collections.
///
/// This method is idempotent; it will only create indexes if they do not
/// already exist. It's crucial for enabling efficient text searches.
Future<void> _ensureIndexes() async {
_log.info('Ensuring database indexes exist...');
try {
// Text index for searching headlines by title
await _db
.collection('headlines')
.createIndex(keys: {'title': 'text'}, name: 'headlines_text_index');

// Text index for searching topics by name
await _db
.collection('topics')
.createIndex(keys: {'name': 'text'}, name: 'topics_text_index');

// Text index for searching sources by name
await _db
.collection('sources')
.createIndex(keys: {'name': 'text'}, name: 'sources_text_index');

// --- TTL and Unique Indexes via runCommand ---
// The following indexes are created using the generic `runCommand` because
// they require specific options not exposed by the simpler `createIndex`
// helper method in the `mongo_dart` library.
// Specifically, `expireAfterSeconds` is needed for TTL indexes.

// Indexes for the verification codes collection
await _db.runCommand({
'createIndexes': kVerificationCodesCollection,
'indexes': [
{
// This is a TTL (Time-To-Live) index. MongoDB will automatically
// delete documents from this collection when the `expiresAt` field's
// value is older than the specified number of seconds (0).
'key': {'expiresAt': 1},
'name': 'expiresAt_ttl_index',
'expireAfterSeconds': 0,
},
{
// This ensures that each email can only have one pending
// verification code at a time, preventing duplicates.
'key': {'email': 1},
'name': 'email_unique_index',
'unique': true,
},
],
});

// Index for the token blacklist collection
await _db.runCommand({
'createIndexes': kBlacklistedTokensCollection,
'indexes': [
{
// This is a TTL index. MongoDB will automatically delete documents
// (blacklisted tokens) when the `expiry` field's value is past.
'key': {'expiry': 1},
'name': 'expiry_ttl_index',
'expireAfterSeconds': 0,
},
],
});

_log.info('Database indexes are set up correctly.');
} on Exception catch (e, s) {
_log.severe('Failed to create database indexes.', e, s);
// We rethrow here because if indexes can't be created,
// critical features like search will fail.
rethrow;
}
}

/// Ensures the single administrator account is correctly configured based on
/// the `OVERRIDE_ADMIN_EMAIL` environment variable.
Future<void> _seedOverrideAdminUser() async {
_log.info('Checking for admin user override...');
final overrideEmail = EnvironmentConfig.overrideAdminEmail;

if (overrideEmail == null || overrideEmail.isEmpty) {
_log.info(
'OVERRIDE_ADMIN_EMAIL not set. Skipping admin user override.',
);
_log.info('OVERRIDE_ADMIN_EMAIL not set. Skipping admin user override.');
return;
}

Expand Down Expand Up @@ -89,9 +224,10 @@ class DatabaseSeedingService {
),
);

await usersCollection.insertOne(
{'_id': newAdminId, ...newAdminUser.toJson()..remove('id')},
);
await usersCollection.insertOne({
'_id': newAdminId,
...newAdminUser.toJson()..remove('id'),
});

// Create default settings and preferences for the new admin.
await _createUserSubDocuments(newAdminId);
Expand Down Expand Up @@ -130,9 +266,10 @@ class DatabaseSeedingService {
showPublishDateInHeadlineFeed: true,
),
);
await _db.collection('user_app_settings').insertOne(
{'_id': userId, ...defaultAppSettings.toJson()..remove('id')},
);
await _db.collection('user_app_settings').insertOne({
'_id': userId,
...defaultAppSettings.toJson()..remove('id'),
});

final defaultUserPreferences = UserContentPreferences(
id: userId.oid,
Expand All @@ -141,100 +278,9 @@ class DatabaseSeedingService {
followedTopics: const [],
savedHeadlines: const [],
);
await _db.collection('user_content_preferences').insertOne(
{'_id': userId, ...defaultUserPreferences.toJson()..remove('id')},
);
}

/// Ensures that the necessary indexes exist on the collections.
///
/// This method is idempotent; it will only create indexes if they do not
/// already exist. It's crucial for enabling efficient text searches.
Future<void> _ensureIndexes() async {
_log.info('Ensuring database indexes exist...');
try {
// Text index for searching headlines by title
await _db
.collection('headlines')
.createIndex(keys: {'title': 'text'}, name: 'headlines_text_index');

// Text index for searching topics by name
await _db
.collection('topics')
.createIndex(keys: {'name': 'text'}, name: 'topics_text_index');

// Text index for searching sources by name
await _db
.collection('sources')
.createIndex(keys: {'name': 'text'}, name: 'sources_text_index');

// --- TTL and Unique Indexes via runCommand ---
// The following indexes are created using the generic `runCommand` because
// they require specific options not exposed by the simpler `createIndex`
// helper method in the `mongo_dart` library.
// Specifically, `expireAfterSeconds` is needed for TTL indexes.

// Indexes for the verification codes collection
await _db.runCommand({
'createIndexes': kVerificationCodesCollection,
'indexes': [
{
// This is a TTL (Time-To-Live) index. MongoDB will automatically
// delete documents from this collection when the `expiresAt` field's
// value is older than the specified number of seconds (0).
'key': {'expiresAt': 1},
'name': 'expiresAt_ttl_index',
'expireAfterSeconds': 0,
},
{
// This ensures that each email can only have one pending
// verification code at a time, preventing duplicates.
'key': {'email': 1},
'name': 'email_unique_index',
'unique': true,
},
],
});

// Index for the token blacklist collection
await _db.runCommand({
'createIndexes': kBlacklistedTokensCollection,
'indexes': [
{
// This is a TTL index. MongoDB will automatically delete documents
// (blacklisted tokens) when the `expiry` field's value is past.
'key': {'expiry': 1},
'name': 'expiry_ttl_index',
'expireAfterSeconds': 0,
},
],
});

// Index for the rate limit attempts collection
await _db.runCommand({
'createIndexes': kRateLimitAttemptsCollection,
'indexes': [
{
// This is a TTL index. MongoDB will automatically delete request
// attempt documents 24 hours after they are created.
'key': {'createdAt': 1},
'name': 'createdAt_ttl_index',
'expireAfterSeconds': 86400, // 24 hours
},
{
// Index on the key field for faster lookups.
'key': {'key': 1},
'name': 'key_index',
},
],
});

_log.info('Database indexes are set up correctly.');
} on Exception catch (e, s) {
_log.severe('Failed to create database indexes.', e, s);
// We rethrow here because if indexes can't be created,
// critical features like search will fail.
rethrow;
}
await _db.collection('user_content_preferences').insertOne({
'_id': userId,
...defaultUserPreferences.toJson()..remove('id'),
});
}
}
5 changes: 5 additions & 0 deletions routes/_middleware.dart
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ Handler middleware(Handler handler) {
(_) => deps.countryRepository,
),
) //
.use(
provider<DataRepository<Language>>(
(_) => deps.languageRepository,
),
) //
.use(
provider<DataRepository<User>>((_) => deps.userRepository),
) //
Expand Down
Loading
Loading