update nach Schuelererfassung

This commit is contained in:
2021-08-10 16:53:27 +02:00
parent 595cd0edea
commit e16ec943e1
1318 changed files with 1538825 additions and 389 deletions

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "5.0.8",
"commands": [
"dotnet-ef"
]
}
}
}

View File

@@ -0,0 +1,35 @@
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/BlazorApp.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}

View File

@@ -0,0 +1,42 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/BlazorApp.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/BlazorApp.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"${workspaceFolder}/BlazorApp.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}

View File

@@ -0,0 +1,13 @@
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace BlazorApp.Data
{
public class BlazorAppContext : IdentityDbContext<IdentityUser>
{
public BlazorAppContext(DbContextOptions<BlazorAppContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
}

View File

@@ -0,0 +1,27 @@
using System;
using BlazorApp.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
//[assembly: HostingStartup(typeof(BlazorApp.Areas.Identity.IdentityHostingStartup))]
//namespace BlazorApp.Areas.Identity
//{
// public class IdentityHostingStartup : IHostingStartup
// {
// public void Configure(IWebHostBuilder builder)
// {
// builder.ConfigureServices((context, services) => {
// services.AddDbContext<BlazorAppContext>(options =>
// options.UseSqlServer(
// context.Configuration.GetConnectionString("BlazorAppContextConnection")));
// services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
// .AddEntityFrameworkStores<BlazorAppContext>();
// });
// }
// }
//}

View File

@@ -0,0 +1,10 @@
@page
@model AccessDeniedModel
@{
ViewData["Title"] = "Zugriff nicht gestattet";
}
<header>
<h1 class="text-danger">@ViewData["Title"]</h1>
<p class="text-danger">Für die ausgeführte Aktion haben Sie keinen Zugriff.</p>
</header>

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlazorApp.Areas.Identity.Pages.Account
{
public class AccessDeniedModel : PageModel
{
public void OnGet()
{
}
}
}

View File

@@ -0,0 +1,7 @@
@page
@model ConfirmEmailModel
@{
ViewData["Title"] = "E-Mail bestätigen";
}
<h1>@ViewData["Title"]</h1>

View File

@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ConfirmEmailModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
public ConfirmEmailModel(UserManager<IdentityUser> userManager)
{
_userManager = userManager;
}
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync(string userId, string code)
{
if (userId == null || code == null)
{
return RedirectToPage("/Index");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return NotFound($"Unable to load user with ID '{userId}'.");
}
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await _userManager.ConfirmEmailAsync(user, code);
StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email.";
return Page();
}
}
}

View File

@@ -0,0 +1,8 @@
@page
@model ConfirmEmailChangeModel
@{
ViewData["Title"] = "E-Mail Änderunge bestätigen";
}
<h1>@ViewData["Title"]</h1>
<partial name="_StatusMessage" model="Model.StatusMessage" />

View File

@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ConfirmEmailChangeModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public ConfirmEmailChangeModel(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync(string userId, string email, string code)
{
if (userId == null || email == null || code == null)
{
return RedirectToPage("/Index");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return NotFound($"Unable to load user with ID '{userId}'.");
}
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await _userManager.ChangeEmailAsync(user, email, code);
if (!result.Succeeded)
{
StatusMessage = "Error changing email.";
return Page();
}
// In our UI email and user name are one and the same, so when we update the email
// we need to update the user name.
var setUserNameResult = await _userManager.SetUserNameAsync(user, email);
if (!setUserNameResult.Succeeded)
{
StatusMessage = "Error changing user name.";
return Page();
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Thank you for confirming your email change.";
return Page();
}
}
}

View File

@@ -0,0 +1,33 @@
@page
@model ExternalLoginModel
@{
ViewData["Title"] = "Register";
}
<h1>@ViewData["Title"]</h1>
<h4 id="external-login-title">Associate your @Model.ProviderDisplayName account.</h4>
<hr />
<p id="external-login-description" class="text-info">
You've successfully authenticated with <strong>@Model.ProviderDisplayName</strong>.
Please enter an email address for this site below and click the Register button to finish
logging in.
</p>
<div class="row">
<div class="col-md-4">
<form asp-page-handler="Confirmation" asp-route-returnUrl="@Model.ReturnUrl" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,168 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ExternalLoginModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly IEmailSender _emailSender;
private readonly ILogger<ExternalLoginModel> _logger;
public ExternalLoginModel(
SignInManager<IdentityUser> signInManager,
UserManager<IdentityUser> userManager,
ILogger<ExternalLoginModel> logger,
IEmailSender emailSender)
{
_signInManager = signInManager;
_userManager = userManager;
_logger = logger;
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public string ProviderDisplayName { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
public IActionResult OnGetAsync()
{
return RedirectToPage("./Login");
}
public IActionResult OnPost(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (remoteError != null)
{
ErrorMessage = $"Error from external provider: {remoteError}";
return RedirectToPage("./Login", new {ReturnUrl = returnUrl });
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ErrorMessage = "Error loading external login information.";
return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor : true);
if (result.Succeeded)
{
_logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
return LocalRedirect(returnUrl);
}
if (result.IsLockedOut)
{
return RedirectToPage("./Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ReturnUrl = returnUrl;
ProviderDisplayName = info.ProviderDisplayName;
if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
{
Input = new InputModel
{
Email = info.Principal.FindFirstValue(ClaimTypes.Email)
};
}
return Page();
}
}
public async Task<IActionResult> OnPostConfirmationAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ErrorMessage = "Error loading external login information during confirmation.";
return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
}
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
_logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
var userId = await _userManager.GetUserIdAsync(user);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = userId, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
// If account confirmation is required, we need to show the link if we don't have a real email sender
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("./RegisterConfirmation", new { Email = Input.Email });
}
await _signInManager.SignInAsync(user, isPersistent: false, info.LoginProvider);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
ProviderDisplayName = info.ProviderDisplayName;
ReturnUrl = returnUrl;
return Page();
}
}
}

View File

@@ -0,0 +1,28 @@
@page
@model ForgotPasswordModel
@{
ViewData["Title"] = "Passwort vergessen?";
}
<h1>@ViewData["Title"]</h1>
<div class="card shadow-lg p-3 mb-5 bg-white rounded">
<h4>Bitte geben Sie Ihre Mail-Adresse ein</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.Encodings.Web;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ForgotPasswordModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly IEmailSender _emailSender;
public ForgotPasswordModel(UserManager<IdentityUser> userManager, IEmailSender emailSender)
{
_userManager = userManager;
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
public async Task<IActionResult> OnPostAsync()
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByEmailAsync(Input.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return RedirectToPage("./ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please
// visit https://go.microsoft.com/fwlink/?LinkID=532713
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ResetPassword",
pageHandler: null,
values: new { area = "Identity", code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(
Input.Email,
"Reset Password",
$"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
return RedirectToPage("./ForgotPasswordConfirmation");
}
return Page();
}
}
}

View File

@@ -0,0 +1,11 @@
@page
@model ForgotPasswordConfirmation
@{
ViewData["Title"] = "Passwort zurücksetzen";
}
<h1>@ViewData["Title"]</h1>
<p>
Prüfen Sie bitte Ihr Postfach um Ihr Passwort zurückzusetzen.
</p>

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ForgotPasswordConfirmation : PageModel
{
public void OnGet()
{
}
}
}

View File

@@ -0,0 +1,10 @@
@page
@model LockoutModel
@{
ViewData["Title"] = "Zugriff gesperrt";
}
<header>
<h1 class="text-danger">@ViewData["Title"]</h1>
<p class="text-danger">Ihr Konto ist gesperrt, bitte versuchen Sie es später wieder.</p>
</header>

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LockoutModel : PageModel
{
public void OnGet()
{
}
}
}

View File

@@ -0,0 +1,125 @@
@page
@model LoginModel
@{
ViewData["Title"] = "Anmelden";
}
<h1>@ViewData["Title"]</h1>
<div class="card shadow-lg p-3 mb-5 bg-white rounded">
<h4 class="card-header">Login</h4>
<div class="card-body">
<form id="account" method="post">
<h4>Bitte melden Sie sich mit Ihrer UserID/Passwort an</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" value="hutter@shub.ch" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
@* <input asp-for="Input.Password" class="form-control" value="Admin*123" />
*@ <input asp-for="Input.Password" class="form-control" value="b" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label asp-for="Input.RememberMe">
<input asp-for="Input.RememberMe" />
@Html.DisplayNameFor(m => m.Input.RememberMe)
</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Log in</button>
</div>
<div class="form-group">
<p>
<a id="forgot-password" asp-page="./ForgotPassword">Passwort vergessen?</a>
</p>
<p>
<a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Neu registrieren</a>
</p>
</div>
</form>
</div>
</div>
@*<div class="row">
<div class="col-md-4">
<section>
<form id="account" method="post">
<h4>Use a local account to log in.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label asp-for="Input.RememberMe">
<input asp-for="Input.RememberMe" />
@Html.DisplayNameFor(m => m.Input.RememberMe)
</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Log in</button>
</div>
<div class="form-group">
<p>
<a id="forgot-password" asp-page="./ForgotPassword">Forgot your password?</a>
</p>
<p>
<a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
</p>
</div>
</form>
</section>
</div>
<div class="col-md-6 col-md-offset-2">
<section>
<h4>Use another service to log in.</h4>
<hr />
@{
if ((Model.ExternalLogins?.Count ?? 0) == 0)
{
<div>
<p>
There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
for details on setting up this ASP.NET application to support logging in via external services.
</p>
</div>
}
else
{
<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
<div>
<p>
@foreach (var provider in Model.ExternalLogins)
{
<button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
}
</p>
</div>
</form>
}
}
</section>
</div>
</div>*@
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Blazored.SessionStorage;
using BlazorApp.Helper;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LoginModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<LoginModel> _logger;
private readonly RoleManager<IdentityRole> _roleManager;
private SessionState sessionState;
public LoginModel(SignInManager<IdentityUser> signInManager,
ILogger<LoginModel> logger,
UserManager<IdentityUser> userManager)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
string autologin = "";
Helper.ParameterHelper ph = new Helper.ParameterHelper();
autologin = ph.GetParameter("autologin");
if (autologin == "true")
{
await AutoLogin(returnUrl);
returnUrl = returnUrl ?? Url.Content("~/");
ReturnUrl = returnUrl;
Response.Redirect(returnUrl);
}
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
returnUrl = returnUrl ?? Url.Content("~/");
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> AutoLogin(string returnUrl)
{
if (ModelState.IsValid)
{
string EMail = "info@shub.ch";
string Password = "Admin*123";
Helper.ParameterHelper ph = new Helper.ParameterHelper();
EMail = ph.GetParameter("autologin_user");
Password = ph.GetParameter("autologin_pw");
var result = await _signInManager.PasswordSignInAsync(EMail, Password, false, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
returnUrl = returnUrl ?? Url.Content("~/");
return LocalRedirect(returnUrl);
}
}
return BadRequest();
}
}
}

View File

@@ -0,0 +1,46 @@
@page "/Areas/Identity/Account/Login"
<h3>Login</h3>
<div class="card">
<h4 class="card-header">Login</h4>
<div class="card-body">
<form id="account" method="post">
<h4>Bitte melden Sie sich mit Ihrer UserID/Passwort an</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label asp-for="Input.RememberMe">
<input asp-for="Input.RememberMe" />
@* @Html.DisplayNameFor(m => m.Input.RememberMe)*@
</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Log in</button>
</div>
<div class="form-group">
<p>
<a id="forgot-password" asp-page="./ForgotPassword">Passwort vergessen?</a>
</p>
<p>
@* <a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Neu registrieren</a>*@
</p>
</div>
</form>
</div>
</div>
@code {
}

View File

@@ -0,0 +1,41 @@
@page
@model LoginWith2faModel
@{
ViewData["Title"] = "Two-factor authentication";
}
<h1>@ViewData["Title"]</h1>
<hr />
<p>Your login is protected with an authenticator app. Enter your authenticator code below.</p>
<div class="row">
<div class="col-md-4">
<form method="post" asp-route-returnUrl="@Model.ReturnUrl">
<input asp-for="RememberMe" type="hidden" />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.TwoFactorCode"></label>
<input asp-for="Input.TwoFactorCode" class="form-control" autocomplete="off" />
<span asp-validation-for="Input.TwoFactorCode" class="text-danger"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label asp-for="Input.RememberMachine">
<input asp-for="Input.RememberMachine" />
@Html.DisplayNameFor(m => m.Input.RememberMachine)
</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Log in</button>
</div>
</form>
</div>
</div>
<p>
Don't have access to your authenticator device? You can
<a id="recovery-code-login" asp-page="./LoginWithRecoveryCode" asp-route-returnUrl="@Model.ReturnUrl">log in with a recovery code</a>.
</p>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LoginWith2faModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<LoginWith2faModel> _logger;
public LoginWith2faModel(SignInManager<IdentityUser> signInManager, ILogger<LoginWith2faModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public bool RememberMe { get; set; }
public string ReturnUrl { get; set; }
public class InputModel
{
[Required]
[StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Text)]
[Display(Name = "Authenticator code")]
public string TwoFactorCode { get; set; }
[Display(Name = "Remember this machine")]
public bool RememberMachine { get; set; }
}
public async Task<IActionResult> OnGetAsync(bool rememberMe, string returnUrl = null)
{
// Ensure the user has gone through the username & password screen first
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new InvalidOperationException($"Unable to load two-factor authentication user.");
}
ReturnUrl = returnUrl;
RememberMe = rememberMe;
return Page();
}
public async Task<IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null)
{
if (!ModelState.IsValid)
{
return Page();
}
returnUrl = returnUrl ?? Url.Content("~/");
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new InvalidOperationException($"Unable to load two-factor authentication user.");
}
var authenticatorCode = Input.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);
var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, Input.RememberMachine);
if (result.Succeeded)
{
_logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", user.Id);
return LocalRedirect(returnUrl);
}
else if (result.IsLockedOut)
{
_logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id);
return RedirectToPage("./Lockout");
}
else
{
_logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", user.Id);
ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
return Page();
}
}
}
}

View File

@@ -0,0 +1,29 @@
@page
@model LoginWithRecoveryCodeModel
@{
ViewData["Title"] = "Recovery code verification";
}
<h1>@ViewData["Title"]</h1>
<hr />
<p>
You have requested to log in with a recovery code. This login will not be remembered until you provide
an authenticator app code at log in or disable 2FA and log in again.
</p>
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.RecoveryCode"></label>
<input asp-for="Input.RecoveryCode" class="form-control" autocomplete="off" />
<span asp-validation-for="Input.RecoveryCode" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Log in</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LoginWithRecoveryCodeModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<LoginWithRecoveryCodeModel> _logger;
public LoginWithRecoveryCodeModel(SignInManager<IdentityUser> signInManager, ILogger<LoginWithRecoveryCodeModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public class InputModel
{
[BindProperty]
[Required]
[DataType(DataType.Text)]
[Display(Name = "Recovery Code")]
public string RecoveryCode { get; set; }
}
public async Task<IActionResult> OnGetAsync(string returnUrl = null)
{
// Ensure the user has gone through the username & password screen first
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new InvalidOperationException($"Unable to load two-factor authentication user.");
}
ReturnUrl = returnUrl;
return Page();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new InvalidOperationException($"Unable to load two-factor authentication user.");
}
var recoveryCode = Input.RecoveryCode.Replace(" ", string.Empty);
var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);
if (result.Succeeded)
{
_logger.LogInformation("User with ID '{UserId}' logged in with a recovery code.", user.Id);
return LocalRedirect(returnUrl ?? Url.Content("~/"));
}
if (result.IsLockedOut)
{
_logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id);
return RedirectToPage("./Lockout");
}
else
{
_logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", user.Id);
ModelState.AddModelError(string.Empty, "Invalid recovery code entered.");
return Page();
}
}
}
}

View File

@@ -0,0 +1,15 @@
@page
@model LogoutModel
@{
ViewData["Title"] = "Abmelden";
}
<header>
<div class="card shadow-lg p-3 mb-5 bg-white rounded">
<div class="card-header bg-primary"><h4>@ViewData["Title"]</h4></div>
<div class="card-body">Sie haben sich erfolgreich abgemeldet</div>
<div class="card-footer">
<button class="btn btn-primary" onclick="window.location.href='/'">Startseite </button>
</div>
</div>
</header>

View File

@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LogoutModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<LogoutModel> _logger;
public LogoutModel(SignInManager<IdentityUser> signInManager, ILogger<LogoutModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
public void OnGet()
{
_signInManager.SignOutAsync();
}
public async Task<IActionResult> OnPost(string returnUrl = null)
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
if (returnUrl != null)
{
return LocalRedirect(returnUrl);
}
else
{
return RedirectToPage();
}
}
}
}

View File

@@ -0,0 +1,36 @@
@page
@model ChangePasswordModel
@{
ViewData["Title"] = "Change password";
ViewData["ActivePage"] = ManageNavPages.ChangePassword;
}
<h4>@ViewData["Title"]</h4>
<partial name="_StatusMessage" for="StatusMessage" />
<div class="row">
<div class="col-md-6">
<form id="change-password-form" method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.OldPassword"></label>
<input asp-for="Input.OldPassword" class="form-control" />
<span asp-validation-for="Input.OldPassword" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.NewPassword"></label>
<input asp-for="Input.NewPassword" class="form-control" />
<span asp-validation-for="Input.NewPassword" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" class="form-control" />
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Update password</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class ChangePasswordModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<ChangePasswordModel> _logger;
public ChangePasswordModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<ChangePasswordModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
[TempData]
public string StatusMessage { get; set; }
public class InputModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var hasPassword = await _userManager.HasPasswordAsync(user);
if (!hasPassword)
{
return RedirectToPage("./SetPassword");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);
if (!changePasswordResult.Succeeded)
{
foreach (var error in changePasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
await _signInManager.RefreshSignInAsync(user);
_logger.LogInformation("User changed their password successfully.");
StatusMessage = "Your password has been changed.";
return RedirectToPage();
}
}
}

View File

@@ -0,0 +1,33 @@
@page
@model DeletePersonalDataModel
@{
ViewData["Title"] = "Delete Personal Data";
ViewData["ActivePage"] = ManageNavPages.PersonalData;
}
<h4>@ViewData["Title"]</h4>
<div class="alert alert-warning" role="alert">
<p>
<strong>Deleting this data will permanently remove your account, and this cannot be recovered.</strong>
</p>
</div>
<div>
<form id="delete-user" method="post" class="form-group">
<div asp-validation-summary="All" class="text-danger"></div>
@if (Model.RequirePassword)
{
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
}
<button class="btn btn-danger" type="submit">Delete data and close my account</button>
</form>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,83 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class DeletePersonalDataModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<DeletePersonalDataModel> _logger;
public DeletePersonalDataModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<DeletePersonalDataModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
public bool RequirePassword { get; set; }
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
if (RequirePassword)
{
if (!await _userManager.CheckPasswordAsync(user, Input.Password))
{
ModelState.AddModelError(string.Empty, "Incorrect password.");
return Page();
}
}
var result = await _userManager.DeleteAsync(user);
var userId = await _userManager.GetUserIdAsync(user);
if (!result.Succeeded)
{
throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'.");
}
await _signInManager.SignOutAsync();
_logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);
return Redirect("~/");
}
}
}

View File

