Repository navigation
Expand file tree
/
Copy pathBlogsController.cs
More file actions
83 lines (72 loc) · 2.68 KB
/
Copy pathBlogsController.cs
File metadata and controls
83 lines (72 loc) · 2.68 KB
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
using Blog.Common.Exceptions;
using Blog.Common.Models.Blog;
using Blog.Services.Api;
using Blog.Services.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Blog.API.Controllers
{
[Route("api")]
[ApiController]
public class BlogsController : ControllerBase
{
private readonly BlogService _blogService;
private readonly UserHelper _userHelper;
public BlogsController(BlogService blogService, UserHelper userHelper)
{
_blogService = blogService;
_userHelper = userHelper;
}
// ---- OCHIQ (login shart emas): umumiy blog-feed ----
[HttpGet("blogs")]
public async Task<IActionResult> GetAllBlogs()
{
var blogs = await _blogService.GetAllBlogs();
return Ok(blogs);
}
[HttpGet("blogs/{blogId:int}")]
public async Task<IActionResult> GetBlogById(int blogId)
{
var blog = await _blogService.GetBlogById(blogId);
return Ok(blog);
}
// ---- Muayyan foydalanuvchining bloglari ----
[HttpGet("users/{userId:guid}/blogs")]
public async Task<IActionResult> GetUserBlogs(Guid userId)
{
var blogs = await _blogService.GetUserBlogs(userId);
return Ok(blogs);
}
[HttpPost("users/{userId:guid}/blogs")]
[Authorize]
public async Task<IActionResult> AddBlog(Guid userId, [FromBody] CreateBlogModel model)
{
EnsureOwner(userId);
var blog = await _blogService.AddBlog(userId, model);
return Ok(blog);
}
[HttpPut("users/{userId:guid}/blogs/{blogId:int}")]
[Authorize]
public async Task<IActionResult> UpdateBlog(Guid userId, int blogId, [FromBody] UpdateBlogModel model)
{
EnsureOwner(userId);
var blog = await _blogService.UpdateBlog(userId, blogId, model);
return Ok(blog);
}
[HttpDelete("users/{userId:guid}/blogs/{blogId:int}")]
[Authorize]
public async Task<IActionResult> DeleteBlog(Guid userId, int blogId)
{
EnsureOwner(userId);
var message = await _blogService.DeleteBlog(userId, blogId);
return Ok(new { message });
}
// Token egasi bilan URL'dagi userId bir xil ekanligini tekshiradi -
// aks holda A foydalanuvchi B nomidan blog yaratishi/o'chirishi mumkin bo'lardi.
private void EnsureOwner(Guid userId)
{
if (_userHelper.UserId != userId)
throw new ForbiddenException("Faqat o'zingizning bloglaringizni boshqarishingiz mumkin");
}
}
}