This commit is contained in:
Paul Schneider 2026-02-28 21:17:54 +00:00
commit 40e8e08690
3487 changed files with 39 additions and 21 deletions

View file

@ -0,0 +1,210 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Abstract.Identity;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Server.Helpers;
using Yavsc.ViewModels;
using Yavsc.ViewModels.Administration;
namespace Yavsc.Controllers
{
[Authorize()]
public class AdministrationController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly ApplicationDbContext _dbContext;
public AdministrationController(UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
ApplicationDbContext context)
{
_userManager = userManager;
_roleManager = roleManager;
this._dbContext = context;
}
[Authorize("AdministratorOnly")]
public async Task<IActionResult> Role(string id)
{
var role = await _roleManager.FindByIdAsync(id);
if (role == null) return NotFound();
RoleUserCollection roleUserCollection = new RoleUserCollection
{
Id = id,
Name = role.Name,
Users = (await this._userManager.GetUsersInRoleAsync(role.Name))
.Select(u => new UserInfo(id, u.UserName, u.Email, u.Avatar)).ToArray()
};
return View(roleUserCollection);
}
private async Task<bool> EnsureRoleList()
{
// ensure all roles existence
foreach (string roleName in new string[] {
Constants.AdminGroupName,
Constants.StarGroupName,
Constants.PerformerGroupName,
Constants.FrontOfficeGroupName,
Constants.StarHunterGroupName,
Constants.BlogModeratorGroupName
})
if (!await _roleManager.RoleExistsAsync(roleName))
{
var role = new IdentityRole { Name = roleName };
var resultCreate = await _roleManager.CreateAsync(role);
if (!resultCreate.Succeeded)
{
AddErrors(resultCreate);
}
}
if (ModelState.ErrorCount > 0) return false;
return true;
}
/// <summary>
/// Gives the new, when not existing, administrator role
/// to current authenticated user.
/// If nothing is to do, it returns a 404.
/// </summary>
/// <returns></returns>
[Produces("application/json")]
public async Task<IActionResult> Take()
{
// If some amdin already exists, make this method disapear
var admins = await _userManager.GetUsersInRoleAsync(Constants.AdminGroupName);
if (admins != null && admins.Count > 0)
{
// All is ok, nothing to do here.
if (User.IsInMsRole(Constants.AdminGroupName))
{
return Ok(new { message = "you already got it." });
}
return NotFound();
}
var user = await _userManager.FindByIdAsync(User.GetUserId());
// check all user groups exist
if (!await EnsureRoleList())
{
ModelState.AddModelError(null, "Could not ensure role list existence. aborting.");
return new BadRequestObjectResult(ModelState);
}
var addToRoleResult = await _userManager.AddToRoleAsync(user, Constants.AdminGroupName);
if (!addToRoleResult.Succeeded)
{
AddErrors(addToRoleResult);
return new BadRequestObjectResult(ModelState);
}
return Ok(new { message = "you owned it." });
}
[Authorize("AdministratorOnly")]
public async Task<IActionResult> Index()
{
var adminCount = await _userManager.GetUsersInRoleAsync(
Constants.AdminGroupName);
var userCount = await _dbContext.Users.CountAsync();
var youAreAdmin = await _userManager.IsInRoleAsync(
await _userManager.FindByIdAsync(User.GetUserId()),
Constants.AdminGroupName);
var roles = await _roleManager.Roles.Select(x => new RoleInfo
{
Id = x.Id,
Name = x.Name
}).ToArrayAsync();
foreach (var role in roles)
{
var uinrole = await _userManager.GetUsersInRoleAsync(role.Name);
role.UserCount = uinrole.Count();
}
var assembly = GetType().Assembly;
ViewBag.ThisAssembly = assembly.FullName;
ViewBag.RunTimeVersion = assembly.ImageRuntimeVersion;
var rolesArray = roles.ToArray();
return View(new AdminViewModel
{
Roles = rolesArray,
AdminCount = adminCount.Count,
YouAreAdmin = youAreAdmin,
UserCount = userCount
});
}
[Authorize("AdministratorOnly")]
public IActionResult Enroll(string roleName)
{
ViewBag.UserId = new SelectList(_dbContext.Users, "Id", "UserName");
return View(new EnrolerViewModel { RoleName = roleName });
}
[Authorize("AdministratorOnly")]
[HttpPost()]
public async Task<IActionResult> Enroll(EnrolerViewModel model)
{
if (ModelState.IsValid)
{
var newAdmin = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == model.EnroledUserId);
if (newAdmin == null) return NotFound();
var addToRoleResult = await _userManager.AddToRoleAsync(newAdmin, model.RoleName);
if (addToRoleResult.Succeeded)
{
return RedirectToAction("Index");
}
AddErrors(addToRoleResult);
}
ViewBag.UserId = new SelectList(_dbContext.Users, "Id", "UserName");
return View(model);
}
[Authorize("AdministratorOnly")]
public async Task<IActionResult> Fire(string roleName, string userId)
{
var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
if (user == null) return NotFound();
return View(new FireViewModel { RoleName = roleName, EnroledUserId = userId, EnroledUserName = user.UserName });
}
[Authorize("AdministratorOnly")]
[HttpPost()]
public async Task<IActionResult> Fire(FireViewModel model)
{
if (ModelState.IsValid)
{
var oldEnroled = await _dbContext.Users.FirstOrDefaultAsync(u => u.Id == model.EnroledUserId);
if (oldEnroled == null) return NotFound();
var removeFromRole = await _userManager.RemoveFromRoleAsync(oldEnroled, model.RoleName);
if (removeFromRole.Succeeded)
{
return RedirectToAction("Index");
}
AddErrors(removeFromRole);
}
ViewBag.UserId = new SelectList(_dbContext.Users, "Id", "UserName");
return View(model);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
}