@@ -0,0 +1,25 @@
@page
@model Disable2faModel
@{
ViewData["Title"] = "Disable two-factor authentication (2FA)";
ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication;
}
<partial name="_StatusMessage" for="StatusMessage" />
<h2>@ViewData["Title"]</h2>
<div class="alert alert-warning" role="alert">
<p>
<strong>This action only disables 2FA.</strong>
</p>
<p>
Disabling 2FA does not change the keys used in authenticator apps. If you wish to change the key
used in an authenticator app you should <a asp-page="./ResetAuthenticator">reset your authenticator keys.</a>
</p>
</div>
<div>
<form method="post" class="form-group">
<button class="btn btn-danger" type="submit">Disable 2FA</button>
</form>
</div>

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class Disable2faModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<Disable2faModel> _logger;
public Disable2faModel(
UserManager<IdentityUser> userManager,
ILogger<Disable2faModel> logger)
{
_userManager = userManager;
_logger = logger;
}
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!await _userManager.GetTwoFactorEnabledAsync(user))
{
throw new InvalidOperationException($"Cannot disable 2FA for user with ID '{_userManager.GetUserId(User)}' as it's not currently enabled.");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false);
if (!disable2faResult.Succeeded)
{
throw new InvalidOperationException($"Unexpected error occurred disabling 2FA for user with ID '{_userManager.GetUserId(User)}'.");
}
_logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", _userManager.GetUserId(User));
StatusMessage = "2fa has been disabled. You can reenable 2fa when you setup an authenticator app";
return RedirectToPage("./TwoFactorAuthentication");
}
}
}

View File

@@ -0,0 +1,12 @@
@page
@model DownloadPersonalDataModel
@{
ViewData["Title"] = "Download Your Data";
ViewData["ActivePage"] = ManageNavPages.PersonalData;
}
<h4>@ViewData["Title"]</h4>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class DownloadPersonalDataModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<DownloadPersonalDataModel> _logger;
public DownloadPersonalDataModel(
UserManager<IdentityUser> userManager,
ILogger<DownloadPersonalDataModel> logger)
{
_userManager = userManager;
_logger = logger;
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
_logger.LogInformation("User with ID '{UserId}' asked for their personal data.", _userManager.GetUserId(User));
// Only include personal data for download
var personalData = new Dictionary<string, string>();
var personalDataProps = typeof(IdentityUser).GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));
foreach (var p in personalDataProps)
{
personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null");
}
var logins = await _userManager.GetLoginsAsync(user);
foreach (var l in logins)
{
personalData.Add($"{l.LoginProvider} external login provider key", l.ProviderKey);
}
Response.Headers.Add("Content-Disposition", "attachment; filename=PersonalData.json");
return new FileContentResult(JsonSerializer.SerializeToUtf8Bytes(personalData), "application/json");
}
}
}

View File

@@ -0,0 +1,43 @@
@page
@model EmailModel
@{
ViewData["Title"] = "Manage Email";
ViewData["ActivePage"] = ManageNavPages.Email;
}
<h4>@ViewData["Title"]</h4>
<partial name="_StatusMessage" model="Model.StatusMessage" />
<div class="row">
<div class="col-md-6">
<form id="email-form" method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Email"></label>
@if (Model.IsEmailConfirmed)
{
<div class="input-group">
<input asp-for="Email" class="form-control" disabled />
<div class="input-group-append">
<span class="input-group-text text-success font-weight-bold">✓</span>
</div>
</div>
}
else
{
<input asp-for="Email" class="form-control" disabled />
<button id="email-verification" type="submit" asp-page-handler="SendVerificationEmail" class="btn btn-link">Send verification email</button>
}
</div>
<div class="form-group">
<label asp-for="Input.NewEmail"></label>
<input asp-for="Input.NewEmail" class="form-control" />
<span asp-validation-for="Input.NewEmail" class="text-danger"></span>
</div>
<button id="change-email-button" type="submit" asp-page-handler="ChangeEmail" class="btn btn-primary">Change email</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Text.Encodings.Web;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public partial class EmailModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly IEmailSender _emailSender;
public EmailModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
}
public string Username { get; set; }
public string Email { get; set; }
public bool IsEmailConfirmed { get; set; }
[TempData]
public string StatusMessage { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "New email")]
public string NewEmail { get; set; }
}
private async Task LoadAsync(IdentityUser user)
{
var email = await _userManager.GetEmailAsync(user);
Email = email;
Input = new InputModel
{
NewEmail = email,
};
IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await LoadAsync(user);
return Page();
}
public async Task<IActionResult> OnPostChangeEmailAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var email = await _userManager.GetEmailAsync(user);
if (Input.NewEmail != email)
{
var userId = await _userManager.GetUserIdAsync(user);
var code = await _userManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail);
var callbackUrl = Url.Page(
"/Account/ConfirmEmailChange",
pageHandler: null,
values: new { userId = userId, email = Input.NewEmail, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(
Input.NewEmail,
"Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
StatusMessage = "Confirmation link to change email sent. Please check your email.";
return RedirectToPage();
}
StatusMessage = "Your email is unchanged.";
return RedirectToPage();
}
public async Task<IActionResult> OnPostSendVerificationEmailAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var userId = await _userManager.GetUserIdAsync(user);
var email = await _userManager.GetEmailAsync(user);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = userId, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(
email,
"Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
StatusMessage = "Verification email sent. Please check your email.";
return RedirectToPage();
}
}
}

View File

@@ -0,0 +1,53 @@
@page
@model EnableAuthenticatorModel
@{
ViewData["Title"] = "Configure authenticator app";
ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication;
}
<partial name="_StatusMessage" for="StatusMessage" />
<h4>@ViewData["Title"]</h4>
<div>
<p>To use an authenticator app go through the following steps:</p>
<ol class="list">
<li>
<p>
Download a two-factor authenticator app like Microsoft Authenticator for
<a href="https://go.microsoft.com/fwlink/?Linkid=825072">Android</a> and
<a href="https://go.microsoft.com/fwlink/?Linkid=825073">iOS</a> or
Google Authenticator for
<a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&amp;hl=en">Android</a> and
<a href="https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8">iOS</a>.
</p>
</li>
<li>
<p>Scan the QR Code or enter this key <kbd>@Model.SharedKey</kbd> into your two factor authenticator app. Spaces and casing do not matter.</p>
<div class="alert alert-info">Learn how to <a href="https://go.microsoft.com/fwlink/?Linkid=852423">enable QR code generation</a>.</div>
<div id="qrCode"></div>
<div id="qrCodeData" data-url="@Html.Raw(@Model.AuthenticatorUri)"></div>
</li>
<li>
<p>
Once you have scanned the QR code or input the key above, your two factor authentication app will provide you
with a unique code. Enter the code in the confirmation box below.
</p>
<div class="row">
<div class="col-md-6">
<form id="send-code" method="post">
<div class="form-group">
<label asp-for="Input.Code" class="control-label">Verification Code</label>
<input asp-for="Input.Code" class="form-control" autocomplete="off" />
<span asp-validation-for="Input.Code" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Verify</button>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
</form>
</div>
</div>
</li>
</ol>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,156 @@
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Text;
using System.Text.Encodings.Web;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class EnableAuthenticatorModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<EnableAuthenticatorModel> _logger;
private readonly UrlEncoder _urlEncoder;
private const string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6";
public EnableAuthenticatorModel(
UserManager<IdentityUser> userManager,
ILogger<EnableAuthenticatorModel> logger,
UrlEncoder urlEncoder)
{
_userManager = userManager;
_logger = logger;
_urlEncoder = urlEncoder;
}
public string SharedKey { get; set; }
public string AuthenticatorUri { get; set; }
[TempData]
public string[] RecoveryCodes { get; set; }
[TempData]
public string StatusMessage { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Text)]
[Display(Name = "Verification Code")]
public string Code { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await LoadSharedKeyAndQrCodeUriAsync(user);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadSharedKeyAndQrCodeUriAsync(user);
return Page();
}
// Strip spaces and hypens
var verificationCode = Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);
if (!is2faTokenValid)
{
ModelState.AddModelError("Input.Code", "Verification code is invalid.");
await LoadSharedKeyAndQrCodeUriAsync(user);
return Page();
}
await _userManager.SetTwoFactorEnabledAsync(user, true);
var userId = await _userManager.GetUserIdAsync(user);
_logger.LogInformation("User with ID '{UserId}' has enabled 2FA with an authenticator app.", userId);
StatusMessage = "Your authenticator app has been verified.";
if (await _userManager.CountRecoveryCodesAsync(user) == 0)
{
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
RecoveryCodes = recoveryCodes.ToArray();
return RedirectToPage("./ShowRecoveryCodes");
}
else
{
return RedirectToPage("./TwoFactorAuthentication");
}
}
private async Task LoadSharedKeyAndQrCodeUriAsync(IdentityUser user)
{
// Load the authenticator key & QR code URI to display on the form
var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
if (string.IsNullOrEmpty(unformattedKey))
{
await _userManager.ResetAuthenticatorKeyAsync(user);
unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
}
SharedKey = FormatKey(unformattedKey);
var email = await _userManager.GetEmailAsync(user);
AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
}
private string FormatKey(string unformattedKey)
{
var result = new StringBuilder();
int currentPosition = 0;
while (currentPosition + 4 < unformattedKey.Length)
{
result.Append(unformattedKey.Substring(currentPosition, 4)).Append(" ");
currentPosition += 4;
}
if (currentPosition < unformattedKey.Length)
{
result.Append(unformattedKey.Substring(currentPosition));
}
return result.ToString().ToLowerInvariant();
}
private string GenerateQrCodeUri(string email, string unformattedKey)
{
return string.Format(
AuthenticatorUriFormat,
_urlEncoder.Encode("BlazorApp"),
_urlEncoder.Encode(email),
unformattedKey);
}
}
}

View File

