Merge pull request 'feature/oidc' (#6) from feature/oidc into development

Reviewed-on: daniel-hbn/Watcher#6
This commit is contained in:
2025-06-14 18:17:14 +00:00
13 changed files with 680 additions and 66 deletions

View File

@@ -0,0 +1,41 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Watcher.Controllers;
public class AuthController : Controller
{
public IActionResult Login()
{
return View();
}
public IActionResult SignIn()
{
return Challenge(new AuthenticationProperties
{
RedirectUri = "/"
}, "oidc");
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return RedirectToAction("Index", "Home");
}
[Authorize]
public IActionResult Info()
{
var name = User.Identity?.Name;
var claims = User.Claims.Select(c => new { c.Type, c.Value }).ToList();
ViewBag.Name = name;
ViewBag.Claims = claims;
return View();
}
}

View File

@@ -1,9 +1,11 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Watcher.Models;
namespace Watcher.Controllers;
[Authorize]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

View File

@@ -0,0 +1,278 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Watcher.Data;
#nullable disable
namespace Watcher.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20250614173150_UserChanges")]
partial class UserChanges
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("Watcher.Models.Container", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("longtext");
b.Property<int?>("ImageId")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("longtext");
b.Property<int?>("TagId")
.HasColumnType("int");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("ImageId");
b.HasIndex("TagId");
b.ToTable("Containers");
});
modelBuilder.Entity("Watcher.Models.Image", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("longtext");
b.Property<string>("Tag")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("Images");
});
modelBuilder.Entity("Watcher.Models.LogEvent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("ContainerId")
.HasColumnType("int");
b.Property<string>("Level")
.HasColumnType("longtext");
b.Property<string>("Message")
.HasColumnType("longtext");
b.Property<int?>("ServerId")
.HasColumnType("int");
b.Property<DateTime>("Timestamp")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("ContainerId");
b.HasIndex("ServerId");
b.ToTable("LogEvents");
});
modelBuilder.Entity("Watcher.Models.Metric", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("ContainerId")
.HasColumnType("int");
b.Property<int?>("ServerId")
.HasColumnType("int");
b.Property<DateTime>("Timestamp")
.HasColumnType("datetime(6)");
b.Property<string>("Type")
.HasColumnType("longtext");
b.Property<double>("Value")
.HasColumnType("double");
b.HasKey("Id");
b.HasIndex("ContainerId");
b.HasIndex("ServerId");
b.ToTable("Metrics");
});
modelBuilder.Entity("Watcher.Models.Server", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Hostname")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("longtext");
b.Property<int?>("TagId")
.HasColumnType("int");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("TagId");
b.ToTable("Servers");
});
modelBuilder.Entity("Watcher.Models.Tag", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("Tags");
});
modelBuilder.Entity("Watcher.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Email")
.HasColumnType("longtext");
b.Property<DateTime>("LastLogin")
.HasColumnType("datetime(6)");
b.Property<string>("PocketId")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("PreferredUsername")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Watcher.Models.Container", b =>
{
b.HasOne("Watcher.Models.Image", null)
.WithMany("Containers")
.HasForeignKey("ImageId");
b.HasOne("Watcher.Models.Tag", null)
.WithMany("Containers")
.HasForeignKey("TagId");
});
modelBuilder.Entity("Watcher.Models.LogEvent", b =>
{
b.HasOne("Watcher.Models.Container", "Container")
.WithMany()
.HasForeignKey("ContainerId");
b.HasOne("Watcher.Models.Server", "Server")
.WithMany()
.HasForeignKey("ServerId");
b.Navigation("Container");
b.Navigation("Server");
});
modelBuilder.Entity("Watcher.Models.Metric", b =>
{
b.HasOne("Watcher.Models.Container", "Container")
.WithMany()
.HasForeignKey("ContainerId");
b.HasOne("Watcher.Models.Server", "Server")
.WithMany()
.HasForeignKey("ServerId");
b.Navigation("Container");
b.Navigation("Server");
});
modelBuilder.Entity("Watcher.Models.Server", b =>
{
b.HasOne("Watcher.Models.Tag", null)
.WithMany("Servers")
.HasForeignKey("TagId");
});
modelBuilder.Entity("Watcher.Models.Image", b =>
{
b.Navigation("Containers");
});
modelBuilder.Entity("Watcher.Models.Tag", b =>
{
b.Navigation("Containers");
b.Navigation("Servers");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,79 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Watcher.Migrations
{
/// <inheritdoc />
public partial class UserChanges : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Role",
table: "Users",
newName: "PreferredUsername");
migrationBuilder.UpdateData(
table: "Users",
keyColumn: "PocketId",
keyValue: null,
column: "PocketId",
value: "");
migrationBuilder.AlterColumn<string>(
name: "PocketId",
table: "Users",
type: "longtext",
nullable: false,
oldClrType: typeof(string),
oldType: "longtext",
oldNullable: true)
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "Email",
table: "Users",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<DateTime>(
name: "LastLogin",
table: "Users",
type: "datetime(6)",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Email",
table: "Users");
migrationBuilder.DropColumn(
name: "LastLogin",
table: "Users");
migrationBuilder.RenameColumn(
name: "PreferredUsername",
table: "Users",
newName: "Role");
migrationBuilder.AlterColumn<string>(
name: "PocketId",
table: "Users",
type: "longtext",
nullable: true,
oldClrType: typeof(string),
oldType: "longtext")
.Annotation("MySql:CharSet", "utf8mb4")
.OldAnnotation("MySql:CharSet", "utf8mb4");
}
}
}

