public Func <HttpRequest, HttpResponse, ClaimsPrincipal, RouteData, Func <Task>, Task> UserInRoles( string[] roles) { return(async(request, response, user, routeData, next) => { if (user == null || !user.Identity.IsAuthenticated) { await HttpResponseSender.SendErrorAsync( response, new UnauthorizedException( null, "NOT_SIGNED", "User must be signed in to perform this operation" ).WithStatus(401) ); } else { var authorized = false; foreach (var role in roles) { if (user.IsInRole(role)) { authorized = true; break; } } if (!authorized) { await HttpResponseSender.SendErrorAsync( response, new UnauthorizedException( null, "NOT_IN_ROLE", "User must be " + String.Join(" or ", roles) + " to perform this operation" ).WithDetails("roles", roles).WithStatus(403) ); } else { await next(); } } }); }
public Func <HttpRequest, HttpResponse, ClaimsPrincipal, RouteData, Func <Task>, Task> Signed() { return (async(request, response, user, routeData, next) => { if (user == null || !user.Identity.IsAuthenticated) { await HttpResponseSender.SendErrorAsync( response, new UnauthorizedException( null, "NOT_SIGNED", "User must be signed in to perform this operation" ).WithStatus(401) ); } else { await next(); } }); }
public Func <HttpRequest, HttpResponse, ClaimsPrincipal, RouteData, Func <Task>, Task> OwnerOrAdmin( string idParam = "user_id") { return(async(request, response, user, routeData, next) => { if (user == null || !user.Identity.IsAuthenticated) { await HttpResponseSender.SendErrorAsync( response, new UnauthorizedException( null, "NOT_SIGNED", "User must be signed in to perform this operation" ).WithStatus(401) ); } else { var identity = user.Identity as ClaimsIdentity; var userIdClaim = identity?.Claims.FirstOrDefault(c => c.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier"); var isAdmin = user.IsInRole("Admin") || user.IsInRole("admin"); if (!request.Query.TryGetValue(idParam, out StringValues userId) || userIdClaim?.Value != userId.ToString() && !isAdmin) { await HttpResponseSender.SendErrorAsync( response, new UnauthorizedException( null, "FORBIDDEN", "Only data owner can perform this operation" ).WithStatus(403) ); } else { await next(); } } }); }