Role-Based Upload Permissions

Role-Based Upload Permissions

Restrict uploads based on user roles. Administrators can upload any file type, while regular users are limited to images under 2 MB. The server enforces role-based rules in the upload handler regardless of client settings.

Drag & drop files here, or paste from clipboard
<%-- web.config: role-based authorization --%>
<location path="admin/upload.ashx">
 <system.web>
 <authorization>
 <allow roles="Admin" />
 <deny users="*" />
 </authorization>
 </system.web>
</location>

<%-- Upload handler with role-based validation --%>
public class UploadHandler : IHttpHandler, IRequiresSessionState
{
 public void ProcessRequest(HttpContext context)
 {
 bool isAdmin = context.User.IsInRole("Admin");
 HttpPostedFile file = context.Request.Files[0];

 if (!isAdmin)
 {
 // Regular users: images only, max 2 MB
 string[] allowed = { ".jpg", ".jpeg", ".png", ".gif" };
 string ext = Path.GetExtension(file.FileName).ToLower();

 if (!allowed.Contains(ext))
 {
 context.Response.StatusCode = 400;
 context.Response.Write("Only image files are allowed.");
 return;
 }

 if (file.ContentLength > 2 * 1024 * 1024)
 {
 context.Response.StatusCode = 400;
 context.Response.Write("File size exceeds 2 MB limit.");
 return;
 }
 }

 // Admin users: no restrictions
 file.SaveAs(Path.Combine(uploadDir, file.FileName));
 context.Response.Write("{\"fileName\":\"" + file.FileName + "\"}");
 }
}