View File

@@ -191,10 +191,17 @@ namespace Watcher.Migrations
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("PocketId")
b.Property<string>("Email")
.HasColumnType("longtext");
b.Property<string>("Role")
b.Property<DateTime>("LastLogin")
.HasColumnType("datetime(6)");
b.Property<string>("PocketId")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("PreferredUsername")
.IsRequired()
.HasColumnType("longtext");

View File

@@ -2,7 +2,9 @@ namespace Watcher.Models;
public class User
{
public int Id { get; set; }
public string? PocketId { get; set; } // z.B. externe ID vom PocketID-Login
public string Role { get; set; } = "User"; // "Admin", "Viewer", etc.
public int Id { get; set; } // PK
public string PocketId { get; set; } = null!;
public string PreferredUsername { get; set; } = null!;
public string? Email { get; set; }
public DateTime LastLogin { get; set; }
}

View File

@@ -1,13 +1,19 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Watcher.Data;
using Watcher.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// HttpContentAccessor
builder.Services.AddHttpContextAccessor();
// ---------- Konfiguration laden ----------
var configuration = builder.Configuration;
@@ -22,23 +28,66 @@ builder.Services.AddDbContext<AppDbContext>(options =>
// ---------- Authentifizierung konfigurieren ----------
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie()
.AddOpenIdConnect(options =>
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://pocketid.triggermeelmo.com";
options.ClientId = "your-client-id";
options.ClientSecret = "your-client-secret";
var config = builder.Configuration.GetSection("Authentication:PocketID");
options.Authority = config["Authority"];
options.ClientId = config["ClientId"];
options.ClientSecret = config["ClientSecret"];
options.ResponseType = "code";
options.CallbackPath = config["CallbackPath"];
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = async ctx =>
{
var db = ctx.HttpContext.RequestServices.GetRequiredService<AppDbContext>();
var principal = ctx.Principal;
var pocketId = principal.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value;
var preferredUsername = principal.FindFirst("preferred_username")?.Value;
var email = principal.FindFirst("email")?.Value;
if (string.IsNullOrEmpty(pocketId))
return;
var user = await db.Users.FirstOrDefaultAsync(u => u.PocketId == pocketId);
if (user == null)
{
user = new User
{
PocketId = pocketId,
PreferredUsername = preferredUsername ?? "",
Email = email,
LastLogin = DateTime.UtcNow
};
db.Users.Add(user);
}
else
{
user.LastLogin = DateTime.UtcNow;
user.PreferredUsername = preferredUsername ?? user.PreferredUsername;
user.Email = email ?? user.Email;
db.Users.Update(user);
}
await db.SaveChangesAsync();
}
};
// Optional: NameClaim & RoleClaim
options.TokenValidationParameters.NameClaimType = "name";
options.TokenValidationParameters.RoleClaimType = "role";
});

View File

