refact
This commit is contained in:
parent
5de53a3cba
commit
476d35ae8a
270 changed files with 477 additions and 401 deletions
260
src/isnd/Controllers/AccountController.cs
Normal file
260
src/isnd/Controllers/AccountController.cs
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
|
||||
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
|
||||
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using isn.Data;
|
||||
using isn.Data.Roles;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace isn.Controllers
|
||||
{
|
||||
[AllowAnonymous]
|
||||
public class AccountController : Controller
|
||||
{
|
||||
private readonly IAuthenticationSchemeProvider _schemeProvider;
|
||||
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly AdminStartupList _startupAdminList;
|
||||
|
||||
public AccountController(
|
||||
IAuthenticationSchemeProvider schemeProvider,
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IOptions<AdminStartupList> startupAdminListConfig )
|
||||
{
|
||||
_schemeProvider = schemeProvider;
|
||||
_signInManager = signInManager;
|
||||
_userManager = userManager;
|
||||
_startupAdminList = startupAdminListConfig.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Entry point into the login workflow
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Login(string returnUrl)
|
||||
{
|
||||
// build a model so we know what to show on the login page
|
||||
var vm = await BuildLoginViewModelAsync(returnUrl);
|
||||
|
||||
if (vm.IsExternalLoginOnly)
|
||||
{
|
||||
// we only have one option for logging in and it's an external provider
|
||||
return RedirectToAction("Challenge", "External", new { scheme = vm.ExternalLoginScheme, returnUrl });
|
||||
}
|
||||
|
||||
return View(vm);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle postback from username/password login
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Login(LoginInputModel model, string button)
|
||||
{
|
||||
|
||||
// the user clicked the "cancel" button
|
||||
if (button != "login")
|
||||
{
|
||||
|
||||
// since we don't have a valid context, then we just go back to the home page
|
||||
return Redirect("~/");
|
||||
}
|
||||
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
// validate username/password
|
||||
var user = await _userManager.FindByNameAsync(model.Username);
|
||||
var signResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true);
|
||||
|
||||
if (signResult.Succeeded)
|
||||
{
|
||||
|
||||
// only set explicit expiration here if user chooses "remember me".
|
||||
// otherwise we rely upon expiration configured in cookie middleware.
|
||||
AuthenticationProperties props = null;
|
||||
if (AccountOptions.AllowRememberLogin && model.RememberLogin)
|
||||
{
|
||||
props = new AuthenticationProperties
|
||||
{
|
||||
IsPersistent = true,
|
||||
ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
|
||||
};
|
||||
};
|
||||
|
||||
await _signInManager.SignInAsync(user, model.RememberLogin && AccountOptions.AllowRememberLogin);
|
||||
if (Url.IsLocalUrl(model.ReturnUrl))
|
||||
{
|
||||
return Redirect(model.ReturnUrl);
|
||||
}
|
||||
else if (string.IsNullOrEmpty(model.ReturnUrl))
|
||||
{
|
||||
return Redirect("~/");
|
||||
}
|
||||
else
|
||||
{
|
||||
// user might have clicked on a malicious link - should be logged
|
||||
throw new Exception("invalid return URL");
|
||||
}
|
||||
}
|
||||
|
||||
ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
|
||||
}
|
||||
|
||||
// something went wrong, show form with error
|
||||
var vm = await BuildLoginViewModelAsync(model);
|
||||
return View(vm);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Show logout page
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Logout(string logoutId)
|
||||
{
|
||||
// build a model so the logout page knows what to display
|
||||
var vm = await BuildLogoutViewModelAsync(logoutId);
|
||||
|
||||
if (vm.ShowLogoutPrompt == false)
|
||||
{
|
||||
// if the request for logout was properly authenticated from IdentityServer, then
|
||||
// we don't need to show the prompt and can just log the user out directly.
|
||||
return await Logout(vm);
|
||||
}
|
||||
|
||||
return View(vm);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle logout page postback
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> Logout(LogoutInputModel model)
|
||||
{
|
||||
// build a model so the logged out page knows what to display
|
||||
var vm = await BuildLoggedOutViewModelAsync(model.LogoutId);
|
||||
|
||||
if (User?.Identity.IsAuthenticated == true)
|
||||
{
|
||||
// delete local authentication cookie
|
||||
await HttpContext.SignOutAsync();
|
||||
}
|
||||
|
||||
// check if we need to trigger sign-out at an upstream identity provider
|
||||
if (vm.TriggerExternalSignout)
|
||||
{
|
||||
// build a return URL so the upstream provider will redirect back
|
||||
// to us after the user has logged out. this allows us to then
|
||||
// complete our single sign-out processing.
|
||||
string url = Url.Action("Logout", new { logoutId = vm.LogoutId });
|
||||
|
||||
// this triggers a redirect to the external provider for sign-out
|
||||
return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme);
|
||||
}
|
||||
|
||||
return View("LoggedOut", vm);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult AccessDenied()
|
||||
{
|
||||
return new BadRequestObjectResult(403);
|
||||
}
|
||||
|
||||
|
||||
/*****************************************/
|
||||
/* helper APIs for the AccountController */
|
||||
/*****************************************/
|
||||
private async Task<LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
|
||||
{
|
||||
|
||||
|
||||
var schemes = await _schemeProvider.GetAllSchemesAsync();
|
||||
|
||||
var providers = schemes
|
||||
.Where(x => x.DisplayName != null)
|
||||
.Select(x => new ExternalProvider
|
||||
{
|
||||
DisplayName = x.DisplayName ?? x.Name,
|
||||
AuthenticationScheme = x.Name
|
||||
}).ToList();
|
||||
|
||||
var allowLocal = true;
|
||||
|
||||
|
||||
return new LoginViewModel
|
||||
{
|
||||
AllowRememberLogin = AccountOptions.AllowRememberLogin,
|
||||
EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
|
||||
ReturnUrl = returnUrl,
|
||||
ExternalProviders = providers.ToArray()
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<LoginViewModel> BuildLoginViewModelAsync(LoginInputModel model)
|
||||
{
|
||||
var vm = await BuildLoginViewModelAsync(model.ReturnUrl);
|
||||
vm.Username = model.Username;
|
||||
vm.RememberLogin = model.RememberLogin;
|
||||
return vm;
|
||||
}
|
||||
|
||||
private async Task<LogoutViewModel> BuildLogoutViewModelAsync(string logoutId)
|
||||
{
|
||||
var vm = new LogoutViewModel { LogoutId = logoutId, ShowLogoutPrompt = AccountOptions.ShowLogoutPrompt };
|
||||
|
||||
if (User?.Identity.IsAuthenticated != true)
|
||||
{
|
||||
// if the user is not authenticated, then just show logged out page
|
||||
vm.ShowLogoutPrompt = false;
|
||||
return vm;
|
||||
}
|
||||
|
||||
// show the logout prompt. this prevents attacks where the user
|
||||
// is automatically signed out by another malicious web page.
|
||||
return vm;
|
||||
}
|
||||
|
||||
private async Task<LoggedOutViewModel> BuildLoggedOutViewModelAsync(string logoutId)
|
||||
{
|
||||
|
||||
var vm = new LoggedOutViewModel
|
||||
{
|
||||
AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut,
|
||||
LogoutId = logoutId
|
||||
};
|
||||
|
||||
return vm;
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
public async Task<IActionResult> GetAdminrole()
|
||||
{
|
||||
string username = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (_startupAdminList.Users.Contains(username))
|
||||
{
|
||||
var user = await _userManager.FindByNameAsync(username);
|
||||
var roles = await _userManager.GetRolesAsync(user);
|
||||
if (!roles.Contains(Constants.AdministratorRoleName))
|
||||
{
|
||||
await _userManager.AddToRoleAsync(user, Constants.AdministratorRoleName);
|
||||
|
||||
}
|
||||
return Ok();
|
||||
}
|
||||
return BadRequest();
|
||||
}
|
||||
}
|
||||
}
|
||||
147
src/isnd/Controllers/ApiKeysController.cs
Normal file
147
src/isnd/Controllers/ApiKeysController.cs
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Rendering;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using isn.Data;
|
||||
using isn.Entities;
|
||||
using isn.Data.ApiKeys;
|
||||
|
||||
|
||||
namespace isn.Controllers
|
||||
{
|
||||
[Authorize]
|
||||
public class ApiKeysController : Controller
|
||||
{
|
||||
private readonly ApplicationDbContext dbContext;
|
||||
private readonly NugetSettings nugetSettings;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
|
||||
private readonly IDataProtector protector;
|
||||
public ApiKeysController(ApplicationDbContext dbContext,
|
||||
IOptions<NugetSettings> nugetSettingsOptions,
|
||||
IDataProtectionProvider provider,
|
||||
UserManager<ApplicationUser> userManager)
|
||||
{
|
||||
this.dbContext = dbContext;
|
||||
this.nugetSettings = nugetSettingsOptions.Value;
|
||||
protector = provider.CreateProtector(nugetSettings.ProtectionTitle);
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult> Index()
|
||||
{
|
||||
string userid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
System.Collections.Generic.List<ApiKey> index = GetUserKeys().ToList();
|
||||
IndexModel model = new IndexModel { ApiKey = index };
|
||||
ViewData["Title"] = "Index";
|
||||
return View("Index", model);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult> Create()
|
||||
{
|
||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
var username = User.Identity.Name;
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
ViewBag.UserId = new SelectList(new List<ApplicationUser> { user });
|
||||
return View(new CreateModel{ });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<ActionResult> Create(CreateModel model)
|
||||
{
|
||||
string userid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
IQueryable<ApiKey> userKeys = GetUserKeys();
|
||||
if (userKeys.Count() >= nugetSettings.MaxUserKeyCount)
|
||||
{
|
||||
ModelState.AddModelError(null, "Maximum key count reached");
|
||||
return View();
|
||||
}
|
||||
ApiKey newKey = new ApiKey { UserId = userid, Name = model.Name,
|
||||
CreationDate = DateTime.Now };
|
||||
_ = dbContext.ApiKeys.Add(newKey);
|
||||
_ = await dbContext.SaveChangesAsync();
|
||||
return View("Details", new DetailModel { Name = newKey.Name,
|
||||
ProtectedValue = protector.Protect(newKey.Id),
|
||||
ApiKey = newKey });
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult> Delete(string id)
|
||||
{
|
||||
string userid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
ApiKey key = dbContext.ApiKeys.FirstOrDefault(k => k.Id == id && k.UserId == userid);
|
||||
return View(new DeleteModel { ApiKey = key });
|
||||
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<ActionResult> Delete(DeleteModel model)
|
||||
{
|
||||
string userid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
ApiKey key = dbContext.ApiKeys.FirstOrDefault(k => k.Id == model.ApiKey.Id && k.UserId == userid);
|
||||
if (key == null)
|
||||
{
|
||||
ModelState.AddModelError(null, "Key not found");
|
||||
return View();
|
||||
}
|
||||
_ = dbContext.ApiKeys.Remove(key);
|
||||
_ = await dbContext.SaveChangesAsync();
|
||||
return View("Index", new IndexModel { ApiKey = GetUserKeys().ToList() } );
|
||||
}
|
||||
|
||||
public async Task<ActionResult> Details(string id)
|
||||
{
|
||||
string userid = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
ApiKey key = await dbContext.ApiKeys.FirstOrDefaultAsync(k => k.Id == id && k.UserId == userid);
|
||||
if (key == null)
|
||||
{
|
||||
ModelState.AddModelError(null, "Key not found");
|
||||
return View();
|
||||
}
|
||||
return View("Details", new DetailModel { ApiKey = key, Name = key.Name, ProtectedValue = protector.Protect(key.Id)});
|
||||
|
||||
}
|
||||
|
||||
public async Task<ActionResult> Edit(string id)
|
||||
{
|
||||
|
||||
EditModel edit = new EditModel();
|
||||
string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
|
||||
edit.ApiKey = await GetUserKeys().SingleOrDefaultAsync(k =>
|
||||
k.UserId == userId && k.Id == id);
|
||||
ViewBag.UserId = new SelectList(new List<ApplicationUser> { user });
|
||||
|
||||
return View(edit);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<ActionResult> Edit(EditModel model)
|
||||
{
|
||||
string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
|
||||
var apiKey = await dbContext.ApiKeys.SingleOrDefaultAsync(k => k.UserId == userId && k.Id == model.ApiKey.Id);
|
||||
apiKey.Name = model.ApiKey.Name;
|
||||
apiKey.ValidityPeriodInDays = model.ApiKey.ValidityPeriodInDays;
|
||||
await dbContext.SaveChangesAsync();
|
||||
return View("Details", new DetailModel { ApiKey = apiKey });
|
||||
}
|
||||
|
||||
public IQueryable<ApiKey> GetUserKeys()
|
||||
{
|
||||
return dbContext.ApiKeys.Include(k => k.User).Where(k => k.User.UserName == User.Identity.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
68
src/isnd/Controllers/HomeController.cs
Normal file
68
src/isnd/Controllers/HomeController.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using isn.Entities;
|
||||
using isn.Data;
|
||||
using System.Linq;
|
||||
using isn.ViewModels;
|
||||
using Unleash.ClientFactory;
|
||||
using Unleash;
|
||||
|
||||
namespace isn.Controllers
|
||||
{
|
||||
public class HomeController : Controller
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
readonly IHostingEnvironment _environment;
|
||||
public SmtpSettings _smtpSettings { get; } //set only via Secret Manager
|
||||
|
||||
private ApplicationDbContext _dbContext;
|
||||
|
||||
public HomeController(
|
||||
IOptions<SmtpSettings> smtpSettings,
|
||||
IHostingEnvironment environment,
|
||||
ApplicationDbContext dbContext,
|
||||
ILogger<HomeController> logger)
|
||||
{
|
||||
_environment = environment;
|
||||
_logger = logger;
|
||||
_smtpSettings = smtpSettings.Value;
|
||||
_dbContext = dbContext;
|
||||
}
|
||||
|
||||
public IActionResult Index()
|
||||
{
|
||||
return View(new HomeIndexViewModel{
|
||||
PkgCount = _dbContext.Packages.Count(),
|
||||
UnleashClient = Startup.UnleashĈlient
|
||||
});
|
||||
}
|
||||
|
||||
public IActionResult About()
|
||||
{
|
||||
ViewData["Message"] = "Your application description page.";
|
||||
|
||||
return View();
|
||||
}
|
||||
|
||||
public IActionResult Contact()
|
||||
{
|
||||
ViewData["Message"] = "Your contact page.";
|
||||
|
||||
return View();
|
||||
}
|
||||
|
||||
public IActionResult Privacy()
|
||||
{
|
||||
ViewData["Message"] = "Your Privacy page.";
|
||||
|
||||
return View(ViewData);
|
||||
}
|
||||
|
||||
public IActionResult Error()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
}
|
||||
}
|
||||
17
src/isnd/Controllers/NewUpdateController.cs
Normal file
17
src/isnd/Controllers/NewUpdateController.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
using System;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using isn.Data;
|
||||
|
||||
namespace isn.Controllers
|
||||
{
|
||||
|
||||
public class NewUpdateController : Controller
|
||||
{
|
||||
[Authorize(Policy = Constants.RequireAdminPolicyName)]
|
||||
public IActionResult NewRelease(NewReleaseInfo version)
|
||||
{
|
||||
return View(version);
|
||||
}
|
||||
}
|
||||
}
|
||||
93
src/isnd/Controllers/PackageVersionController.cs
Normal file
93
src/isnd/Controllers/PackageVersionController.cs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using isn.Data;
|
||||
using isn.ViewModels;
|
||||
|
||||
namespace isn
|
||||
{
|
||||
[AllowAnonymous]
|
||||
public class PackageVersionController : Controller
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
|
||||
public PackageVersionController(ApplicationDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: PackageVersion
|
||||
public async Task<IActionResult> Index(PackageVersionIndexViewModel model)
|
||||
{
|
||||
var applicationDbContext = _context.PackageVersions.Include(p => p.Package).Where(p => p.PackageId == model.PackageId);
|
||||
|
||||
model.Versions = await applicationDbContext.ToListAsync();
|
||||
|
||||
return View(model);
|
||||
}
|
||||
|
||||
// GET: PackageVersion/Details/5
|
||||
public async Task<IActionResult> Details(string pkgid, string version)
|
||||
{
|
||||
if (pkgid == null || version == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
var packageVersion = await _context.PackageVersions
|
||||
.Include(p => p.Package)
|
||||
.FirstOrDefaultAsync(m => m.PackageId == pkgid && m.FullString == version);
|
||||
if (packageVersion == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
return View(packageVersion);
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
public async Task<IActionResult> Delete(string pkgid, string version)
|
||||
{
|
||||
if (pkgid == null || version == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
var packageVersion = await _context.PackageVersions
|
||||
.Include(p => p.Package)
|
||||
.FirstOrDefaultAsync(m => m.PackageId == pkgid && m.FullString == version);
|
||||
if (packageVersion == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
if (!IsOwner(packageVersion)) return Unauthorized();
|
||||
|
||||
return View(packageVersion);
|
||||
}
|
||||
|
||||
bool IsOwner(PackageVersion v)
|
||||
{
|
||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
return v.Package.OwnerId == userId;
|
||||
}
|
||||
|
||||
// POST: PackageVersion/Delete/5
|
||||
[HttpPost, ActionName("Delete")]
|
||||
[ValidateAntiForgeryToken]
|
||||
public async Task<IActionResult> DeleteConfirmed(string PackageId, string FullString)
|
||||
{
|
||||
var packageVersion = await _context.PackageVersions.Include(p => p.Package)
|
||||
.FirstOrDefaultAsync(m => m.PackageId == PackageId && m.FullString == FullString);
|
||||
if (packageVersion == null) return NotFound();
|
||||
if (!IsOwner(packageVersion)) return Unauthorized();
|
||||
|
||||
_context.PackageVersions.Remove(packageVersion);
|
||||
await _context.SaveChangesAsync();
|
||||
return RedirectToAction(nameof(Index));
|
||||
}
|
||||
}
|
||||
}
|
||||
173
src/isnd/Controllers/PackagesController.Put.cs
Normal file
173
src/isnd/Controllers/PackagesController.Put.cs
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NuGet.Packaging.Core;
|
||||
using NuGet.Versioning;
|
||||
using isn.Data;
|
||||
using isn.Helpers;
|
||||
|
||||
namespace isn.Controllers
|
||||
{
|
||||
|
||||
public partial class PackagesController
|
||||
{
|
||||
|
||||
[HttpPut("packages")]
|
||||
public async Task<IActionResult> Put()
|
||||
{
|
||||
try
|
||||
{
|
||||
var clientVersionId = Request.Headers["X-NuGet-Client-Version"];
|
||||
var apiKey = Request.Headers["X-NuGet-ApiKey"];
|
||||
ViewData["versionId"] = typeof(PackagesController).Assembly.FullName;
|
||||
var files = new List<string>();
|
||||
ViewData["files"] = files;
|
||||
|
||||
var clearkey = protector.Unprotect(apiKey);
|
||||
var apikey = dbContext.ApiKeys.SingleOrDefault(k => k.Id == clearkey);
|
||||
if (apikey == null)
|
||||
{
|
||||
logger.LogError("403 : no api-key");
|
||||
return Unauthorized();
|
||||
}
|
||||
|
||||
foreach (var file in Request.Form.Files)
|
||||
{
|
||||
string initpath = Path.Combine(Environment.GetEnvironmentVariable("TEMP") ??
|
||||
Environment.GetEnvironmentVariable("TMP") ?? "/tmp",
|
||||
$"isn-{Guid.NewGuid()}.nupkg");
|
||||
|
||||
using (FileStream fw = new FileStream(initpath, FileMode.Create))
|
||||
{
|
||||
file.CopyTo(fw);
|
||||
}
|
||||
|
||||
using (FileStream fw = new FileStream(initpath, FileMode.Open))
|
||||
{
|
||||
var archive = new ZipArchive(fw);
|
||||
|
||||
var nuspec = archive.Entries.FirstOrDefault(e => e.FullName.EndsWith(".nuspec"));
|
||||
if (nuspec == null) return BadRequest(new { error = "no nuspec from archive" });
|
||||
string pkgpath;
|
||||
NuGetVersion version;
|
||||
string pkgid;
|
||||
string fullpath;
|
||||
|
||||
using (var specstr = nuspec.Open())
|
||||
{
|
||||
NuspecCoreReader reader = new NuspecCoreReader(specstr);
|
||||
|
||||
string pkgdesc = reader.GetDescription();
|
||||
var types = reader.GetPackageTypes();
|
||||
pkgid = reader.GetId();
|
||||
version = reader.GetVersion();
|
||||
|
||||
string pkgidpath = Path.Combine(nugetSettings.PackagesRootDir,
|
||||
pkgid);
|
||||
pkgpath = Path.Combine(pkgidpath, version.ToFullString());
|
||||
string name = $"{pkgid}-{version}.nupkg";
|
||||
fullpath = Path.Combine(pkgpath, name);
|
||||
|
||||
var destpkgiddir = new DirectoryInfo(pkgidpath);
|
||||
Package package = dbContext.Packages.SingleOrDefault(p => p.Id == pkgid);
|
||||
if (package != null)
|
||||
{
|
||||
if (package.OwnerId != apikey.UserId)
|
||||
{
|
||||
return new ForbidResult();
|
||||
}
|
||||
package.Description = pkgdesc;
|
||||
}
|
||||
else
|
||||
{
|
||||
package = new Package
|
||||
{
|
||||
Id = pkgid,
|
||||
Description = pkgdesc,
|
||||
OwnerId = apikey.UserId
|
||||
};
|
||||
dbContext.Packages.Add(package);
|
||||
}
|
||||
if (!destpkgiddir.Exists) destpkgiddir.Create();
|
||||
|
||||
var source = new FileInfo(initpath);
|
||||
var dest = new FileInfo(fullpath);
|
||||
var destdir = new DirectoryInfo(dest.DirectoryName);
|
||||
if (dest.Exists)
|
||||
{
|
||||
ViewData["msg"] = "existant";
|
||||
ViewData["ecode"] = 1;
|
||||
logger.LogWarning("400 : existant");
|
||||
return base.BadRequest(new { error = ModelState });
|
||||
}
|
||||
else
|
||||
{
|
||||
destdir.Create();
|
||||
source.MoveTo(fullpath);
|
||||
files.Add(name);
|
||||
string fullstringversion = version.ToFullString();
|
||||
var pkgvers = dbContext.PackageVersions.Where
|
||||
(v => v.PackageId == package.Id && v.FullString == fullstringversion);
|
||||
if (pkgvers.Count() > 0)
|
||||
{
|
||||
foreach (var v in pkgvers.ToArray())
|
||||
dbContext.PackageVersions.Remove(v);
|
||||
}
|
||||
foreach (var type in types)
|
||||
{
|
||||
var pkgver = new PackageVersion
|
||||
{
|
||||
Package = package,
|
||||
Major = version.Major,
|
||||
Minor = version.Minor,
|
||||
Patch = version.Patch,
|
||||
IsPrerelease = version.IsPrerelease,
|
||||
FullString = version.ToFullString(),
|
||||
Type = type.Name
|
||||
};
|
||||
dbContext.PackageVersions.Add(pkgver);
|
||||
}
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
logger.LogInformation($"new package : {nuspec.Name}");
|
||||
}
|
||||
}
|
||||
using (var shacrypto = System.Security.Cryptography.SHA512.Create())
|
||||
{
|
||||
using (var stream = System.IO.File.OpenRead(fullpath))
|
||||
{
|
||||
var hash = shacrypto.ComputeHash(stream);
|
||||
var shafullname = fullpath + ".sha512";
|
||||
var hashtext = Convert.ToBase64String(hash);
|
||||
var hashtextbytes = Encoding.ASCII.GetBytes(hashtext);
|
||||
|
||||
using (var shafile = System.IO.File.OpenWrite(shafullname))
|
||||
{
|
||||
shafile.Write(hashtextbytes, 0, hashtextbytes.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
nuspec.ExtractToFile(Path.Combine(pkgpath, pkgid + ".nuspec"));
|
||||
}
|
||||
|
||||
}
|
||||
return Ok(ViewData);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex.Message);
|
||||
logger.LogError("Stack Trace: " + ex.StackTrace);
|
||||
return new ObjectResult(new { ViewData, ex.Message })
|
||||
{ StatusCode = 500 };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
173
src/isnd/Controllers/PackagesController.cs
Normal file
173
src/isnd/Controllers/PackagesController.cs
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
using System.ComponentModel.DataAnnotations;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NuGet.Versioning;
|
||||
using isn.Data;
|
||||
using isn.Entities;
|
||||
using Unleash.ClientFactory;
|
||||
using Unleash;
|
||||
using System.Collections.Generic;
|
||||
using isnd.Services;
|
||||
|
||||
namespace isn.Controllers
|
||||
{
|
||||
|
||||
[AllowAnonymous]
|
||||
public partial class PackagesController : Controller
|
||||
{
|
||||
const int maxTake = 100;
|
||||
|
||||
const string _pkgRootPrefix = "~/package";
|
||||
const string defaultSemVer = "2.0.0";
|
||||
private readonly Resource[] ressources;
|
||||
private readonly ILogger<PackagesController> logger;
|
||||
private readonly IDataProtector protector;
|
||||
|
||||
private readonly NugetSettings nugetSettings;
|
||||
ApplicationDbContext dbContext;
|
||||
private PackageManager packageManager;
|
||||
|
||||
public PackagesController(
|
||||
PackageManager packageManager,
|
||||
ILoggerFactory loggerFactory,
|
||||
IDataProtectionProvider provider,
|
||||
IOptions<NugetSettings> nugetOptions,
|
||||
ApplicationDbContext dbContext)
|
||||
{
|
||||
logger = loggerFactory.CreateLogger<PackagesController>();
|
||||
nugetSettings = nugetOptions.Value;
|
||||
protector = provider.CreateProtector(nugetSettings.ProtectionTitle);
|
||||
this.dbContext = dbContext;
|
||||
this.packageManager = packageManager;
|
||||
|
||||
ressources = packageManager.GetResources(Startup.UnleashĈlient).ToArray();
|
||||
}
|
||||
|
||||
// dotnet add . package -s http://localhost:5000/packages isn
|
||||
// packages/FindPackagesById()?id='isn'&semVerLevel=2.0.0
|
||||
|
||||
// Search
|
||||
// GET {@id}?q={QUERY}&skip={SKIP}&take={TAKE}&prerelease={PRERELEASE}&semVerLevel={SEMVERLEVEL}&packageType={PACKAGETYPE}
|
||||
|
||||
|
||||
[HttpGet("~/index.json")]
|
||||
public IActionResult ApiIndex()
|
||||
{
|
||||
return Ok(ressources);
|
||||
}
|
||||
|
||||
|
||||
[HttpGet(_pkgRootPrefix + "/index.json")]
|
||||
public IActionResult Index(
|
||||
string q,
|
||||
string semVerLevel = defaultSemVer,
|
||||
bool prerelease = false,
|
||||
string packageType = null,
|
||||
int skip = 0,
|
||||
int take = 25)
|
||||
{
|
||||
if (string.IsNullOrEmpty(q))
|
||||
{
|
||||
ModelState.AddModelError("q", "no value");
|
||||
}
|
||||
if (take > maxTake)
|
||||
{
|
||||
ModelState.AddModelError("take", "Maximum exceeded");
|
||||
}
|
||||
if (ModelState.IsValid)
|
||||
{
|
||||
return Ok(packageManager.SearchByName(q,skip,take,prerelease,packageType));
|
||||
}
|
||||
return BadRequest(new { error = ModelState });
|
||||
}
|
||||
|
||||
// GET /autocomplete?id=nuget.protocol&prerelease=true
|
||||
[HttpGet(_pkgRootPrefix + "/autocomplete")]
|
||||
public IActionResult AutoComplete(
|
||||
string id,
|
||||
string semVerLevel = defaultSemVer,
|
||||
bool prerelease = false,
|
||||
string packageType = null,
|
||||
int skip = 0,
|
||||
int take = 25)
|
||||
{
|
||||
if (take > maxTake)
|
||||
{
|
||||
ModelState.AddModelError("take", "Maximum exceeded");
|
||||
return BadRequest(ModelState);
|
||||
}
|
||||
|
||||
return Ok(packageManager.AutoComplete(id,skip,take,prerelease,packageType));
|
||||
}
|
||||
// TODO GET {@id}/{LOWER_ID}/index.json
|
||||
// LOWER_ID URL string yes The package ID, lowercased
|
||||
// response : versions array of strings yes The versions available
|
||||
[HttpGet(_pkgRootPrefix + "/{id}/{lower}/index.json")]
|
||||
public IActionResult GetVersions(
|
||||
string id,
|
||||
string lower,
|
||||
bool prerelease = false,
|
||||
string packageType = null,
|
||||
int skip = 0,
|
||||
int take = 25)
|
||||
{
|
||||
if (take > maxTake)
|
||||
{
|
||||
ModelState.AddModelError("take", "Maximum exceeded");
|
||||
}
|
||||
// NugetVersion
|
||||
if (!NuGetVersion.TryParse(lower, out NuGetVersion parsedVersion))
|
||||
{
|
||||
ModelState.AddModelError("lower", "invalid version string");
|
||||
}
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return BadRequest(ModelState);
|
||||
}
|
||||
return Ok(new
|
||||
{
|
||||
versions = packageManager.GetVersions(
|
||||
id, parsedVersion, prerelease, packageType, skip, take)
|
||||
});
|
||||
}
|
||||
|
||||
// TODO GET GET {@id}/{LOWER_ID}/{LOWER_VERSION}/{LOWER_ID}.{LOWER_VERSION}.nupkg
|
||||
// LOWER_ID URL string yes The package ID, lowercase
|
||||
// LOWER_VERSION URL string yes The package version, normalized and lowercased
|
||||
// response 200 : the package
|
||||
[HttpGet(_pkgRootPrefix + "/{id}/{lower}/{idf}.{lowerf}.nupkg")]
|
||||
public IActionResult GetPackage(
|
||||
[FromRoute] string id, [FromRoute] string lower,
|
||||
[FromRoute] string idf, [FromRoute] string lowerf)
|
||||
{
|
||||
var pkgpath = Path.Combine(nugetSettings.PackagesRootDir,
|
||||
id, lower, $"{idf}.{lowerf}.nupkg"
|
||||
);
|
||||
|
||||
FileInfo pkgfi = new FileInfo(pkgpath);
|
||||
return File(pkgfi.OpenRead(), "application/zip; charset=binary");
|
||||
}
|
||||
|
||||
// TODO GET {@id}/{LOWER_ID}/{LOWER_VERSION}/{LOWER_ID}.nuspec
|
||||
// response 200 : the nuspec
|
||||
[HttpGet(_pkgRootPrefix + "/{id}/{lower}/{idf}.{lowerf}.nuspec")]
|
||||
public IActionResult GetNuspec(
|
||||
[FromRoute][SafeName][Required] string id,
|
||||
[FromRoute][SafeName][Required] string lower,
|
||||
[FromRoute][SafeName][Required] string idf,
|
||||
[FromRoute][SafeName][Required] string lowerf)
|
||||
{
|
||||
var pkgpath = Path.Combine(nugetSettings.PackagesRootDir,
|
||||
id, lower, $"{idf}.{lowerf}.nuspec");
|
||||
|
||||
FileInfo pkgfi = new FileInfo(pkgpath);
|
||||
return File(pkgfi.OpenRead(), "text/xml; charset=utf-8");
|
||||
}
|
||||
}
|
||||
}
|
||||
10
src/isnd/Controllers/Resource.cs
Normal file
10
src/isnd/Controllers/Resource.cs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
namespace isn.Controllers
|
||||
{
|
||||
internal class Resource
|
||||
{
|
||||
public string id {get; set; }
|
||||
public string type {get; set; }
|
||||
public string comment {get; set; }
|
||||
|
||||
}
|
||||
}
|
||||
20
src/isnd/Controllers/SafeNameAttribute.cs
Normal file
20
src/isnd/Controllers/SafeNameAttribute.cs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
|
||||
namespace isn.Controllers
|
||||
{
|
||||
internal class SafeNameAttribute : ValidationAttribute
|
||||
{
|
||||
public override bool IsValid(object value)
|
||||
{
|
||||
if (!(value is string))
|
||||
return false;
|
||||
string str = value as string;
|
||||
if (str.Length>126) return false;
|
||||
if (str.Any(c => !char.IsLetterOrDigit(c)
|
||||
&& !"-_.".Contains(c))) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue