Clean Architecture Demo
Loading...
Searching...
No Matches
BearerToken.cs
Go to the documentation of this file.
2
15internal static class BearerToken
16{
17 private const string VariableName = "BEARER_TOKEN";
18
19 private static readonly Lazy<string?> Token = new(Load);
20
21 public static string Value => Token.Value
22 ?? throw new InvalidOperationException(
23 $"No se encontró el token. Definir la variable de entorno {VariableName} o crear el archivo .env " +
24 "en la raíz del proyecto a partir de .env.example.");
25
26 private static string? Load()
27 {
28 var fromEnvironment = Environment.GetEnvironmentVariable(VariableName);
29 if (!string.IsNullOrWhiteSpace(fromEnvironment))
30 return fromEnvironment.Trim();
31
32 var envFile = FindEnvFile();
33 if (envFile is null)
34 return null;
35
36 return File.ReadLines(envFile)
37 .Select(line => line.Trim())
38 .Where(line => line.StartsWith(VariableName + "=", StringComparison.Ordinal))
39 .Select(line => line[(VariableName.Length + 1)..].Trim().Trim('"'))
40 .FirstOrDefault(value => value.Length > 0);
41 }
42
43 // Sube desde el directorio de salida de las pruebas hasta encontrar un archivo .env.
44 private static string? FindEnvFile()
45 {
46 for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
47 {
48 var candidate = Path.Combine(dir.FullName, ".env");
49 if (File.Exists(candidate))
50 return candidate;
51 }
52 return null;
53 }
54}