| | | 1 | | using ArturRios.Util.WebApi.Security.Constants; |
| | | 2 | | using ArturRios.Util.WebApi.Security.Interfaces; |
| | | 3 | | using ArturRios.Util.WebApi.Security.Records; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Util.WebApi.Security.Mappers; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// The mapper used when an app registers none of its own: it maps <see cref="IAuthenticatedUser.Id"/> and |
| | | 9 | | /// <see cref="IAuthenticatedUser.RoleId"/> through <see cref="TokenClaimKeys"/> and produces an |
| | | 10 | | /// <see cref="AuthenticatedUser"/>. Also the reference implementation for writing your own. |
| | | 11 | | /// </summary> |
| | | 12 | | public class DefaultAuthenticatedUserMapper : IAuthenticatedUserMapper |
| | | 13 | | { |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public Dictionary<string, string> ToClaims(IAuthenticatedUser user) => |
| | 19 | 16 | | new() |
| | 19 | 17 | | { |
| | 19 | 18 | | { TokenClaimKeys.Id, user.Id.ToString() }, |
| | 19 | 19 | | { TokenClaimKeys.RoleId, user.RoleId.ToString() } |
| | 19 | 20 | | }; |
| | | 21 | | |
| | | 22 | | /// <inheritdoc /> |
| | | 23 | | public IAuthenticatedUser? FromClaims(IReadOnlyDictionary<string, string> claims) |
| | | 24 | | { |
| | 19 | 25 | | if (!claims.TryGetValue(TokenClaimKeys.Id, out var idClaim) || !Guid.TryParse(idClaim, out var id)) |
| | | 26 | | { |
| | 4 | 27 | | return null; |
| | | 28 | | } |
| | | 29 | | |
| | 15 | 30 | | if (!claims.TryGetValue(TokenClaimKeys.RoleId, out var roleClaim) || !int.TryParse(roleClaim, out var roleId)) |
| | | 31 | | { |
| | 2 | 32 | | return null; |
| | | 33 | | } |
| | | 34 | | |
| | 13 | 35 | | return new AuthenticatedUser(id, roleId); |
| | | 36 | | } |
| | | 37 | | } |