Sending the notification after sending the response

This commit is contained in:
ashutosh.nehete 2025-08-13 10:21:07 +05:30
parent b44fd6d49f
commit 48fb5fd449
2 changed files with 58 additions and 38 deletions

View File

@ -1,6 +1,6 @@
namespace Marco.Pms.Model.Utilities namespace Marco.Pms.Model.Utilities
{ {
public class DeviceTokenDto public class FCMTokenDto
{ {
public required string FcmToken { get; set; } public required string FcmToken { get; set; }
} }

View File

@ -158,41 +158,6 @@ namespace MarcoBMS.Services.Controllers
// Log the start of the login attempt for traceability. // Log the start of the login attempt for traceability.
_logger.LogInfo("Login attempt initiated for user: {Username}", loginDto.Username ?? "N/A"); _logger.LogInfo("Login attempt initiated for user: {Username}", loginDto.Username ?? "N/A");
// --- Push Notification Section ---
// This section attempts to send a test push notification to the user's device.
// It's designed to fail gracefully and handle invalid Firebase Cloud Messaging (FCM) tokens.
var message = new Message()
{
Token = loginDto.DeviceToken,
Notification = new Notification
{
Title = "Hello from .NET",
Body = "This is a test message"
}
};
try
{
// Attempt to send the message via Firebase.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
_logger.LogInfo("Successfully sent test push notification. MessageId: {MessageId}", response);
}
catch (FirebaseMessagingException ex)
{
// Log the specific Firebase error.
_logger.LogError(ex, "Error sending push notification");
// Check for specific error codes that indicate an invalid or unregistered token.
if (ex.MessagingErrorCode == MessagingErrorCode.Unregistered ||
ex.MessagingErrorCode == MessagingErrorCode.InvalidArgument)
{
_logger.LogWarning("FCM token is invalid and should be deleted from the database: {Token}", loginDto.DeviceToken ?? string.Empty);
// TODO: Implement the logic here to remove the invalid token from your database.
// Example: await YourTokenService.DeleteTokenAsync(loginDto.DeviceToken);
}
}
try try
{ {
// --- Input Validation --- // --- Input Validation ---
@ -285,6 +250,44 @@ namespace MarcoBMS.Services.Controllers
// Return a successful response with the generated tokens. // Return a successful response with the generated tokens.
_logger.LogInfo("User {Username} logged in successfully.", user.UserName); _logger.LogInfo("User {Username} logged in successfully.", user.UserName);
_ = Task.Run(async () =>
{
// --- Push Notification Section ---
// This section attempts to send a test push notification to the user's device.
// It's designed to fail gracefully and handle invalid Firebase Cloud Messaging (FCM) tokens.
var message = new Message()
{
Token = loginDto.DeviceToken,
Notification = new Notification
{
Title = "Hello from .NET",
Body = "This is a test message"
}
};
try
{
// Attempt to send the message via Firebase.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
_logger.LogInfo("Successfully sent test push notification. MessageId: {MessageId}", response);
}
catch (FirebaseMessagingException ex)
{
// Log the specific Firebase error.
_logger.LogError(ex, "Error sending push notification");
// Check for specific error codes that indicate an invalid or unregistered token.
if (ex.MessagingErrorCode == MessagingErrorCode.Unregistered ||
ex.MessagingErrorCode == MessagingErrorCode.InvalidArgument)
{
_logger.LogWarning("FCM token is invalid and should be deleted from the database: {Token}", loginDto.DeviceToken ?? string.Empty);
// TODO: Implement the logic here to remove the invalid token from your database.
// Example: await YourTokenService.DeleteTokenAsync(loginDto.DeviceToken);
}
}
});
return Ok(ApiResponse<object>.SuccessResponse(responseData, "User logged in successfully.", 200)); return Ok(ApiResponse<object>.SuccessResponse(responseData, "User logged in successfully.", 200));
} }
catch (Exception ex) catch (Exception ex)
@ -921,9 +924,26 @@ namespace MarcoBMS.Services.Controllers
[Authorize] [Authorize]
[HttpPost("set/device-token")] [HttpPost("set/device-token")]
public async Task<IActionResult> StoreDeviceToken([FromBody] DeviceTokenDto model) public async Task<IActionResult> StoreDeviceToken([FromBody] FCMTokenDto model)
{ {
return Ok(ApiResponse<object>.SuccessResponse(model)); var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
var tenantId = _userHelper.GetTenantId();
var fcmTokenMapping = new FCMTokenMapping
{
EmployeeId = loggedInEmployee.Id,
FcmToken = model.FcmToken,
TenantId = tenantId
};
//_context.FCMTokenMappings.Add(fcmTokenMapping);
//try
//{
// await _context.SaveChangesAsync();
//}
//catch (Exception ex)
//{
// _logger.LogError(ex, "Exception occured while saving FCM Token for employee {EmployeeId}", loggedInEmployee.Id);
//}
return Ok(ApiResponse<object>.SuccessResponse(fcmTokenMapping));
} }
private static string ComputeSha256Hash(string rawData) private static string ComputeSha256Hash(string rawData)
{ {