Skip to content

Commit

Permalink
Next-js-web-app (#138)
Browse files Browse the repository at this point in the history
  • Loading branch information
jurabek committed Dec 29, 2023
1 parent abee90c commit ad9929a
Show file tree
Hide file tree
Showing 43 changed files with 629 additions and 376 deletions.
19 changes: 10 additions & 9 deletions src/backend/services/catalog-api/src/handlers/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,16 +72,16 @@ pub fn delete(catalog_id: i32) {
}

#[openapi]
#[get("/all", format = "json")]
pub fn get_catalogs() -> Result<Json<Vec<CatalogResponse>>> {
#[get("/all?<category_name>", format = "json")]
pub fn get_catalogs(category_name: Option<String>) -> Result<Json<Vec<CatalogResponse>>> {
use schema::catalog::dsl::*;


// let tracer = global::tracer("catalog_handler");
// let mut span = tracer.start("get_all_catalogs");

let connection = &mut establish_connection();
let res = catalog

let mut query = catalog.into_boxed();
if let Some(ref cat_name) = category_name {
query = query.filter(category.eq(cat_name));
}
let res = query
.load::<Catalog>(connection)
.expect("failed to loading catalogs")
.into_iter()
Expand All @@ -92,9 +92,9 @@ pub fn get_catalogs() -> Result<Json<Vec<CatalogResponse>>> {
image: c.image,
price: c.price.to_f64().unwrap(),
currency: c.currency,
category: c.category,
})
.collect();
// span.end();
return Ok(Json(res));
}

Expand All @@ -116,6 +116,7 @@ pub fn get_catalog(catalog_id: i32) -> Result<Json<CatalogResponse>> {
image: c.image,
price: c.price.to_f64().unwrap(),
currency: c.currency,
category: c.category,
};

return Ok(Json(res));
Expand Down
1 change: 1 addition & 0 deletions src/backend/services/catalog-api/src/models/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,5 @@ pub struct CatalogResponse {
pub image: String,
pub price: f64,
pub currency: String,
pub category: String,
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@

namespace Identity.API.Abstraction
{
public interface IUserManagerFacade
{
Task<IdentityResult> Create(ApplicationUser user, string password);
public interface IUserManagerFacade
{
Task<IdentityResult> Create(ApplicationUser user, string password);

Task<IdentityResult> UpdateAsync(ApplicationUser user);
Task<IdentityResult> UpdateAsync(ApplicationUser user);

Task<ApplicationUser> GetAsync(ClaimsPrincipal principal);
IEnumerable<ApplicationUser> GetAllUsers();
}
Task<ApplicationUser> GetAsync(ClaimsPrincipal principal);

IEnumerable<ApplicationUser> GetAllUsers();
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
namespace Identity.API
{
public struct ApiConstants
{
public const string ClientId = "user_password.client";
}
public struct ApiConstants
{
public const string ClientId = "user_password.client";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,24 @@

namespace Identity.API.Controllers.Account
{
public static class Extensions
{
/// <summary>
/// Checks if the redirect URI is for a native client.
/// </summary>
/// <returns></returns>
public static bool IsNativeClient(this AuthorizationRequest context)
public static class Extensions
{
return !context?.RedirectUri?.StartsWith("https", StringComparison.Ordinal) == true
&& !context?.RedirectUri?.StartsWith("http", StringComparison.Ordinal) == true;
}
/// <summary>
/// Checks if the redirect URI is for a native client.
/// </summary>
/// <returns></returns>
public static bool IsNativeClient(this AuthorizationRequest context)
{
return !context?.RedirectUri?.StartsWith("https", StringComparison.Ordinal) == true
&& !context?.RedirectUri?.StartsWith("http", StringComparison.Ordinal) == true;
}

public static IActionResult LoadingPage(this Controller controller, string viewName, string redirectUri)
{
controller.HttpContext.Response.StatusCode = 200;
controller.HttpContext.Response.Headers["Location"] = "";

return controller.View(viewName, new RedirectViewModel { RedirectUrl = redirectUri });
public static IActionResult LoadingPage(this Controller controller, string viewName, string redirectUri)
{
controller.HttpContext.Response.StatusCode = 200;
controller.HttpContext.Response.Headers["Location"] = "";

return controller.View(viewName, new RedirectViewModel { RedirectUrl = redirectUri });
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,20 @@ public IActionResult Challenge(string scheme, string returnUrl)
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}

// start challenge and roundtrip the return URL and scheme
var props = new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(Callback)),
RedirectUri = Url.Action(nameof(Callback)),
Items =
{
{ "returnUrl", returnUrl },
{ "returnUrl", returnUrl },
{ "scheme", scheme },
}
};

return Challenge(props, scheme);

}

/// <summary>
Expand Down Expand Up @@ -112,14 +112,14 @@ public async Task<IActionResult> Callback()
var additionalLocalClaims = new List<Claim>();
var localSignInProps = new AuthenticationProperties();
ProcessLoginCallback(result, additionalLocalClaims, localSignInProps);

// issue authentication cookie for user
// we must issue the cookie maually, and can't use the SignInManager because
// it doesn't expose an API to issue additional claims from the login workflow
var principal = await _signInManager.CreateUserPrincipalAsync(user);
additionalLocalClaims.AddRange(principal.Claims);
var name = principal.FindFirst(JwtClaimTypes.Name)?.Value ?? user.Id;

var isuser = new IdentityServerUser(user.Id)
{
DisplayName = name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ private async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, Conse
vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();

var apiScopes = new List<ScopeViewModel>();
foreach(var parsedScope in request.ValidatedResources.ParsedScopes)
foreach (var parsedScope in request.ValidatedResources.ParsedScopes)
{
var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName);
if (apiScope != null)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using System.Collections.Generic;
using System.Collections.Generic;

namespace Identity.API.Controllers.Consent
namespace Identity.API.Controllers.Consent
{
public class ConsentInputModel
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using System.Collections.Generic;
using System.Collections.Generic;

namespace Identity.API.Controllers.Consent
namespace Identity.API.Controllers.Consent
{
public class ConsentViewModel : ConsentInputModel
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ private async Task<GrantsViewModel> BuildViewModelAsync()
var grants = await _interaction.GetAllUserGrantsAsync();

var list = new List<GrantViewModel>();
foreach(var grant in grants)
foreach (var grant in grants)
{
var client = await _clients.FindClientByIdAsync(grant.ClientId);
if (client != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : ba
{
}

protected override void OnModelCreating(ModelBuilder builder)
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,44 +11,44 @@

namespace Identity.API.Data
{
[ExcludeFromCodeCoverage]
public class RestaurantDbContextSeed
{
public async Task SeedAsync(
ILogger<RestaurantDbContextSeed> logger,
IConfiguration configuration,
RoleManager<IdentityRole> roleManager,
UserManager<ApplicationUser> userManager)
{
var policy = CreatePolicy(logger, nameof(RestaurantDbContextSeed));
[ExcludeFromCodeCoverage]
public class RestaurantDbContextSeed
{
public async Task SeedAsync(
ILogger<RestaurantDbContextSeed> logger,
IConfiguration configuration,
RoleManager<IdentityRole> roleManager,
UserManager<ApplicationUser> userManager)
{
var policy = CreatePolicy(logger, nameof(RestaurantDbContextSeed));

await policy.ExecuteAsync(async () =>
{
var roleNames = configuration.GetSection("UserSettings:DefaultRoles").Get<List<string>>();
foreach (var roleName in roleNames)
{
var roleExist = await roleManager.RoleExistsAsync(roleName);
if (!roleExist)
await roleManager.CreateAsync(new IdentityRole(roleName));
}
await policy.ExecuteAsync(async () =>
{
var roleNames = configuration.GetSection("UserSettings:DefaultRoles").Get<List<string>>();
foreach (var roleName in roleNames)
{
var roleExist = await roleManager.RoleExistsAsync(roleName);
if (!roleExist)
await roleManager.CreateAsync(new IdentityRole(roleName));
}
var user = await userManager.FindByEmailAsync(configuration["UserSettings:AdminEmail"]);
var user = await userManager.FindByEmailAsync(configuration["UserSettings:AdminEmail"]);
if (user == null)
{
var admin = new ApplicationUser
{
UserName = configuration["UserSettings:AdminEmail"],
Email = configuration["UserSettings:AdminEmail"]
};
if (user == null)
{
var admin = new ApplicationUser
{
UserName = configuration["UserSettings:AdminEmail"],
Email = configuration["UserSettings:AdminEmail"]
};
var password = configuration["UserSettings:AdminPassword"];
var createPowerUser = await userManager.CreateAsync(admin, password);
var password = configuration["UserSettings:AdminPassword"];
var createPowerUser = await userManager.CreateAsync(admin, password);
if (createPowerUser.Succeeded)
await userManager.AddToRoleAsync(admin, "Admin");
}
});
}
}
if (createPowerUser.Succeeded)
await userManager.AddToRoleAsync(admin, "Admin");
}
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,41 +11,41 @@
namespace Identity.API.Facades
{
[ExcludeFromCodeCoverage]
public class UserManagerFacade : IUserManagerFacade
{
private readonly UserManager<ApplicationUser> _userManager;

public UserManagerFacade(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}

public Task<IdentityResult> Create(ApplicationUser applicationUser, string password)
{
return _userManager.CreateAsync(applicationUser, password);
}

public async Task<ApplicationUser> GetAsync(ClaimsPrincipal principal)
{
var userId = principal.FindFirst(ClaimTypes.NameIdentifier).Value;

var result = await _userManager.Users
.Include(x => x.UserProfile)
.SingleOrDefaultAsync(x => x.Id == userId);

return result;
}

public IEnumerable<ApplicationUser> GetAllUsers()
{
return _userManager.Users
.Include(x => x.UserProfile)
.ToList();
}

public Task<IdentityResult> UpdateAsync(ApplicationUser applicationUser)
{
return _userManager.UpdateAsync(applicationUser);
}
}
public class UserManagerFacade : IUserManagerFacade
{
private readonly UserManager<ApplicationUser> _userManager;

public UserManagerFacade(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}

public Task<IdentityResult> Create(ApplicationUser applicationUser, string password)
{
return _userManager.CreateAsync(applicationUser, password);
}

public async Task<ApplicationUser> GetAsync(ClaimsPrincipal principal)
{
var userId = principal.FindFirst(ClaimTypes.NameIdentifier).Value;

var result = await _userManager.Users
.Include(x => x.UserProfile)
.SingleOrDefaultAsync(x => x.Id == userId);

return result;
}

public IEnumerable<ApplicationUser> GetAllUsers()
{
return _userManager.Users
.Include(x => x.UserProfile)
.ToList();
}

public Task<IdentityResult> UpdateAsync(ApplicationUser applicationUser)
{
return _userManager.UpdateAsync(applicationUser);
}
}
}
Loading

0 comments on commit ad9929a

Please sign in to comment.