Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernize codebase to use latest language features #107

Merged
merged 1 commit into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,8 @@ services.AddPasswordlessSdk(options =>
Inject the client into your controller:

```csharp
public class HomeController : Controller
public class HomeController(IPasswordlessClient passwordlessClient) : Controller
{
private readonly IPasswordlessClient _passwordlessClient;

public HomeController(IPasswordlessClient passwordlessClient)
{
_passwordlessClient = passwordlessClient;
}

// ...
}
```
Expand All @@ -70,12 +63,12 @@ public async Task<IActionResult> GetRegisterToken(string alias)
var payload = new RegisterOptions(userId, alias)
{
// Optional: Link this userid to an alias (e.g. email)
Aliases = new HashSet<string> { alias }
Aliases = [alias]
};

try
{
var tokenRegistration = await _passwordlessClient.CreateRegisterTokenAsync(payload);
var tokenRegistration = await passwordlessClient.CreateRegisterTokenAsync(payload);

// Return this token to the frontend
return Ok(tokenRegistration);
Expand All @@ -100,7 +93,7 @@ public async Task<IActionResult> VerifyAuthenticationToken(string token)
{
try
{
var verifiedUser = await _passwordlessClient.VerifyTokenAsync(token);
var verifiedUser = await passwordlessClient.VerifyTokenAsync(token);

// Sign the user in, set a cookie, etc
return Ok(verifiedUser);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,9 @@

namespace Passwordless.AspNetIdentity.Example.DataContext;

public class PasswordlessContext : IdentityDbContext<IdentityUser, IdentityRole, string>
public class PasswordlessContext(DbContextOptions options) :
IdentityDbContext<IdentityUser, IdentityRole, string>(options)
{
public PasswordlessContext(DbContextOptions options) : base(options)
{
}

protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlite("Data Source=example.db");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -8,15 +7,8 @@

namespace Passwordless.AspNetIdentity.Example.Pages.Account;

public class LoginModel : PageModel
public class LoginModel(ILogger<LoginModel> logger) : PageModel
{
private readonly ILogger<LoginModel> _logger;

public LoginModel(ILogger<LoginModel> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

public IActionResult OnGet()
{
if (HttpContext.User.Identity is { IsAuthenticated: true })
Expand All @@ -26,11 +18,15 @@ public IActionResult OnGet()
return Page();
}

public async Task OnPostAsync(LoginForm form, CancellationToken cancellationToken)
public Task OnPostAsync(LoginForm form, CancellationToken cancellationToken)
{
if (!ModelState.IsValid) return;
_logger.LogInformation("Logging in user {email}", form.Email);
ViewData["CanLogin"] = true;
if (ModelState.IsValid)
{
logger.LogInformation("Logging in user {email}", form.Email);
ViewData["CanLogin"] = true;
}

return Task.CompletedTask;
}

public LoginForm Form { get; } = new();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,13 @@

namespace Passwordless.AspNetIdentity.Example.Pages.Account;

public class Logout : PageModel
public class Logout(SignInManager<IdentityUser> userSignInManager, ILogger<Logout> logger) : PageModel
{
private readonly SignInManager<IdentityUser> _userSignInManager;
private readonly ILogger<Logout> _logger;

public Logout(SignInManager<IdentityUser> userSignInManager, ILogger<Logout> logger)
{
_userSignInManager = userSignInManager;
_logger = logger;
}

public async Task<IActionResult> OnGet()
{
await _userSignInManager.SignOutAsync();
_logger.LogInformation("User has signed out.");
await userSignInManager.SignOutAsync();
logger.LogInformation("User has signed out.");

return Page();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -9,29 +8,27 @@

namespace Passwordless.AspNetIdentity.Example.Pages.Account;

public class RegisterModel : PageModel
public class RegisterModel(ILogger<PrivacyModel> logger) : PageModel
{
private readonly ILogger<PrivacyModel> _logger;

public RegisterModel(ILogger<PrivacyModel> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

public IActionResult OnGet()
{
if (HttpContext.User.Identity is { IsAuthenticated: true })
{
return LocalRedirect("/");
}

return Page();
}

public async Task OnPostAsync(FormModel form, CancellationToken cancellationToken)
public Task OnPostAsync(FormModel form, CancellationToken cancellationToken)
{
if (!ModelState.IsValid) return;
_logger.LogInformation("Registering user {username}", form.Username);
ViewData["CanAddPasskeys"] = true;
if (ModelState.IsValid)
{
logger.LogInformation("Registering user {username}", form.Username);
ViewData["CanAddPasskeys"] = true;
}

return Task.CompletedTask;
}

public FormModel Form { get; init; } = new();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
using System;
using System.Security.Claims;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace Passwordless.AspNetIdentity.Example.Pages.Authorized;

public class HelloWorldModel : PageModel
{
private readonly ILogger<HelloWorldModel> _logger;

public HelloWorldModel(ILogger<HelloWorldModel> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

public void OnGet()
{
var identity = HttpContext.User.Identity!;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace Passwordless.AspNetIdentity.Example.Pages;

Expand All @@ -13,13 +12,6 @@ public class ErrorModel : PageModel

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);

private readonly ILogger<ErrorModel> _logger;

public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}

public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace Passwordless.AspNetIdentity.Example.Pages;

public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;

public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}

public void OnGet()
{
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace Passwordless.AspNetIdentity.Example.Pages;

public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;

public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}

public void OnGet()
{
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,4 @@

namespace Passwordless.AspNetIdentity.Example.Validation;

public class AlphanumericAttribute : RegularExpressionAttribute
{
private const string Regex = "([a-zA-Z0-9]+)";

public AlphanumericAttribute() : base(Regex)
{
}
}
public class AlphanumericAttribute() : RegularExpressionAttribute("([a-zA-Z0-9]+)");
17 changes: 4 additions & 13 deletions examples/Passwordless.Example/PasswordlessController.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace Passwordless.Example;

[ApiController]
public class PasswordlessController : Controller
public class PasswordlessController(IPasswordlessClient passwordlessClient) : Controller
{
private readonly IPasswordlessClient _passwordlessClient;

public PasswordlessController(IPasswordlessClient passwordlessClient)
{
_passwordlessClient = passwordlessClient;
}

/// <summary>
/// Register - Get token from the passwordless API
/// The passwordless client side code needs a Token to register a key to a username.
Expand All @@ -32,12 +23,12 @@ public async Task<IActionResult> GetRegisterToken(string alias)

var payload = new RegisterOptions(userId, alias)
{
Aliases = new HashSet<string> { alias }
Aliases = [alias]
};

try
{
var token = await _passwordlessClient.CreateRegisterTokenAsync(payload);
var token = await passwordlessClient.CreateRegisterTokenAsync(payload);
return Ok(token);
}
catch (PasswordlessApiException e)
Expand All @@ -62,7 +53,7 @@ public async Task<IActionResult> VerifyAuthenticationToken(string token)
{
try
{
var verifiedUser = await _passwordlessClient.VerifyAuthenticationTokenAsync(token);
var verifiedUser = await passwordlessClient.VerifyAuthenticationTokenAsync(token);
return Ok(verifiedUser);
}
catch (PasswordlessApiException e)
Expand Down
8 changes: 3 additions & 5 deletions examples/Passwordless.Example/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ public static void Main(string[] args)
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(host => host.UseStartup<Startup>());
}
9 changes: 2 additions & 7 deletions examples/Passwordless.Example/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,9 @@

namespace Passwordless.Example;

public class Startup
public class Startup(IConfiguration configuration)
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

private IConfiguration Configuration { get; }
private IConfiguration Configuration { get; } = configuration;

// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
Expand Down
1 change: 0 additions & 1 deletion src/Passwordless.AspNetCore/IdentityBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Passwordless;
Expand Down
Loading
Loading