@@ -0,0 +1,53 @@
@page
@model ExternalLoginsModel
@{
ViewData["Title"] = "Manage your external logins";
ViewData["ActivePage"] = ManageNavPages.ExternalLogins;
}
<partial name="_StatusMessage" for="StatusMessage" />
@if (Model.CurrentLogins?.Count > 0)
{
<h4>Registered Logins</h4>
<table class="table">
<tbody>
@foreach (var login in Model.CurrentLogins)
{
<tr>
<td id="@($"login-provider-{login.LoginProvider}")">@login.ProviderDisplayName</td>
<td>
@if (Model.ShowRemoveButton)
{
<form id="@($"remove-login-{login.LoginProvider}")" asp-page-handler="RemoveLogin" method="post">
<div>
<input asp-for="@login.LoginProvider" name="LoginProvider" type="hidden" />
<input asp-for="@login.ProviderKey" name="ProviderKey" type="hidden" />
<button type="submit" class="btn btn-primary" title="Remove this @login.ProviderDisplayName login from your account">Remove</button>
</div>
</form>
}
else
{
@: &nbsp;
}
</td>
</tr>
}
</tbody>
</table>
}
@if (Model.OtherLogins?.Count > 0)
{
<h4>Add another service to log in.</h4>
<hr />
<form id="link-login-form" asp-page-handler="LinkLogin" method="post" class="form-horizontal">
<div id="socialLoginList">
<p>
@foreach (var provider in Model.OtherLogins)
{
<button id="@($"link-login-button-{provider.Name}")" type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
}
</p>
</div>
</form>
}

View File

@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class ExternalLoginsModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public ExternalLoginsModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationScheme> OtherLogins { get; set; }
public bool ShowRemoveButton { get; set; }
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID 'user.Id'.");
}
CurrentLogins = await _userManager.GetLoginsAsync(user);
OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
.Where(auth => CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
.ToList();
ShowRemoveButton = user.PasswordHash != null || CurrentLogins.Count > 1;
return Page();
}
public async Task<IActionResult> OnPostRemoveLoginAsync(string loginProvider, string providerKey)
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID 'user.Id'.");
}
var result = await _userManager.RemoveLoginAsync(user, loginProvider, providerKey);
if (!result.Succeeded)
{
StatusMessage = "The external login was not removed.";
return RedirectToPage();
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "The external login was removed.";
return RedirectToPage();
}
public async Task<IActionResult> OnPostLinkLoginAsync(string provider)
{
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Page("./ExternalLogins", pageHandler: "LinkLoginCallback");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return new ChallengeResult(provider, properties);
}
public async Task<IActionResult> OnGetLinkLoginCallbackAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID 'user.Id'.");
}
var info = await _signInManager.GetExternalLoginInfoAsync(user.Id);
if (info == null)
{
throw new InvalidOperationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'.");
}
var result = await _userManager.AddLoginAsync(user, info);
if (!result.Succeeded)
{
StatusMessage = "The external login was not added. External logins can only be associated with one account.";
return RedirectToPage();
}
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
StatusMessage = "The external login was added.";
return RedirectToPage();
}
}
}

View File

@@ -0,0 +1,27 @@
@page
@model GenerateRecoveryCodesModel
@{
ViewData["Title"] = "Generate two-factor authentication (2FA) recovery codes";
ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication;
}
<partial name="_StatusMessage" for="StatusMessage" />
<h4>@ViewData["Title"]</h4>
<div class="alert alert-warning" role="alert">
<p>
<span class="glyphicon glyphicon-warning-sign"></span>
<strong>Put these codes in a safe place.</strong>
</p>
<p>
If you lose your device and don't have the recovery codes you will lose access to your account.
</p>
<p>
Generating new recovery codes does not change the keys used in authenticator apps. If you wish to change the key
used in an authenticator app you should <a asp-page="./ResetAuthenticator">reset your authenticator keys.</a>
</p>
</div>
<div>
<form method="post" class="form-group">
<button class="btn btn-danger" type="submit">Generate Recovery Codes</button>
</form>
</div>

View File

@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class GenerateRecoveryCodesModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<GenerateRecoveryCodesModel> _logger;
public GenerateRecoveryCodesModel(
UserManager<IdentityUser> userManager,
ILogger<GenerateRecoveryCodesModel> logger)
{
_userManager = userManager;
_logger = logger;
}
[TempData]
public string[] RecoveryCodes { get; set; }
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
if (!isTwoFactorEnabled)
{
var userId = await _userManager.GetUserIdAsync(user);
throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' because they do not have 2FA enabled.");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
var userId = await _userManager.GetUserIdAsync(user);
if (!isTwoFactorEnabled)
{
throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' as they do not have 2FA enabled.");
}
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
RecoveryCodes = recoveryCodes.ToArray();
_logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", userId);
StatusMessage = "You have generated new recovery codes.";
return RedirectToPage("./ShowRecoveryCodes");
}
}
}

View File

@@ -0,0 +1,30 @@
@page
@model IndexModel
@{
ViewData["Title"] = "Profile";
ViewData["ActivePage"] = ManageNavPages.Index;
}
<h4>@ViewData["Title"]</h4>
<partial name="_StatusMessage" model="Model.StatusMessage" />
<div class="row">
<div class="col-md-6">
<form id="profile-form" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" disabled />
</div>
<div class="form-group">
<label asp-for="Input.PhoneNumber"></label>
<input asp-for="Input.PhoneNumber" class="form-control" />
<span asp-validation-for="Input.PhoneNumber" class="text-danger"></span>
</div>
<button id="update-profile-button" type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public partial class IndexModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public IndexModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public string Username { get; set; }
[TempData]
public string StatusMessage { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Phone]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
}
private async Task LoadAsync(IdentityUser user)
{
var userName = await _userManager.GetUserNameAsync(user);
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
Username = userName;
Input = new InputModel
{
PhoneNumber = phoneNumber
};
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await LoadAsync(user);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
if (Input.PhoneNumber != phoneNumber)
{
var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
if (!setPhoneResult.Succeeded)
{
StatusMessage = "Unexpected error when trying to set phone number.";
return RedirectToPage();
}
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your profile has been updated";
return RedirectToPage();
}
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public static class ManageNavPages
{
public static string Index => "Index";
public static string Email => "Email";
public static string ChangePassword => "ChangePassword";
public static string DownloadPersonalData => "DownloadPersonalData";
public static string DeletePersonalData => "DeletePersonalData";
public static string ExternalLogins => "ExternalLogins";
public static string PersonalData => "PersonalData";
public static string TwoFactorAuthentication => "TwoFactorAuthentication";
public static string IndexNavClass(ViewContext viewContext) => PageNavClass(viewContext, Index);
public static string EmailNavClass(ViewContext viewContext) => PageNavClass(viewContext, Email);
public static string ChangePasswordNavClass(ViewContext viewContext) => PageNavClass(viewContext, ChangePassword);
public static string DownloadPersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, DownloadPersonalData);
public static string DeletePersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, DeletePersonalData);
public static string ExternalLoginsNavClass(ViewContext viewContext) => PageNavClass(viewContext, ExternalLogins);
public static string PersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, PersonalData);
public static string TwoFactorAuthenticationNavClass(ViewContext viewContext) => PageNavClass(viewContext, TwoFactorAuthentication);
private static string PageNavClass(ViewContext viewContext, string page)
{
var activePage = viewContext.ViewData["ActivePage"] as string
?? System.IO.Path.GetFileNameWithoutExtension(viewContext.ActionDescriptor.DisplayName);
return string.Equals(activePage, page, StringComparison.OrdinalIgnoreCase) ? "active" : null;
}
}
}

View File

@@ -0,0 +1,27 @@
@page
@model PersonalDataModel
@{
ViewData["Title"] = "Personal Data";
ViewData["ActivePage"] = ManageNavPages.PersonalData;
}
<h4>@ViewData["Title"]</h4>
<div class="row">
<div class="col-md-6">
<p>Your account contains personal data that you have given us. This page allows you to download or delete that data.</p>
<p>
<strong>Deleting this data will permanently remove your account, and this cannot be recovered.</strong>
</p>
<form id="download-data" asp-page="DownloadPersonalData" method="post" class="form-group">
<button class="btn btn-primary" type="submit">Download</button>
</form>
<p>
<a id="delete" asp-page="DeletePersonalData" class="btn btn-primary">Delete</a>
</p>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,33 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class PersonalDataModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<PersonalDataModel> _logger;
public PersonalDataModel(
UserManager<IdentityUser> userManager,
ILogger<PersonalDataModel> logger)
{
_userManager = userManager;
_logger = logger;
}
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
return Page();
}
}
}

View File

@@ -0,0 +1,24 @@
@page
@model ResetAuthenticatorModel
@{
ViewData["Title"] = "Reset authenticator key";
ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication;
}
<partial name="_StatusMessage" for="StatusMessage" />
<h4>@ViewData["Title"]</h4>
<div class="alert alert-warning" role="alert">
<p>
<span class="glyphicon glyphicon-warning-sign"></span>
<strong>If you reset your authenticator key your authenticator app will not work until you reconfigure it.</strong>
</p>
<p>
This process disables 2FA until you verify your authenticator app.
If you do not complete your authenticator app configuration you may lose access to your account.
</p>
</div>
<div>
<form id="reset-authenticator-form" method="post" class="form-group">
<button id="reset-authenticator-button" class="btn btn-danger" type="submit">Reset authenticator key</button>
</form>
</div>

View File

@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class ResetAuthenticatorModel : PageModel
{
UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
ILogger<ResetAuthenticatorModel> _logger;
public ResetAuthenticatorModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<ResetAuthenticatorModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _userManager.ResetAuthenticatorKeyAsync(user);
_logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", user.Id);
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your authenticator app key has been reset, you will need to configure your authenticator app using the new key.";
return RedirectToPage("./EnableAuthenticator");
}
}
}

View File

