File size: 5,182 Bytes
70556b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
using Application.Abstractions.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RobDeliveryAPI.Extensions;
using System.Security.Claims;

namespace RobDeliveryAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class FileController : ControllerBase
    {
        private readonly IFileService _fileService;
        private readonly IWebHostEnvironment _environment;

        public FileController(
            IFileService fileService,
            IWebHostEnvironment environment)
        {
            _fileService = fileService;
            _environment = environment;
        }

        /// <summary>
        /// Get authenticated user ID from JWT token
        /// </summary>
        private int GetAuthenticatedUserId()
        {
            var userIdClaim = User.FindFirst("Id") ?? User.FindFirst(ClaimTypes.NameIdentifier);
            if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out int userId))
            {
                throw new UnauthorizedAccessException("User ID not found in token");
            }
            return userId;
        }

        /// <summary>
        /// Upload images for an order
        /// </summary>
        [HttpPost("order/{orderId}")]
        [Consumes("multipart/form-data")]
        public async Task<IActionResult> UploadOrderImages(int orderId, IFormFileCollection files)
        {
            try
            {
                int userId = GetAuthenticatedUserId();

                var uploadedFiles = await _fileService.UploadOrderImagesAsync(orderId, files.ToFileUploadDTOs(), _environment.ContentRootPath);

                return Ok(new { message = $"{uploadedFiles.Count} file(s) uploaded successfully", files = uploadedFiles });
            }
            catch (UnauthorizedAccessException ex)
            {
                return Unauthorized(new { error = ex.Message });
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = "An error occurred while uploading files", details = ex.Message });
            }
        }

        /// <summary>
        /// Delete a file
        /// </summary>
        [HttpDelete("{fileId}")]
        public async Task<IActionResult> DeleteFile(int fileId)
        {
            try
            {
                int userId = GetAuthenticatedUserId();
                bool isAdmin = User.IsInRole("Admin");

                // Check authorization
                bool isAuthorized = await _fileService.IsUserAuthorizedForFileAsync(fileId, userId, isAdmin);
                if (!isAuthorized)
                {
                    return StatusCode(403, new { error = "You do not have permission to delete this file" });
                }

                // Delete file
                var result = await _fileService.DeleteFileAsync(fileId, _environment.ContentRootPath);
                if (!result)
                {
                    return NotFound(new { error = "File not found" });
                }

                return Ok(new { message = "File deleted successfully" });
            }
            catch (UnauthorizedAccessException ex)
            {
                return Unauthorized(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = "An error occurred while deleting the file", details = ex.Message });
            }
        }

        /// <summary>
        /// Get files for an order
        /// </summary>
        [HttpGet("order/{orderId}")]
        public async Task<IActionResult> GetOrderFiles(int orderId)
        {
            try
            {
                var files = await _fileService.GetOrderFilesAsync(orderId);
                return Ok(files);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = "An error occurred while retrieving files", details = ex.Message });
            }
        }

        /// <summary>
        /// Download a file by ID
        /// </summary>
        [HttpGet("{fileId}/download")]
        [AllowAnonymous]
        public async Task<IActionResult> DownloadFile(int fileId)
        {
            try
            {
                var file = await _fileService.GetFileByIdAsync(fileId);
                if (file == null)
                {
                    return NotFound(new { error = "File not found" });
                }

                var fileBytes = await _fileService.GetFileContentAsync(fileId, _environment.ContentRootPath);
                if (fileBytes == null)
                {
                    return NotFound(new { error = "File not found on disk" });
                }

                return File(fileBytes, file.ContentType, file.FileName);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = "An error occurred while downloading the file", details = ex.Message });
            }
        }
    }
}