-
-
Notifications
You must be signed in to change notification settings - Fork 203
/
DefaultUserFactory.cs
67 lines (57 loc) · 1.87 KB
/
DefaultUserFactory.cs
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
using Microsoft.AspNetCore.Http;
namespace Sentry.AspNetCore;
internal class DefaultUserFactory : IUserFactory, ISentryUserFactory
{
private readonly IHttpContextAccessor? _httpContextAccessor;
public DefaultUserFactory()
{
}
public DefaultUserFactory(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public User? Create() => _httpContextAccessor?.HttpContext is {} httpContext ? Create(httpContext) : null;
public User? Create(HttpContext context)
{
var principal = context.User;
if (principal is null)
{
return null;
}
string? email = null;
string? id = null;
string? username = null;
foreach (var claim in principal.Claims)
{
switch (claim.Type)
{
case ClaimTypes.Email:
email = claim.Value;
break;
case ClaimTypes.NameIdentifier:
id = claim.Value;
break;
case ClaimTypes.Name:
username = claim.Value;
break;
}
}
// Identity.Name Reads the value of: ClaimsIdentity.NameClaimType which by default is ClaimTypes.Name
// It can be changed by the application to read a different claim though:
var name = principal.Identity?.Name;
if (name is not null && username != name)
{
username = name;
}
var ipAddress = context.Connection?.RemoteIpAddress?.ToString();
return email is null && id is null && username is null && ipAddress is null
? null
: new User
{
Id = id,
Email = email,
Username = username,
IpAddress = ipAddress,
};
}
}