@@ -0,0 +1,35 @@
@page
@model SetPasswordModel
@{
ViewData["Title"] = "Set password";
ViewData["ActivePage"] = ManageNavPages.ChangePassword;
}
<h4>Set your password</h4>
<partial name="_StatusMessage" for="StatusMessage" />
<p class="text-info">
You do not have a local username/password for this site. Add a local
account so you can log in without an external login.
</p>
<div class="row">
<div class="col-md-6">
<form id="set-password-form" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.NewPassword"></label>
<input asp-for="Input.NewPassword" class="form-control" />
<span asp-validation-for="Input.NewPassword" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" class="form-control" />
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Set password</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class SetPasswordModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public SetPasswordModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[BindProperty]
public InputModel Input { get; set; }
[TempData]
public string StatusMessage { get; set; }
public class InputModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var hasPassword = await _userManager.HasPasswordAsync(user);
if (hasPassword)
{
return RedirectToPage("./ChangePassword");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var addPasswordResult = await _userManager.AddPasswordAsync(user, Input.NewPassword);
if (!addPasswordResult.Succeeded)
{
foreach (var error in addPasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your password has been set.";
return RedirectToPage();
}
}
}

View File

@@ -0,0 +1,25 @@
@page
@model ShowRecoveryCodesModel
@{
ViewData["Title"] = "Recovery codes";
ViewData["ActivePage"] = "TwoFactorAuthentication";
}
<partial name="_StatusMessage" for="StatusMessage" />
<h4>@ViewData["Title"]</h4>
<div class="alert alert-warning" role="alert">
<p>
<strong>Put these codes in a safe place.</strong>
</p>
<p>
If you lose your device and don't have the recovery codes you will lose access to your account.
</p>
</div>
<div class="row">
<div class="col-md-12">
@for (var row = 0; row < Model.RecoveryCodes.Length; row += 2)
{
<code class="recovery-code">@Model.RecoveryCodes[row]</code><text>&nbsp;</text><code class="recovery-code">@Model.RecoveryCodes[row + 1]</code><br />
}
</div>
</div>

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class ShowRecoveryCodesModel : PageModel
{
[TempData]
public string[] RecoveryCodes { get; set; }
[TempData]
public string StatusMessage { get; set; }
public IActionResult OnGet()
{
if (RecoveryCodes == null || RecoveryCodes.Length == 0)
{
return RedirectToPage("./TwoFactorAuthentication");
}
return Page();
}
}
}

View File

@@ -0,0 +1,57 @@
@page
@model TwoFactorAuthenticationModel
@{
ViewData["Title"] = "Two-factor authentication (2FA)";
ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication;
}
<partial name="_StatusMessage" for="StatusMessage" />
<h4>@ViewData["Title"]</h4>
@if (Model.Is2faEnabled)
{
if (Model.RecoveryCodesLeft == 0)
{
<div class="alert alert-danger">
<strong>You have no recovery codes left.</strong>
<p>You must <a asp-page="./GenerateRecoveryCodes">generate a new set of recovery codes</a> before you can log in with a recovery code.</p>
</div>
}
else if (Model.RecoveryCodesLeft == 1)
{
<div class="alert alert-danger">
<strong>You have 1 recovery code left.</strong>
<p>You can <a asp-page="./GenerateRecoveryCodes">generate a new set of recovery codes</a>.</p>
</div>
}
else if (Model.RecoveryCodesLeft <= 3)
{
<div class="alert alert-warning">
<strong>You have @Model.RecoveryCodesLeft recovery codes left.</strong>
<p>You should <a asp-page="./GenerateRecoveryCodes">generate a new set of recovery codes</a>.</p>
</div>
}
if (Model.IsMachineRemembered)
{
<form method="post" style="display: inline-block">
<button type="submit" class="btn btn-default">Forget this browser</button>
</form>
}
<a asp-page="./Disable2fa" class="btn btn-default">Disable 2FA</a>
<a asp-page="./GenerateRecoveryCodes" class="btn btn-default">Reset recovery codes</a>
}
<h5>Authenticator app</h5>
@if (!Model.HasAuthenticator)
{
<a id="enable-authenticator" asp-page="./EnableAuthenticator" class="btn btn-default">Add authenticator app</a>
}
else
{
<a id="enable-authenticator" asp-page="./EnableAuthenticator" class="btn btn-default">Setup authenticator app</a>
<a id="reset-authenticator" asp-page="./ResetAuthenticator" class="btn btn-default">Reset authenticator app</a>
}
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account.Manage
{
public class TwoFactorAuthenticationModel : PageModel
{
private const string AuthenicatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}";
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<TwoFactorAuthenticationModel> _logger;
public TwoFactorAuthenticationModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<TwoFactorAuthenticationModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
public bool HasAuthenticator { get; set; }
public int RecoveryCodesLeft { get; set; }
[BindProperty]
public bool Is2faEnabled { get; set; }
public bool IsMachineRemembered { get; set; }
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
HasAuthenticator = await _userManager.GetAuthenticatorKeyAsync(user) != null;
Is2faEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
IsMachineRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user);
RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user);
return Page();
}
public async Task<IActionResult> OnPost()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await _signInManager.ForgetTwoFactorClientAsync();
StatusMessage = "The current browser has been forgotten. When you login again from this browser you will be prompted for your 2fa code.";
return RedirectToPage();
}
}
}

View File

@@ -0,0 +1,29 @@
@{
if (ViewData.TryGetValue("ParentLayout", out var parentLayout))
{
Layout = (string)parentLayout;
}
else
{
Layout = "/Areas/Identity/Pages/_Layout.cshtml";
}
}
<h2>Manage your account</h2>
<div>
<h4>Change your account settings</h4>
<hr />
<div class="row">
<div class="col-md-3">
<partial name="_ManageNav" />
</div>
<div class="col-md-9">
@RenderBody()
</div>
</div>
</div>
@section Scripts {
@RenderSection("Scripts", required: false)
}

View File

@@ -0,0 +1,15 @@
@inject SignInManager<IdentityUser> SignInManager
@{
var hasExternalLogins = (await SignInManager.GetExternalAuthenticationSchemesAsync()).Any();
}
<ul class="nav nav-pills flex-column">
<li class="nav-item"><a class="nav-link @ManageNavPages.IndexNavClass(ViewContext)" id="profile" asp-page="./Index">Profile</a></li>
<li class="nav-item"><a class="nav-link @ManageNavPages.EmailNavClass(ViewContext)" id="email" asp-page="./Email">Email</a></li>
<li class="nav-item"><a class="nav-link @ManageNavPages.ChangePasswordNavClass(ViewContext)" id="change-password" asp-page="./ChangePassword">Password</a></li>
@if (hasExternalLogins)
{
<li id="external-logins" class="nav-item"><a id="external-login" class="nav-link @ManageNavPages.ExternalLoginsNavClass(ViewContext)" asp-page="./ExternalLogins">External logins</a></li>
}
<li class="nav-item"><a class="nav-link @ManageNavPages.TwoFactorAuthenticationNavClass(ViewContext)" id="two-factor" asp-page="./TwoFactorAuthentication">Two-factor authentication</a></li>
<li class="nav-item"><a class="nav-link @ManageNavPages.PersonalDataNavClass(ViewContext)" id="personal-data" asp-page="./PersonalData">Personal data</a></li>
</ul>

View File

@@ -0,0 +1,10 @@
@model string
@if (!String.IsNullOrEmpty(Model))
{
var statusMessageClass = Model.StartsWith("Error") ? "danger" : "success";
<div class="alert alert-@statusMessageClass alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
@Model
</div>
}

View File

@@ -0,0 +1 @@
@using BlazorApp.Areas.Identity.Pages.Account.Manage

View File

@@ -0,0 +1,67 @@
@page
@model RegisterModel
@{
ViewData["Title"] = "Register";
}
<h1>@ViewData["Title"]</h1>
<div class="row">
<div class="col-md-4">
<form asp-route-returnUrl="@Model.ReturnUrl" method="post">
<h4>Create a new account.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" class="form-control" />
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
<div class="col-md-6 col-md-offset-2">
<section>
<h4>Use another service to register.</h4>
<hr />
@{
if ((Model.ExternalLogins?.Count ?? 0) == 0)
{
<div>
<p>
There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
for details on setting up this ASP.NET application to support logging in via external services.
</p>
</div>
}
else
{
<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
<div>
<p>
@foreach (var provider in Model.ExternalLogins)
{
<button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
}
</p>
</div>
</form>
}
}
</section>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class RegisterModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
public RegisterModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
}

View File

@@ -0,0 +1,71 @@
@page
@model RegisterComapnyModel
@{
ViewData["Title"] = "Registrierung als Firma";
}
<h1>@ViewData["Title"]</h1>
<div class="card shadow-lg p-3 mb-5 bg-white rounded">
<div class="row">
<div class="col-md-4">
<form asp-route-returnUrl="@Model.ReturnUrl" method="post">
<h4>Neues Konto erstellen</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" class="form-control" />
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
<div class="col-md-6 col-md-offset-2">
<section>
<h4>Ablauf</h4>
<hr />
@{
if ((Model.ExternalLogins?.Count ?? 0) == 0)
{
<div>
<p>
Nach der Registrierung erhalten Sie ein E-Mail um Ihr Konto zu bestätigen.
</p>
<p>
Nach der Bestätigung können Sie Ihre Daten verwalten.
</p>
</div>
}
else
{
<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
<div>
<p>
@foreach (var provider in Model.ExternalLogins)
{
<button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
}
</p>
</div>
</form>
}
}
</section>
</div>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class RegisterComapnyModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
public RegisterComapnyModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
await _userManager.AddToRoleAsync(user, "Firma");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
BlazorApp.Helper.ParameterHelper ph = new BlazorApp.Helper.ParameterHelper();
string smtpserver = ph.GetParameter("smtpserver");
string smtpuser = ph.GetParameter("smtpuser");
string smtppw = ph.GetParameter("smtppw");
string smtpport = ph.GetParameter("smtpport");
BlazorApp.Helper.EmailSender esend = new BlazorApp.Helper.EmailSender(smtpserver, Convert.ToInt32(smtpport), true, smtpuser, smtppw);
await esend.SendEmailAsync(Input.Email,"BWPM: Registrierungsbestätigung",
$"Sie haben sich beim Berufswahlparcours registriert. Bitte bestätigen Sie Ihre Registrierung über den folgenden Link_ <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>Registrierung Bestägigen</a>.");
//await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
// $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
}

