Feature/Auth: last one was authentication, this one is authorization #4

Merged
homeburger merged 33 commits from feature/auth into main 2026-04-23 00:18:39 -05:00
2 changed files with 89 additions and 0 deletions
Showing only changes of commit eeee94d0d6 - Show all commits

View File

@@ -0,0 +1,50 @@
// this is basically a demo on roles
// level 0 can't access the users endpoint at all
// level 1 has read permissions
// level 2 has modify permissions
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using agologumApi.Models;
using agologumApi.Services;
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase {
private readonly UserService service_;
public UsersController(UserService service) {
service_ = service;
}
[Authorize(Roles = "Admin, Superuser")]
[HttpGet]
public async Task<ActionResult<List<User>>> getUsers() {
return Ok(await service_.GetAll());
}
[Authorize(Roles = "Admin, Superuser")]
[HttpGet("{id:int}")]
public async Task<ActionResult<User>> getUser(int id) {
var user = await service_.Get(id);
if (user == null) return NotFound();
return Ok(user);
}
[Authorize(Roles = "Superuser")]
[HttpDelete("{id}")]
public async Task<ActionResult> deleteUser(int id) {
var success = await service_.Delete(id);
if (!success) return NotFound();
return NoContent();
}
}

View File

@@ -0,0 +1,39 @@
using Microsoft.EntityFrameworkCore;
using agologumApi.Models;
namespace agologumApi.Services;
public class UserService {
private readonly AppDbContext db_;
public UserService(AppDbContext db) {
db_ = db;
}
public async Task<List<User>> GetAll() {
return await db_.Users.ToListAsync();
}
public async Task<User?> Get(int id) {
return await db_.Users.FindAsync(id);
}
public async Task<User?> Get(string name) {
return await db_.Users.FirstOrDefaultAsync(u => u.UserName == name);
}
public async Task<bool> Delete(int id) {
User? User = await db_.Users.FindAsync(id);
if(User != null) {
db_.Users.Remove(User);
await db_.SaveChangesAsync();
return true;
} else {
return false;
}
}
}