ВВассралман
ВВассралман
CC#
Created by ВВассралман on 4/12/2025 in #help
how to verify me One Time Password? (i'm making login logic)
User needs to insert Name , Email and then One time password which will be sent on his Email . how to make this one time password verification logic? any ideas? (probably i will use this Email sender for many purposes , Email confirmation and etc.) thats what my sender looks like :
internal class EmailSender : IEmailSender
{
private readonly EmailSenderOptions _options;

public EmailSender(IOptions<EmailSenderOptions> options)
{
_options = options.Value;
}

public async Task SendEmailAsync(string email, string subject, string message)
{
// Create the email message
var emailMessage = new MimeMessage();

// From address
emailMessage.From.Add(new MailboxAddress(
_options.SenderName,
_options.SenderAddress));

// To address
emailMessage.To.Add(MailboxAddress.Parse(email));

emailMessage.Subject = subject;
emailMessage.Body = new TextPart("plain")
{
Text = message
};

// Send email using Gmail's SMTP server
using var client = new MailKit.Net.Smtp.SmtpClient();

// For development only. In production, you should properly handle certificate validation.
client.ServerCertificateValidationCallback = (s, c, h, e) => true;

var host = _options.SmtpServer;
var port = _options.Port;
var username = _options.UserName;
var password = _options.Password;

// Connect to the SMTP server using STARTTLS on port 587
await client.ConnectAsync(host, port, SecureSocketOptions.StartTls);

// Authenticate using your Gmail credentials

await client.AuthenticateAsync(username, password);

// Send the email
await client.SendAsync(emailMessage);

// Disconnect from the SMTP server
await client.DisconnectAsync(true);
}
}
internal class EmailSender : IEmailSender
{
private readonly EmailSenderOptions _options;

public EmailSender(IOptions<EmailSenderOptions> options)
{
_options = options.Value;
}

public async Task SendEmailAsync(string email, string subject, string message)
{
// Create the email message
var emailMessage = new MimeMessage();

// From address
emailMessage.From.Add(new MailboxAddress(
_options.SenderName,
_options.SenderAddress));

// To address
emailMessage.To.Add(MailboxAddress.Parse(email));

emailMessage.Subject = subject;
emailMessage.Body = new TextPart("plain")
{
Text = message
};

// Send email using Gmail's SMTP server
using var client = new MailKit.Net.Smtp.SmtpClient();

// For development only. In production, you should properly handle certificate validation.
client.ServerCertificateValidationCallback = (s, c, h, e) => true;

var host = _options.SmtpServer;
var port = _options.Port;
var username = _options.UserName;
var password = _options.Password;

// Connect to the SMTP server using STARTTLS on port 587
await client.ConnectAsync(host, port, SecureSocketOptions.StartTls);

// Authenticate using your Gmail credentials

await client.AuthenticateAsync(username, password);

// Send the email
await client.SendAsync(emailMessage);

// Disconnect from the SMTP server
await client.DisconnectAsync(true);
}
}
11 replies
CC#
Created by ВВассралман on 3/24/2025 in #help
blazor authentication service (WEB Api server)
i'm back end dev and i got no idea how i need to do Client side auth, any tips (or link on guide)? This is my Back End Controller i think to do AuthService in client side
using Application.Users;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Xml.Linq;
using Infrastructure.Service;

namespace WebApi.Controllers;


[ApiController]
[Route("api/auth")]
public sealed class UserController(IMediator mediator) : ControllerBase
{
[HttpPost("register")]
public async Task<ActionResult> RegisterAsync([FromBody] RegisterRequest request, CancellationToken ct)
{
var command = new RegisterUserCommand(request.Name, request.Email);
var userId = await mediator.Send(command, ct);

return Ok(new { UserId = userId });

}

[HttpPost("login")]
public async Task<ActionResult> AuthenticateAsync([FromBody] LoginRequest request, CancellationToken ct)
{
var command = new LoginUserCommand(request.Name, request.Email);
var user = await mediator.Send(command, ct);

if (user == null)
{
return Unauthorized("Invalid credentials.");
}

var token = JwtGenerator.GenerateToken(user);
return Ok(new { Token = token });
}
}

//I prefer to use Serilog + [Logmasked] attribute to be sure that data can't be leaked
public sealed record RegisterRequest (string Name,string Email);
public sealed record LoginRequest (string Name,string Email);
using Application.Users;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Xml.Linq;
using Infrastructure.Service;

namespace WebApi.Controllers;


[ApiController]
[Route("api/auth")]
public sealed class UserController(IMediator mediator) : ControllerBase
{
[HttpPost("register")]
public async Task<ActionResult> RegisterAsync([FromBody] RegisterRequest request, CancellationToken ct)
{
var command = new RegisterUserCommand(request.Name, request.Email);
var userId = await mediator.Send(command, ct);

return Ok(new { UserId = userId });

}

[HttpPost("login")]
public async Task<ActionResult> AuthenticateAsync([FromBody] LoginRequest request, CancellationToken ct)
{
var command = new LoginUserCommand(request.Name, request.Email);
var user = await mediator.Send(command, ct);

if (user == null)
{
return Unauthorized("Invalid credentials.");
}

var token = JwtGenerator.GenerateToken(user);
return Ok(new { Token = token });
}
}

//I prefer to use Serilog + [Logmasked] attribute to be sure that data can't be leaked
public sealed record RegisterRequest (string Name,string Email);
public sealed record LoginRequest (string Name,string Email);
3 replies
CC#
Created by ВВассралман on 3/21/2025 in #help
Any good guides for learning Blazor WASM?
I have opportunity to start job , but i need solid knowledge of Blazor WASM (i have 0 expirience , where i can learn it)
4 replies
CC#
Created by ВВассралман on 3/6/2025 in #help
Is there any open source clean+ddd project for learning?
Asp.net clean architecture with ddd , good examples for beginner and intermediate , drop link please
4 replies
CC#
Created by ВВассралман on 2/20/2025 in #help
Ef core seed (data)
namespace EventManager.SqlRepository.EntityConfigurations
{
internal sealed class ApplicationUserRolesConfiguration : IEntityTypeConfiguration<ApplicationUserRole>
{
public void Configure(EntityTypeBuilder<ApplicationUserRole> builder)
{
builder.HasData(
new ApplicationUserRole
{Id = "A117A8B5-F055-4A06-98A6-faxA4CEDBB24",Name = "Member", NormalizedName = "MEMBER",AccessDescription = "Can Subscribe/Unsubscribe on Events, has access to own account manipulations",ConcurrencyStamp = "member-concurrency-stamp",
},
new ApplicationUserRole
{Id = "190F2xxC-7177-4C77-BAd2-9121A40206BB",Name = "Admin",NormalizedName = "ADMIN",AccessDescription = "Can Manipulate with Events, has access to own account manipulations",ConcurrencyStamp = "admin-concurrency-stamp",
},
new ApplicationUserRole{Id = "e2H52d72-326e-4AV3-8f1b-7d1a2c2ed14b",Name = "Owner", NormalizedName = "OWNER",AccessDescription = "Can Manage Roles, can assign Roles to Users",ConcurrencyStamp = "owner-concurrency-stamp",
}
);
}
}

internal sealed class ApplicationUserSeed : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
{
builder.HasData(
new ApplicationUser
{Id = "BC59E711-CEFD-4088-BB9F-19B19F92170D",Email = "[email protected]",EmailConfirmed = true,LockoutEnabled = true,});
}
}
internal sealed class ApplicationUserRoles : IEntityTypeConfiguration<IdentityUserRole<?????>>
{
public void Configure(EntityTypeBuilder<ApplicationUserRole> builder)
{
builder.HasData(
new ApplicationUserRole{Id = "e2H52d72-326e-4AV3-8f1b-7d1a2c2ed14b",});
}
}

}
namespace EventManager.SqlRepository.EntityConfigurations
{
internal sealed class ApplicationUserRolesConfiguration : IEntityTypeConfiguration<ApplicationUserRole>
{
public void Configure(EntityTypeBuilder<ApplicationUserRole> builder)
{
builder.HasData(
new ApplicationUserRole
{Id = "A117A8B5-F055-4A06-98A6-faxA4CEDBB24",Name = "Member", NormalizedName = "MEMBER",AccessDescription = "Can Subscribe/Unsubscribe on Events, has access to own account manipulations",ConcurrencyStamp = "member-concurrency-stamp",
},
new ApplicationUserRole
{Id = "190F2xxC-7177-4C77-BAd2-9121A40206BB",Name = "Admin",NormalizedName = "ADMIN",AccessDescription = "Can Manipulate with Events, has access to own account manipulations",ConcurrencyStamp = "admin-concurrency-stamp",
},
new ApplicationUserRole{Id = "e2H52d72-326e-4AV3-8f1b-7d1a2c2ed14b",Name = "Owner", NormalizedName = "OWNER",AccessDescription = "Can Manage Roles, can assign Roles to Users",ConcurrencyStamp = "owner-concurrency-stamp",
}
);
}
}

internal sealed class ApplicationUserSeed : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
{
builder.HasData(
new ApplicationUser
{Id = "BC59E711-CEFD-4088-BB9F-19B19F92170D",Email = "[email protected]",EmailConfirmed = true,LockoutEnabled = true,});
}
}
internal sealed class ApplicationUserRoles : IEntityTypeConfiguration<IdentityUserRole<?????>>
{
public void Configure(EntityTypeBuilder<ApplicationUserRole> builder)
{
builder.HasData(
new ApplicationUserRole{Id = "e2H52d72-326e-4AV3-8f1b-7d1a2c2ed14b",});
}
}

}
123 replies
CC#
Created by ВВассралман on 2/20/2025 in #help
Mapping to avoid data dublicating.(Just help with ideas)
Hello, guys! I have a question. If I have a domain model Customer that is used in services, but at the same time I'm using ASP.NET Core Identity, where the user already has all the properties of my Customer, I end up duplicating data and storing it in the database. My Customer model has no unique properties. Can I somehow configure the logic to map or retrieve information from the AspNetUsers table and map it to Customer (I need the ID or email)?
11 replies
CC#
Created by ВВассралман on 2/16/2025 in #help
I am implementing role-based authentication using ASP.NET Identity. I have issue with assign roles
Hello guys, I am implementing role-based authentication using ASP.NET Identity. I have already added three roles: Member, Admin (can create resources), and Owner (can assign roles, grant or revoke the Admin role). I want to keep my controllers clean and move the logic to the infrastructure layer, but something feels wrong. I can't write proper code to prevent the Owner from demoting themselves. Any ideas?
cs
public sealed record AssignAdminRoleRequest
{
public required string Email { get; set; }
}

public async Task<TokensResponse> AssignAdminRole(AssignAdminRoleRequest request)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user is null)
{
throw new AuthenticationException();
}
if (!user.EmailConfirmed)
throw new AuthenticationException($"User :{request.Email} needs to confirm email");

if (await _userManager.IsInRoleAsync(user, "Admin"))
{
throw new IdentityException("User already has this role");
}


var result = await _userManager.AddToRoleAsync(user, "Admin");
if (!result.Succeeded)
throw new IdentityException("Failed to add Role. Try again later");

return await CreateTokenResponce(user);
}
cs
public sealed record AssignAdminRoleRequest
{
public required string Email { get; set; }
}

public async Task<TokensResponse> AssignAdminRole(AssignAdminRoleRequest request)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user is null)
{
throw new AuthenticationException();
}
if (!user.EmailConfirmed)
throw new AuthenticationException($"User :{request.Email} needs to confirm email");

if (await _userManager.IsInRoleAsync(user, "Admin"))
{
throw new IdentityException("User already has this role");
}


var result = await _userManager.AddToRoleAsync(user, "Admin");
if (!result.Succeeded)
throw new IdentityException("Failed to add Role. Try again later");

return await CreateTokenResponce(user);
}
4 replies