Skip to content

Commit

Permalink
Feature: Added the possibility to add a custom claim for the user.
Browse files Browse the repository at this point in the history
  • Loading branch information
LibardiFelipe committed Dec 30, 2022
1 parent ebef7fd commit f148071
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
45 changes: 37 additions & 8 deletions TemplateBase.Domain/Entities/User.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
using Flunt.Notifications;
using FirebaseAdmin.Auth;
using FirebaseAdmin;
using Flunt.Notifications;
using Flunt.Validations;
using Google.Apis.Auth.OAuth2;
using System.Collections.Generic;
using System.Threading;
using TemplateBase.Domain.Entities.Base;
using TemplateBase.Domain.Enumerators;
using TemplateBase.Domain.Resources;
using System.Threading.Tasks;
using System;

namespace TemplateBase.Domain.Entities
{
Expand All @@ -21,8 +28,8 @@ public User(string firebaseId, string name, string email, string? profilePicture
ChangeName(name, true);
ChangeEmail(email, true);
ChangeProfilePictureUrl(profilePictureUrl, true);
ChangeType(EUserType.Basic, true);
ChangeIsLocked(false, true);

IsLocked = false;
Role = EUserRole.Customer;
}
#endregion
Expand Down Expand Up @@ -85,14 +92,36 @@ public User ChangeProfilePictureUrl(string? value, bool fromConstructor = false)
return this;
}

public User ChangeType(EUserType value, bool fromConstructor = false)
public async Task ChangeRole(EUserRole value, CancellationToken cancellationToken)
{
if (!fromConstructor && Type.Equals(value))
return this;
if (Role.Equals(value))
return;

Type = value;
Role = value;
await SetCustomClaim(this, cancellationToken);
}

return this;
private async Task SetCustomClaim(User user, CancellationToken cancellationToken)
{
try
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("path/to/serviceAccountKey.json"),
});

var auth = FirebaseAuth.DefaultInstance;
var customClaims = new Dictionary<string, object>()
{
{ "role", $"{user.Role}" }
};

await auth.SetCustomUserClaimsAsync(user.FirebaseId, customClaims, cancellationToken);
}
catch (Exception x)
{
AddNotification("Role", x.Message);
}
}
#endregion
}
Expand Down
1 change: 1 addition & 0 deletions TemplateBase.Domain/TemplateBase.Domain.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="FirebaseAdmin" Version="2.3.0" />
<PackageReference Include="Flunt" Version="2.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
Expand Down

0 comments on commit f148071

Please sign in to comment.