MailSharp / MailSharp.Common / Services / AuthenticationService.cs
Code · 68 lines · 2587 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68using System.Text.Json;

namespace MailSharp.Common.Services;

public class AuthenticationService(
	IConfiguration configuration, 
	ILogger<AuthenticationService> logger)
{

	// Authenticate user credentials for POP3 or IMAP
	public async Task<bool> AuthenticateAsync(string username, string password, CancellationToken cancellationToken)
	{
		EventIdConfig eventIdConfig = configuration.GetSection("AuthEventIds:AuthenticationAttempt").Get<EventIdConfig>()
			?? throw new InvalidOperationException("Missing AuthEventIds:AuthenticationAttempt");
		logger.LogInformation(
			new EventId(eventIdConfig.Id, eventIdConfig.Name),
			configuration["AuthLogMessages:AuthenticationAttempt"],
			username);

		try
		{
			string userStorePath = configuration["AuthSettings:UserStorePath"] ?? throw new InvalidOperationException("UserStorePath not configured");
			if (!File.Exists(userStorePath))
			{
				eventIdConfig = configuration.GetSection("AuthEventIds:AuthenticationFailed").Get<EventIdConfig>()
					?? throw new InvalidOperationException("Missing AuthEventIds:AuthenticationFailed");
				logger.LogWarning(
					new EventId(eventIdConfig.Id, eventIdConfig.Name),
					configuration["AuthLogMessages:AuthenticationFailed"],
					username);
				return false;
			}

			string json = await File.ReadAllTextAsync(userStorePath, cancellationToken);
			var users = JsonSerializer.Deserialize<List<UserConfig>>(json) ?? throw new InvalidOperationException("Invalid user store format");
			var user = users.FirstOrDefault(u => u.Username == username && u.Password == password);

			if (user != null)
			{
				logger.LogInformation(
					new EventId(eventIdConfig.Id, eventIdConfig.Name),
					configuration["AuthLogMessages:AuthenticationSuccess"],
					username);
				return true;
			}

			var errorEventIdConfig = configuration.GetSection("AuthEventIds:AuthenticationFailed").Get<EventIdConfig>()
				?? throw new InvalidOperationException("Missing AuthEventIds:AuthenticationFailed");
			logger.LogWarning(
				new EventId(errorEventIdConfig.Id, errorEventIdConfig.Name),
				configuration["AuthLogMessages:AuthenticationFailed"],
				username);
			return false;
		}
		catch (Exception ex)
		{
			var errorEventIdConfig = configuration.GetSection("AuthEventIds:AuthenticationFailed").Get<EventIdConfig>()
				?? throw new InvalidOperationException("Missing AuthEventIds:AuthenticationFailed");
			logger.LogError(
				new EventId(errorEventIdConfig.Id, errorEventIdConfig.Name),
				ex,
				configuration["AuthLogMessages:AuthenticationFailed"],
				username);
			return false;
		}
	}

}