View File

@@ -0,0 +1,22 @@
@page
@model RegisterConfirmationModel
@{
ViewData["Title"] = "Bestätitugn Ihrer Registrierung";
}
<h1>@ViewData["Title"]</h1>
@{
if (@Model.DisplayConfirmAccountLink)
{
<p>
This app does not currently have a real email sender registered, see <a href="https://aka.ms/aspaccountconf">these docs</a> for how to configure a real email sender.
Normally this would be emailed: <a id="confirm-link" href="@Model.EmailConfirmationUrl">Click here to confirm your account</a>
</p>
}
else
{
<p>
Bitte überprüfen Sie ihr Postfach, um Ihr neues Konto zu bestätigen.
</p>
}
}

View File

@@ -0,0 +1,61 @@
using Microsoft.AspNetCore.Authorization;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class RegisterConfirmationModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly IEmailSender _sender;
public RegisterConfirmationModel(UserManager<IdentityUser> userManager, IEmailSender sender)
{
_userManager = userManager;
_sender = sender;
}
public string Email { get; set; }
public bool DisplayConfirmAccountLink { get; set; }
public string EmailConfirmationUrl { get; set; }
public async Task<IActionResult> OnGetAsync(string email, string returnUrl = null)
{
if (email == null)
{
return RedirectToPage("/Index");
}
var user = await _userManager.FindByEmailAsync(email);
if (user == null)
{
return NotFound($"Unable to load user with email '{email}'.");
}
Email = email;
// Once you add a real email sender, you should remove this code that lets you confirm the account
DisplayConfirmAccountLink = true;
if (DisplayConfirmAccountLink)
{
var userId = await _userManager.GetUserIdAsync(user);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
EmailConfirmationUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
}
return Page();
}
}
}

View File

@@ -0,0 +1,71 @@
@page
@model RegisterComapnyModel
@{
ViewData["Title"] = "Registrierung als Lehrperson";
}
<h1>@ViewData["Title"]</h1>
<div class="card shadow-lg p-3 mb-5 bg-white rounded">
<div class="row">
<div class="col-md-4">
<form asp-route-returnUrl="@Model.ReturnUrl" method="post">
<h4>Neues Konto erstellen</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" class="form-control" />
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
<div class="col-md-6 col-md-offset-2">
<section>
<h4>Ablauf</h4>
<hr />
@{
if ((Model.ExternalLogins?.Count ?? 0) == 0)
{
<div>
<p>
Nach der Registrierung erhalten Sie ein E-Mail um Ihr Konto zu bestätigen.
</p>
<p>
Nach der Bestätigung können Sie Ihre Daten verwalten.
</p>
</div>
}
else
{
<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
<div>
<p>
@foreach (var provider in Model.ExternalLogins)
{
<button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
}
</p>
</div>
</form>
}
}
</section>
</div>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class RegisterTeacherModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
public RegisterTeacherModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
ReturnUrl = returnUrl;
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
await _userManager.AddToRoleAsync(user, "Lehrer");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
BlazorApp.Helper.ParameterHelper ph = new BlazorApp.Helper.ParameterHelper();
string smtpserver = ph.GetParameter("smtpserver");
string smtpuser = ph.GetParameter("smtpuser");
string smtppw = ph.GetParameter("smtppw");
string smtpport = ph.GetParameter("smtpport");
BlazorApp.Helper.EmailSender esend = new BlazorApp.Helper.EmailSender(smtpserver, Convert.ToInt32(smtpport), true, smtpuser, smtppw);
await esend.SendEmailAsync(Input.Email,"BWPM: Registrierungsbestätigung",
$"Sie haben sich beim Berufswahlparcours registriert. Bitte bestätigen Sie Ihre Registrierung über den folgenden Link_ <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>Registrierung Bestägigen</a>.");
//await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
// $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
}

View File

@@ -0,0 +1,37 @@
@page
@model ResetPasswordModel
@{
ViewData["Title"] = "Reset password";
}
<h1>@ViewData["Title"]</h1>
<h4>Reset your password.</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="Input.Code" type="hidden" />
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" class="form-control" />
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Reset</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

View File

@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ResetPasswordModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
public ResetPasswordModel(UserManager<IdentityUser> userManager)
{
_userManager = userManager;
}
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string Code { get; set; }
}
public IActionResult OnGet(string code = null)
{
if (code == null)
{
return BadRequest("A code must be supplied for password reset.");
}
else
{
Input = new InputModel
{
Code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code))
};
return Page();
}
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.FindByEmailAsync(Input.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToPage("./ResetPasswordConfirmation");
}
var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password);
if (result.Succeeded)
{
return RedirectToPage("./ResetPasswordConfirmation");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
}
}

View File

@@ -0,0 +1,10 @@
@page
@model ResetPasswordConfirmationModel
@{
ViewData["Title"] = "Reset password confirmation";
}
<h1>@ViewData["Title"]</h1>
<p>
Your password has been reset. Please <a asp-page="./Login">click here to log in</a>.
</p>

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlazorApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ResetPasswordConfirmationModel : PageModel
{
public void OnGet()
{
}
}
}

View File

@@ -0,0 +1,10 @@
@model string
@if (!String.IsNullOrEmpty(Model))
{
var statusMessageClass = Model.StartsWith("Error") ? "danger" : "success";
<div class="alert alert-@statusMessageClass alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
@Model
</div>
}

View File

@@ -0,0 +1 @@
@using BlazorApp.Areas.Identity.Pages.Account

View File

@@ -0,0 +1,23 @@
@page
@model ErrorModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>Development environment should not be enabled in deployed applications</strong>, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>, and restarting the application.
</p>

View File

@@ -0,0 +1,21 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace BlazorApp.Areas.Identity.Pages
{
[AllowAnonymous]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}

View File

@@ -0,0 +1,18 @@
<environment include="Development">
<script src="~/Identity/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/Identity/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.17.0/jquery.validate.min.js"
asp-fallback-src="~/Identity/lib/jquery-validation/dist/jquery.validate.min.js"
asp-fallback-test="window.jQuery && window.jQuery.validator"
crossorigin="anonymous"
integrity="sha384-rZfj/ogBloos6wzLGpPkkOr/gpkBNLZ6b6yLy4o+ok+t/SAKlL5mvXLr0OXNi1Hp">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.9/jquery.validate.unobtrusive.min.js"
asp-fallback-src="~/Identity/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"
asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive"
crossorigin="anonymous"
integrity="sha384-ifv0TYDWxBHzvAk2Z0n8R434FL1Rlv/Av18DXE43N/1rvHyOG4izKst0f2iSLdds">
</script>
</environment>

View File

@@ -0,0 +1,4 @@
@using Microsoft.AspNetCore.Identity
@using BlazorApp.Areas.Identity
@using BlazorApp.Areas.Identity.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@@ -0,0 +1,4 @@
@{
Layout = "/Pages/Shared/_Layout.cshtml";
}

View File

@@ -0,0 +1,56 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>b42c85b7-be12-4985-a19a-d4d5d80d37fb</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Blazored.SessionStorage" Version="1.0.13" />
<PackageReference Include="FastReport.Core" Version="2021.3.17" />
<PackageReference Include="FastReport.Web" Version="2021.3.17" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.15" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.1.15" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.15" />
<PackageReference Include="Microsoft.AspNetCore.ProtectedBrowserStorage" Version="0.1.0-alpha.19521.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.15">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.14" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.5" />
<PackageReference Include="Radzen.Blazor" Version="3.6.7" />
<PackageReference Include="Syncfusion.Blazor" Version="19.1.0.54" />
<PackageReference Include="Syncfusion.Blazor.Themes" Version="19.1.0.54" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="System.Net.Http.Json" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Models\BWPMModels.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Update="Resources\SfResources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SfResources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resources\SfResources.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SfResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="Pages\User\" />
</ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JsonSchema="https://ffizer.github.io/ffizer/ffizer.schema.json" /></VisualStudio></ProjectExtensions>
</Project>

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<_SelectedScaffolderID>IdentityScaffolder</_SelectedScaffolderID>
<_SelectedScaffolderCategoryPath>root/Identity</_SelectedScaffolderCategoryPath>
<WebStackScaffolding_ViewDialogWidth>800</WebStackScaffolding_ViewDialogWidth>
<WebStackScaffolding_DbContextDialogWidth>650</WebStackScaffolding_DbContextDialogWidth>
<ActiveDebugProfile>IIS Express</ActiveDebugProfile>
<RazorPage_SelectedScaffolderID>RazorPageScaffolder</RazorPage_SelectedScaffolderID>
<RazorPage_SelectedScaffolderCategoryPath>root/Common/RazorPage</RazorPage_SelectedScaffolderCategoryPath>
<Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
<NameOfLastUsedPublishProfile>E:\Software-Projekte\Lehrlingsparcours\Core\BWPM\BlazorApp\Properties\PublishProfiles\FolderProfile.pubxml</NameOfLastUsedPublishProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class AnredeController : ControllerBase
{
public static List<Anrede> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Anrede", false, true);
return dbh.ConvertDataTable<Anrede>(dbh.dsdaten.Tables[0]);
}
public static List<Anrede> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Anrede where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Anrede>(dbh.dsdaten.Tables[0]);
}
public static List<Anrede> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Anrede order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Anrede>(dbh.dsdaten.Tables[0]);
}
public static List<Anrede> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Anrede where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Anrede>(dbh.dsdaten.Tables[0]);
}
public static List<Anrede> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<Anrede>(dbh.dsdaten.Tables[0]);
}
public static int POST(Anrede Anrededata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Anrede] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
Anrededata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Anrededata, null);
}
else
{
dr[f.Name] = f.GetValue(Anrededata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
List<Anrede> tmplst = GetLastByMutierer(Anrededata.mutierer);
return tmplst.First<Anrede>().ID;
}
public static void PUT(Anrede Anrededata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Anrede] where id=" + Anrededata.ID.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
Anrededata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Anrededata, null);
}
else
{
dr[f.Name] = f.GetValue(Anrededata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(Anrede Anrededata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [Anrede] where id=" + Anrededata.ID.ToString(), false, true);
}
}
}