View file

@ -0,0 +1,147 @@
using IdentityServer8.EntityFramework.DbContexts;
using IdentityServer8.EntityFramework.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Models;
using Yavsc.Models.Auth;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class ClientController : Controller
{
private readonly ConfigurationDbContext _context;
public ClientController(ConfigurationDbContext context)
{
_context = context;
}
// GET: Client
public async Task<IActionResult> Index()
{
return View(await _context.Clients.Include(c=>c.AllowedGrantTypes)
.Include(c=>c.RedirectUris).ToListAsync());
}
// GET: Client/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return NotFound();
}
Client client = await _context.Clients.Include(
c => c.ClientSecrets
).Include(c=>c.AllowedGrantTypes)
.Include(c=>c.RedirectUris)
.SingleAsync(m => m.ClientId == id);
if (client == null)
{
return NotFound();
}
return View(client);
}
// GET: Client/Create
public IActionResult Create()
{
SetAppTypesInputValues();
return View();
}
// POST: Client/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Client client)
{
if (ModelState.IsValid)
{
if (string.IsNullOrWhiteSpace(client.ClientId))
client.ClientId = Guid.NewGuid().ToString();
_context.Clients.Add(client);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
SetAppTypesInputValues();
return View(client);
}
private void SetAppTypesInputValues()
{
IEnumerable<SelectListItem> types = new SelectListItem[] {
new SelectListItem {
Text = ApplicationTypes.JavaScript.ToString(),
Value = ((int) ApplicationTypes.JavaScript).ToString() },
new SelectListItem {
Text = ApplicationTypes.NativeConfidential.ToString(),
Value = ((int) ApplicationTypes.NativeConfidential).ToString()
}
};
ViewData["AccessTokenType"] = types;
}
// GET: Client/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return NotFound();
}
Client client = await _context.Clients.SingleAsync(m => m.ClientId == id);
if (client == null)
{
return NotFound();
}
SetAppTypesInputValues();
return View(client);
}
// POST: Client/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Client client)
{
if (ModelState.IsValid)
{
_context.Update(client);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(client);
}
// GET: Client/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return NotFound();
}
Client client = await _context.Clients.SingleAsync(m => m.ClientId == id);
if (client == null)
{
return NotFound();
}
return View(client);
}
// POST: Client/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
Client client = await _context.Clients.SingleAsync(m => m.ClientId == id);
_context.Clients.Remove(client);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}

View file

