UserInfo Seite zeigt fast alles an + User werden in datenbank registriert

This commit is contained in:
2025-06-14 20:15:44 +02:00
parent d5ea5e4581
commit 546225bfb9
9 changed files with 507 additions and 21 deletions

View File

@@ -19,9 +19,12 @@ public class AuthController : Controller
}, "oidc"); }, "oidc");
} }
public IActionResult Logout() [HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{ {
return SignOut("Cookies", "oidc"); await HttpContext.SignOutAsync();
return RedirectToAction("Index", "Home");
} }
[Authorize] [Authorize]

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() .ValueGeneratedOnAdd()
.HasColumnType("int"); .HasColumnType("int");
b.Property<string>("PocketId") b.Property<string>("Email")
.HasColumnType("longtext"); .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() .IsRequired()
.HasColumnType("longtext"); .HasColumnType("longtext");

View File

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

View File

@@ -1,8 +1,10 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Watcher.Data; using Watcher.Data;
using Watcher.Models;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -40,13 +42,52 @@ builder.Services.AddAuthentication(options =>
options.CallbackPath = config["CallbackPath"]; options.CallbackPath = config["CallbackPath"];
options.SaveTokens = true; options.SaveTokens = true;
options.TokenValidationParameters = new TokenValidationParameters options.GetClaimsFromUserInfoEndpoint = true;
{
NameClaimType = "name", // oder "preferred_username" oder der Wert, den du im Schritt 1 gesehen hast
};
options.Scope.Clear();
options.Scope.Add("openid"); options.Scope.Add("openid");
options.Scope.Add("profile"); 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();
}
};
}); });

View File

@@ -1,15 +1,86 @@
@{ @{
ViewData["Title"] = "Account Info"; ViewData["Title"] = "Account Info";
var pictureUrl = User.Claims.FirstOrDefault(c => c.Type == "picture")?.Value ?? "123";
} }
<h2>Account-Informationen</h2> <h2>Account Info</h2>
<p><strong>Benutzername:</strong> @ViewBag.Name</p> <div class="card" style="max-width: 600px; margin: auto; padding: 1rem; box-shadow: 0 0 10px #ccc; text-align:center;">
@if (!string.IsNullOrEmpty(pictureUrl))
<h4>Claims:</h4>
<ul>
@foreach (var claim in ViewBag.Claims)
{ {
<li><strong>@claim.Type:</strong> @claim.Value</li> <img src="@pictureUrl" alt="Profilbild" style="width:120px; height:120px; border-radius:50%; object-fit:cover; margin-bottom:1rem;" />
} }
</ul> 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

View File

@@ -3,6 +3,11 @@
@using Microsoft.AspNetCore.Http @using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor @inject IHttpContextAccessor HttpContextAccessor
@{
var pictureUrl = User.FindFirst("picture")?.Value;
var preferredUsername = User.FindFirst("preferred_username")?.Value ?? "User";
}
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -63,7 +68,7 @@
<a class="nav-link" href="/Uptime">Uptime</a> <a class="nav-link" href="/Uptime">Uptime</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="/Server">Server</a> <a class="nav-link" href="/Monitoring/Servers">Servers</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="/Container">Container</a> <a class="nav-link" href="/Container">Container</a>
@@ -80,7 +85,7 @@
<i class="bi bi-person"></i> <i class="bi bi-person"></i>
</div> </div>
<div> <div>
<strong>@User.Identity.Name</strong><br /> <strong>@User.Claims.FirstOrDefault(c => c.Type == "name")?.Value</strong><br />
<small class="text-muted">Profil ansehen</small> <small class="text-muted">Profil ansehen</small>
</div> </div>
</div> </div>