@@ -0,0 +1,86 @@
@{
ViewData["Title"] = "Account Info";
var pictureUrl = User.Claims.FirstOrDefault(c => c.Type == "picture")?.Value ?? "123";
}
<h2>Account Info</h2>
<div class="card" style="max-width: 600px; margin: auto; padding: 1rem; box-shadow: 0 0 10px #ccc; text-align:center;">
@if (!string.IsNullOrEmpty(pictureUrl))
{
<img src="@pictureUrl" alt="Profilbild" style="width:120px; height:120px; border-radius:50%; object-fit:cover; margin-bottom:1rem;" />
}
else
{
<div style="width:120px; height:120px; border-radius:50%; background:#ccc; display:inline-block; line-height:120px; font-size:48px; color:#fff; margin-bottom:1rem;">
<span>@(User.Identity?.Name?.Substring(0,1).ToUpper() ?? "?")</span>
</div>
}
<h3>@(User.FindFirst("name")?.Value ?? "Unbekannter Nutzer")</h3>
<table class="table" style="margin-top: 1rem;">
<tbody>
<tr></tr>
<th>Username</th>
<td>@(@User.Claims.FirstOrDefault(c => c.Type == "preferred_username")?.Value ?? "Nicht verfügbar")</td>
</tr>
<tr>
<th>E-Mail</th>
<td>@(@User.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")?.Value ?? "Nicht verfügbar")</td>
</tr>
<tr>
<th>Benutzer-ID</th>
<td>@(User.FindFirst("sub")?.Value ?? "Nicht verfügbar")</td>
</tr>
<tr>
<th>Login-Zeit</th>
<td>@(User.FindFirst("iat") != null
? DateTimeOffset.FromUnixTimeSeconds(long.Parse(User.FindFirst("iat").Value)).ToLocalTime().ToString()
: "Nicht verfügbar")
</td>
</tr>
<tr>
<th>Token läuft ab</th>
<td>@(User.FindFirst("exp") != null
? DateTimeOffset.FromUnixTimeSeconds(long.Parse(User.FindFirst("exp").Value)).ToLocalTime().ToString()
: "Nicht verfügbar")
</td>
</tr>
<tr>
<th>Rollen</th>
<td>
@{
var roles = User.FindAll("role").Select(r => r.Value);
if (!roles.Any())
{
<text>Keine Rollen</text>
}
else
{
<ul>
@foreach (var role in roles)
{
<li>@role</li>
}
</ul>
}
}
</td>
</tr>
</tbody>
</table>
<form method="post" asp-controller="Auth" asp-action="Logout">
<button type="submit" class="btn btn-danger">Abmelden</button>
</form>
</div>
<h3>Alle Claims</h3>
<ul>
@foreach (var claim in User.Claims)
{
<li>@claim.Type: @claim.Value</li>
}
</ul>

View File

@@ -0,0 +1,9 @@
@{
ViewData["Title"] = "Login";
}
<h2>Willkommen beim Watcher</h2>
<p>Bitte melde dich über PocketID an:</p>
<a class="btn btn-primary" href="/Account/SignIn">Mit PocketID anmelden</a>

View File

@@ -1,13 +1,6 @@
@{
ViewData["Title"] = "Home Page";
ViewData["Title"] = "Dashboard";
}
<head>
<link rel="stylesheet" href="css/site.css" />
</head>
<body>
<div class="text-center"></div>
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
</body>
<h1>Dashboard</h1>
<p>Willkommen im Watcher Monitoring Interface!</p>

View File

View File

@@ -1,49 +1,108 @@
<!DOCTYPE html>
<html lang="en">
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
var pictureUrl = User.FindFirst("picture")?.Value;
var preferredUsername = User.FindFirst("preferred_username")?.Value ?? "User";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Watcher</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/Watcher.styles.css" asp-append-version="true" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
<style>
body {
overflow: hidden;
}
.sidebar {
width: 240px;
height: 100vh;
position: fixed;
left: 0;
top: 0;
background-color: #343a40;
color: white;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 1rem;
}
.main {
margin-left: 240px;
padding: 2rem;
}
.nav-link {
color: #adb5bd;
}
.nav-link:hover {
color: white;
}
.account-box {
font-size: 0.9rem;
color: #ced4da;
}
</style>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Watcher</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
<div class="sidebar">
<div>
<h4>Watcher</h4>
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link" href="/">Dashboard</a>
</li>
<li class="nav-item"></li>
<a class="nav-link" href="/Uptime">Uptime</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/Monitoring/Servers">Servers</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/Container">Container</a>
</li>
</ul>
</div>
<div class="account-box mt-auto">
@if (User.Identity?.IsAuthenticated ?? false)
{
<a href="/Auth/Info" class="d-block text-decoration-none text-light">
<div class="d-flex align-items-center gap-2">
<div class="rounded-circle bg-secondary text-white px-2 py-1">
<i class="bi bi-person"></i>
</div>
<div>
<strong>@User.Claims.FirstOrDefault(c => c.Type == "name")?.Value</strong><br />
<small class="text-muted">Profil ansehen</small>
</div>
</div>
</a>
}
else
{
<a class="nav-link p-0 text-primary" href="/Account/Login">Login</a>
}
</div>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2025 - Watcher - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
<main class="main">
@RenderBody()
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

View File

@@ -8,5 +8,14 @@
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "server=192.168.178.68;port=3306;database=watcher;user=monitoringuser;password=ssp123;"
}
},
"Authentication": {
"PocketID": {
"Authority": "https://pocketid.triggermeelmo.com",
"ClientId": "629a5f42-ab02-4905-8311-cc7b64165cc0",
"ClientSecret": "QHUNaRyK2VVYdZVz1cQqv8FEf2qtL6QH",
"CallbackPath": "/signin-oidc",
"ResponseType": "code"
}
}
}