@ -0,0 +1,72 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Yavsc.Models;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class DatabaseController : Controller
{
private readonly ILogger<DatabaseController> logger;
private readonly ApplicationDbContext applicationDbContext;
public DatabaseController(ApplicationDbContext applicationDbContext,
ILoggerFactory loggerFactory)
{
logger = loggerFactory.CreateLogger<DatabaseController>();
this.applicationDbContext = applicationDbContext;
}
public IActionResult GetBlog()
{
return ReturnDbSet(applicationDbContext.BlogSpot);
}
public IActionResult GetUsers()
{
return ReturnDbSet(applicationDbContext.Users);
}
public IActionResult GeActivities()
{
return ReturnDbSet(applicationDbContext.Activities);
}
public IActionResult ImportUsers(String usersJson)
{
return DBSetImportFromJson(applicationDbContext.Users, usersJson);
}
public IActionResult ImportBlog(String blogJson)
{
return DBSetImportFromJson(applicationDbContext.BlogSpot, blogJson);
}
IActionResult ReturnDbSet<T>(DbSet<T> dbSet) where T : class
{
var data = dbSet.ToArray();
return Ok(data);
}
private IActionResult DBSetImportFromJson<T>(DbSet<T> dbSet, string usersJson) where T : class
{
int failures = 0;
var input = JsonConvert.DeserializeObject<T[]>(usersJson);
foreach (var user in input)
{
try
{
dbSet.Add(user);
}
catch (Exception ex)
{
failures++;
}
}
return Ok(failures);
}
}
}

View file

@ -0,0 +1,158 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Yavsc.Models;
using Yavsc.Models.Calendar;
using Yavsc.Server.Models.EMailing;
using Microsoft.AspNetCore.Authorization;
using Yavsc.Server.Settings;
using Microsoft.EntityFrameworkCore;
using Yavsc.Helpers;
using Yavsc.Server.Models.Calendar;
using Yavsc.Server.Helpers;
namespace Yavsc.Controllers
{
[Authorize("AdministratorOnly")]
public class MailingTemplateController : Controller
{
private readonly ApplicationDbContext _context;
private readonly ILogger logger;
public MailingTemplateController(ApplicationDbContext context,
ILoggerFactory loggerFactory)
{
_context = context;
logger = loggerFactory.CreateLogger<MailingTemplateController>();
}
// GET: MailingTemplate
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.MailingTemplate;
return View(await applicationDbContext.ToListAsync());
}
// GET: MailingTemplate/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return NotFound();
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return NotFound();
}
return View(mailingTemplate);
}
List<SelectListItem> GetSelectFromEnum(Type enumType)
{
var list = new List<SelectListItem>();
foreach (var v in enumType.GetEnumValues())
{
list.Add(new SelectListItem { Value = v.ToString(), Text = enumType.GetEnumName(v) });
}
return list;
}
private void SetupViewBag()
{
ViewBag.ManagerId = new SelectList(_context.ApplicationUser, "Id", "UserName");
ViewBag.ToSend = GetSelectFromEnum(typeof(Periodicity));
ViewBag.Id = UserPolicies.Criterias.Select(
c => new SelectListItem{ Text = c.Key, Value = c.Key }).ToList();
}
// GET: MailingTemplate/Create
public IActionResult Create()
{
SetupViewBag();
return View();
}
// POST: MailingTemplate/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(MailingTemplate mailingTemplate)
{
if (ModelState.IsValid)
{
_context.MailingTemplate.Add(mailingTemplate);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
SetupViewBag();
return View(mailingTemplate);
}
// GET: MailingTemplate/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return NotFound();
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return NotFound();
}
SetupViewBag();
return View(mailingTemplate);
}
// POST: MailingTemplate/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(MailingTemplate mailingTemplate)
{
if (ModelState.IsValid)
{
_context.Update(mailingTemplate);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
SetupViewBag();
return View(mailingTemplate);
}
// GET: MailingTemplate/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return NotFound();
}
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
if (mailingTemplate == null)
{
return NotFound();
}
return View(mailingTemplate);
}
// POST: MailingTemplate/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
MailingTemplate mailingTemplate = await _context.MailingTemplate.SingleAsync(m => m.Id == id);
_context.MailingTemplate.Remove(mailingTemplate);
await _context.SaveChangesAsync(User.GetUserId());
return RedirectToAction("Index");
}
}
}