View File

@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class AspNetRolesController : ControllerBase
{
public static List<AspNetRoles> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from AspNetRoles", false, true);
return dbh.ConvertDataTable<AspNetRoles>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetRoles> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from AspNetRoles where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<AspNetRoles>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetRoles> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from AspNetRoles order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<AspNetRoles>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetRoles> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from AspNetRoles where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<AspNetRoles>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetRoles> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<AspNetRoles>(dbh.dsdaten.Tables[0]);
}
public static void POST(AspNetRoles AspNetRolesdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [AspNetRoles] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
AspNetRolesdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(AspNetRolesdata, null);
}
else
{
dr[f.Name] = f.GetValue(AspNetRolesdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
}
public static void PUT(AspNetRoles AspNetRolesdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [AspNetRoles] where id=" + AspNetRolesdata.Id.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
AspNetRolesdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(AspNetRolesdata, null);
}
else
{
dr[f.Name] = f.GetValue(AspNetRolesdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(AspNetRoles AspNetRolesdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [AspNetRoles] where id=" + AspNetRolesdata.Id.ToString(), false, true);
}
}
}

View File

@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class AspNetUserRolesController : ControllerBase
{
public static List<AspNetUserRoles> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from AspNetUserRoles", false, true);
return dbh.ConvertDataTable<AspNetUserRoles>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUserRoles> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from AspNetUserRoles where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<AspNetUserRoles>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUserRoles> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from AspNetUserRoles order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<AspNetUserRoles>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUserRoles> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from AspNetUserRoles where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<AspNetUserRoles>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUserRoles> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<AspNetUserRoles>(dbh.dsdaten.Tables[0]);
}
public static void POST(AspNetUserRoles AspNetUserRolesdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [AspNetUserRoles] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
AspNetUserRolesdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(AspNetUserRolesdata, null);
}
else
{
dr[f.Name] = f.GetValue(AspNetUserRolesdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
}
public static void PUT(AspNetUserRoles AspNetUserRolesdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [AspNetUserRoles] where userid='" + AspNetUserRolesdata.UserId.ToString()+"'", false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
AspNetUserRolesdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(AspNetUserRolesdata, null);
}
else
{
dr[f.Name] = f.GetValue(AspNetUserRolesdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(AspNetUserRoles AspNetUserRolesdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [AspNetUserRoles] where id=" + AspNetUserRolesdata.UserId.ToString(), false, true);
}
}
}

View File

@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class AspNetUserRolleController : ControllerBase
{
public static List<AspNetUserRolle> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from AspNetUserRolle", false, true);
return dbh.ConvertDataTable<AspNetUserRolle>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUserRolle> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from AspNetUserRolle where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<AspNetUserRolle>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUserRolle> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from AspNetUserRolle order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<AspNetUserRolle>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUserRolle> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from AspNetUserRolle where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<AspNetUserRolle>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUserRolle> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<AspNetUserRolle>(dbh.dsdaten.Tables[0]);
}
public static void POST(AspNetUserRolle AspNetUserRolledata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [AspNetUserRolle] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
AspNetUserRolledata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(AspNetUserRolledata, null);
}
else
{
dr[f.Name] = f.GetValue(AspNetUserRolledata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
}
public static void PUT(AspNetUserRolle AspNetUserRolledata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [AspNetUserRolle] where id=" + AspNetUserRolledata.Id.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
AspNetUserRolledata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(AspNetUserRolledata, null);
}
else
{
dr[f.Name] = f.GetValue(AspNetUserRolledata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void PUTPassword(AspNetUsers aspNetUser)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [AspNetUsers] where id='" +aspNetUser.Id + "'", false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
dr["PasswordHash"] = aspNetUser.PasswordHash;
dbh.Update_Tabeldata();
}
public static void DELETE(AspNetUserRolle AspNetUserRolledata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [AspNetUserRolle] where id=" + AspNetUserRolledata.Id.ToString(), false, true);
}
}
}

View File

@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class AspNetUsersController : ControllerBase
{
public static List<AspNetUsers> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from AspNetUsers", false, true);
return dbh.ConvertDataTable<AspNetUsers>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUsers> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from AspNetUsers where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<AspNetUsers>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUsers> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from AspNetUsers order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<AspNetUsers>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUsers> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from AspNetUsers where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<AspNetUsers>(dbh.dsdaten.Tables[0]);
}
public static List<AspNetUsers> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<AspNetUsers>(dbh.dsdaten.Tables[0]);
}
public static void POST(AspNetUsers AspNetUsersdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [AspNetUsers] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
AspNetUsersdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(AspNetUsersdata, null);
}
else
{
dr[f.Name] = f.GetValue(AspNetUsersdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
}
public static void PUT(AspNetUsers AspNetUsersdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [AspNetUsers] where id=" + AspNetUsersdata.Id.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
AspNetUsersdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(AspNetUsersdata, null);
}
else
{
dr[f.Name] = f.GetValue(AspNetUsersdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(AspNetUsers AspNetUsersdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [AspNetUsers] where id=" + AspNetUsersdata.Id.ToString(), false, true);
}
}
}

View File

@@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class BerufController : ControllerBase
{
public static List<Beruf> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Beruf", false, true);
return dbh.ConvertDataTable<Beruf>(dbh.dsdaten.Tables[0]);
}
public static List<Beruf> GetAllAktiveData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Beruf where aktiv=1 order by bezeichnung", false, true);
return dbh.ConvertDataTable<Beruf>(dbh.dsdaten.Tables[0]);
}
public static List<Beruf> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Beruf where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Beruf>(dbh.dsdaten.Tables[0]);
}
public static List<Beruf> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Beruf order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Beruf>(dbh.dsdaten.Tables[0]);
}
public static List<Beruf> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Beruf where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Beruf>(dbh.dsdaten.Tables[0]);
}
public static List<Beruf> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<Beruf>(dbh.dsdaten.Tables[0]);
}
public static int POST(Beruf Berufdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Beruf] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
Berufdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Berufdata, null);
}
else
{
dr[f.Name] = f.GetValue(Berufdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
List<Beruf> tmplst = GetLastByMutierer(Berufdata.mutierer);
return tmplst.First<Beruf>().ID;
}
public static void PUT(Beruf Berufdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Beruf] where id=" + Berufdata.ID.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
Berufdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Berufdata, null);
}
else
{
dr[f.Name] = f.GetValue(Berufdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(Beruf Berufdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [Beruf] where id=" + Berufdata.ID.ToString(), false, true);
}
public static List<Beruf> GetBerufsangebot()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select Beruf.* from dbo.FirmaBeruf INNER JOIN dbo.Firma ON dbo.FirmaBeruf.ID = dbo.Firma.ID INNER JOIN dbo.Beruf ON dbo.FirmaBeruf.ID = dbo.Beruf.ID WHERE(dbo.Beruf.aktiv = 1) AND(dbo.FirmaBeruf.aktiv = 1) AND(dbo.Firma.aktiv = 1) AND(dbo.Firma.aktuell = 1)", false, true);
return dbh.ConvertDataTable<Beruf>(dbh.dsdaten.Tables[0]);
}
}
}

View File

@@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class AnsprechpartnerController : ControllerBase
{
public static List<Ansprechpartner> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Ansprechpartner", false, true);
return dbh.ConvertDataTable<Ansprechpartner>(dbh.dsdaten.Tables[0]);
}
public static List<ViewAnsprechpartner> GetAllAktivData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("SELECT ID, FirmaID, name + ' ' + vorname AS Ansprechpartner FROM dbo.Ansprechpartner WHERE aktiv = 1 ORDER BY Ansprechpartner", false, true);
return dbh.ConvertDataTable<ViewAnsprechpartner>(dbh.dsdaten.Tables[0]);
}
public static List<Ansprechpartner> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Ansprechpartner where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Ansprechpartner>(dbh.dsdaten.Tables[0]);
}
public static List<Ansprechpartner> GetByFirmaID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Ansprechpartner where aktiv=1 and firmaid=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Ansprechpartner>(dbh.dsdaten.Tables[0]);
}
public static List<Ansprechpartner> GetAllAktivDataByFirmaID(int firmaid)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("SELECT * from Ansprechpartner WHERE aktiv = 1 and firmaid=" + firmaid.ToString() + " ORDER BY Name, Vorname", false, true);
return dbh.ConvertDataTable<Ansprechpartner>(dbh.dsdaten.Tables[0]);
}
public static List<Ansprechpartner> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Ansprechpartner order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Ansprechpartner>(dbh.dsdaten.Tables[0]);
}
public static List<Ansprechpartner> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Ansprechpartner where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Ansprechpartner>(dbh.dsdaten.Tables[0]);
}
public static List<Ansprechpartner> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<Ansprechpartner>(dbh.dsdaten.Tables[0]);
}
public static int POST(Ansprechpartner Ansprechpartnerdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Ansprechpartner] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
Ansprechpartnerdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Ansprechpartnerdata, null);
}
else
{
dr[f.Name] = f.GetValue(Ansprechpartnerdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
List<Ansprechpartner> tmplst = GetLastByMutierer(Ansprechpartnerdata.mutierer);
return tmplst.First<Ansprechpartner>().ID;
}
public static void PUT(Ansprechpartner Ansprechpartnerdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Ansprechpartner] where id=" + Ansprechpartnerdata.ID.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
Ansprechpartnerdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Ansprechpartnerdata, null);
}
else
{
dr[f.Name] = f.GetValue(Ansprechpartnerdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(Ansprechpartner Ansprechpartnerdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [Ansprechpartner] where id=" + Ansprechpartnerdata.ID.ToString(), false, true);
}
}
public class ViewAnsprechpartner
{
}
}

View File

@@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class FirmaController : ControllerBase
{
public static List<Firma> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Firma", false, true);
return dbh.ConvertDataTable<Firma>(dbh.dsdaten.Tables[0]);
}
public static List<Firma> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Firma where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Firma>(dbh.dsdaten.Tables[0]);
}
public static List<Firma> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Firma order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Firma>(dbh.dsdaten.Tables[0]);
}
public static List<Firma> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Firma where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Firma>(dbh.dsdaten.Tables[0]);
}
public static List<Firma> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<Firma>(dbh.dsdaten.Tables[0]);
}
public static List<Firma> GetByUserID(string UserID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Firma where userid='" + UserID + "'", false, true);
if (dbh.dsdaten.Tables[0].Rows.Count==0)
{
Firma Firmadata = new Firma();
Firmadata.aktiv = true;
Firmadata.erstellt_am = DateTime.Now;
Firmadata.mutierer = UserID;
Firmadata.mutiert_am = DateTime.Now;
Firmadata.userid = UserID;
POST(Firmadata);
dbh.Get_Tabledata("Select * from Firma where userid='" + UserID + "'", false, true);
}
return dbh.ConvertDataTable<Firma>(dbh.dsdaten.Tables[0]);
}
public static int POST(Firma Firmadata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Firma] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
Firmadata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Firmadata, null);
}
else
{
dr[f.Name] = f.GetValue(Firmadata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
List<Firma> tmplst = GetLastByMutierer(Firmadata.mutierer);
return tmplst.First<Firma>().ID;
}
public static void PUT(Firma Firmadata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Firma] where id=" + Firmadata.ID.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
Firmadata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Firmadata, null);
}
else
{
dr[f.Name] = f.GetValue(Firmadata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(Firma Firmadata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [Firma] where id=" + Firmadata.ID.ToString(), false, true);
}
}
}

View File

@@ -0,0 +1,116 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class FirmaberufController : ControllerBase
{
public static List<Firmaberuf> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Firmaberuf", false, true);
return dbh.ConvertDataTable<Firmaberuf>(dbh.dsdaten.Tables[0]);
}
public static List<Firmaberuf> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Firmaberuf where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Firmaberuf>(dbh.dsdaten.Tables[0]);
}
public static List<Firmaberuf> GetAllAktiveByFirmaID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Firmaberuf where aktiv=1 and firmaid=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Firmaberuf>(dbh.dsdaten.Tables[0]);
}
public static List<Firmaberuf> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Firmaberuf order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Firmaberuf>(dbh.dsdaten.Tables[0]);
}
public static List<Firmaberuf> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Firmaberuf where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Firmaberuf>(dbh.dsdaten.Tables[0]);
}
public static List<Firmaberuf> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<Firmaberuf>(dbh.dsdaten.Tables[0]);
}
public static int POST(Firmaberuf Firmaberufdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Firmaberuf] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
Firmaberufdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Firmaberufdata, null);
}
else
{
dr[f.Name] = f.GetValue(Firmaberufdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
List<Firmaberuf> tmplst = GetLastByMutierer(Firmaberufdata.mutierer);
return tmplst.First<Firmaberuf>().ID;
}
public static void PUT(Firmaberuf Firmaberufdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Firmaberuf] where id=" + Firmaberufdata.ID.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
Firmaberufdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Firmaberufdata, null);
}
else
{
dr[f.Name] = f.GetValue(Firmaberufdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(Firmaberuf Firmaberufdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [Firmaberuf] where id=" + Firmaberufdata.ID.ToString(), false, true);
}
}
}

View File

@@ -0,0 +1,118 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class KlasseController : ControllerBase
{
public static List<Klasse> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Klasse", false, true);
return dbh.ConvertDataTable<Klasse>(dbh.dsdaten.Tables[0]);
}
public static List<Klasse> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Klasse where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Klasse>(dbh.dsdaten.Tables[0]);
}
public static List<Klasse> GetByLehrerID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Klasse where lehrerid=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Klasse>(dbh.dsdaten.Tables[0]);
}
public static List<Klasse> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Klasse order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Klasse>(dbh.dsdaten.Tables[0]);
}
public static List<Klasse> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Klasse where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Klasse>(dbh.dsdaten.Tables[0]);
}
public static List<Klasse> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<Klasse>(dbh.dsdaten.Tables[0]);
}
public static int POST(Klasse Klassedata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Klasse] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
Klassedata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Klassedata, null);
}
else
{
dr[f.Name] = f.GetValue(Klassedata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
List<Klasse> tmplst = GetLastByMutierer(Klassedata.mutierer);
return tmplst.First<Klasse>().ID;
}
public static void PUT(Klasse Klassedata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Klasse] where id=" + Klassedata.ID.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
Klassedata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Klassedata, null);
}
else
{
dr[f.Name] = f.GetValue(Klassedata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(Klasse Klassedata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [Klasse] where id=" + Klassedata.ID.ToString(), false, true);
}
}
}

View File

@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class KlassentypController : ControllerBase
{
public static List<Klassentyp> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Klassentyp", false, true);
return dbh.ConvertDataTable<Klassentyp>(dbh.dsdaten.Tables[0]);
}
public static List<Klassentyp> GetAllAktiveData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Klassentyp where aktiv=1", false, true);
return dbh.ConvertDataTable<Klassentyp>(dbh.dsdaten.Tables[0]);
}
public static List<Klassentyp> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Klassentyp where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Klassentyp>(dbh.dsdaten.Tables[0]);
}
public static List<Klassentyp> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Klassentyp order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Klassentyp>(dbh.dsdaten.Tables[0]);
}
public static List<Klassentyp> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Klassentyp where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Klassentyp>(dbh.dsdaten.Tables[0]);
}
public static List<Klassentyp> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<Klassentyp>(dbh.dsdaten.Tables[0]);
}
public static int POST(Klassentyp Klassentypdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Klassentyp] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
Klassentypdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Klassentypdata, null);
}
else
{
dr[f.Name] = f.GetValue(Klassentypdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
List<Klassentyp> tmplst = GetLastByMutierer(Klassentypdata.mutierer);
return tmplst.First<Klassentyp>().ID;
}
public static void PUT(Klassentyp Klassentypdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Klassentyp] where id=" + Klassentypdata.ID.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
Klassentypdata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Klassentypdata, null);
}
else
{
dr[f.Name] = f.GetValue(Klassentypdata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(Klassentyp Klassentypdata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [Klassentyp] where id=" + Klassentypdata.ID.ToString(), false, true);
}
}
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
namespace BlazorApp.Controller
{
public class MyScriptController
{
public static List<MyScriptGenerator> GetAllData()
{
Helper.HttpClientHelper httpcli = new Helper.HttpClientHelper();
httpcli.CallService("Optionen", "", "GET", null);
return JsonConvert.DeserializeObject<List<MyScriptGenerator>>(httpcli.Results.daten);
}
public static List<MyScriptGenerator> GetData(int fnkt, string tablename)
{
Helper.HttpClientHelper httpcli = new Helper.HttpClientHelper();
httpcli.CallService("MyScript", fnkt.ToString()+","+tablename+"", "GET", null);
return JsonConvert.DeserializeObject<List<MyScriptGenerator>>(httpcli.Results.daten);
}
}
}

View File

@@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorApp.Controller
{
public class NewAnredeController : ControllerBase
{
}
}

View File

@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BWPMModels;
using BlazorApp.Helper;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Mvc;
namespace BlazorApp.Controller
{
public class OptionenController : ControllerBase
{
public static List<Optionen> GetAllData()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Optionen", false, true);
return dbh.ConvertDataTable<Optionen>(dbh.dsdaten.Tables[0]);
}
public static List<Optionen> GetByID(int ID)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select * from Optionen where id=" + ID.ToString(), false, true);
return dbh.ConvertDataTable<Optionen>(dbh.dsdaten.Tables[0]);
}
public static List<Optionen> GetLast()
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Optionen order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Optionen>(dbh.dsdaten.Tables[0]);
}
public static List<Optionen> GetLastByMutierer(string Mutierer)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata("Select top 1 * from Optionen where mutierer='" + Mutierer + "' order by mutiert_am desc", false, true);
return dbh.ConvertDataTable<Optionen>(dbh.dsdaten.Tables[0]);
}
public static List<Optionen> GetbyUserSQL(string SQL)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabledata(SQL, false, true);
return dbh.ConvertDataTable<Optionen>(dbh.dsdaten.Tables[0]);
}
public static int POST(Optionen Optionendata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Optionen] where id=-1", false, true);
DataRow dr = dbh.dsdaten.Tables[0].NewRow();
Optionendata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Optionendata, null);
}
else
{
dr[f.Name] = f.GetValue(Optionendata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.dsdaten.Tables[0].Rows.Add(dr);
dbh.Update_Tabeldata();
List<Optionen> tmplst = GetLastByMutierer(Optionendata.mutierer);
return tmplst.First<Optionen>().ID;
}
public static void PUT(Optionen Optionendata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("Select top 1 * from [Optionen] where id=" + Optionendata.ID.ToString(), false, true);
DataRow dr = dbh.dsdaten.Tables[0].Rows[0];
Optionendata.GetType().GetProperties().ToList().ForEach(f =>
{
try
{
if (f.PropertyType == typeof(DateTime))
{
dr[f.Name] = (DateTime)f.GetValue(Optionendata, null);
}
else
{
dr[f.Name] = f.GetValue(Optionendata, null);
}
}
catch (Exception ex) { string s = ex.Message; }
});
dbh.Update_Tabeldata();
}
public static void DELETE(Optionen Optionendata)
{
dbhelper dbh = new dbhelper();
dbh.Get_Tabeldata_for_Update("delete from [Optionen] where id=" + Optionendata.ID.ToString(), false, true);
}
}
}

Some files were not shown because too many files have changed in this diff Show More