Better Dashboard

This commit is contained in:
LittleSheep 2024-01-30 17:57:23 +08:00
parent cd71bbad5f
commit 2a32c8b2f6
12 changed files with 271 additions and 12 deletions

View File

@ -15,6 +15,7 @@ func RunMigration(source *gorm.DB) error {
&models.AuthChallenge{}, &models.AuthChallenge{},
&models.MagicToken{}, &models.MagicToken{},
&models.ThirdClient{}, &models.ThirdClient{},
&models.ActionEvent{},
); err != nil { ); err != nil {
return err return err
} }

View File

@ -25,6 +25,7 @@ type Account struct {
Challenges []AuthChallenge `json:"challenges"` Challenges []AuthChallenge `json:"challenges"`
Factors []AuthFactor `json:"factors"` Factors []AuthFactor `json:"factors"`
Contacts []AccountContact `json:"contacts"` Contacts []AccountContact `json:"contacts"`
Events []ActionEvent `json:"events"`
MagicTokens []MagicToken `json:"-" gorm:"foreignKey:AssignTo"` MagicTokens []MagicToken `json:"-" gorm:"foreignKey:AssignTo"`
ThirdClients []ThirdClient `json:"clients"` ThirdClients []ThirdClient `json:"clients"`
ConfirmedAt *time.Time `json:"confirmed_at"` ConfirmedAt *time.Time `json:"confirmed_at"`

12
pkg/models/events.go Normal file
View File

@ -0,0 +1,12 @@
package models
type ActionEvent struct {
BaseModel
Type string `json:"type"`
Target string `json:"target"`
Location string `json:"location"`
IpAddress string `json:"ip_address"`
UserAgent string `json:"user_agent"`
AccountID uint `json:"account_id"`
}

View File

@ -27,6 +27,34 @@ func getPrincipal(c *fiber.Ctx) error {
return c.JSON(data) return c.JSON(data)
} }
func getEvents(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
take := c.QueryInt("take", 0)
offset := c.QueryInt("offset", 0)
var count int64
var events []models.ActionEvent
if err := database.C.
Where(&models.ActionEvent{AccountID: user.ID}).
Model(&models.ActionEvent{}).
Count(&count).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
if err := database.C.
Where(&models.ActionEvent{AccountID: user.ID}).
Limit(take).
Offset(offset).
Find(&events).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
return c.JSON(fiber.Map{
"count": count,
"data": events,
})
}
func doRegister(c *fiber.Ctx) error { func doRegister(c *fiber.Ctx) error {
var data struct { var data struct {
Name string `json:"name"` Name string `json:"name"`

View File

@ -32,6 +32,7 @@ func startChallenge(c *fiber.Ctx) error {
return fiber.NewError(fiber.StatusNotFound, err.Error()) return fiber.NewError(fiber.StatusNotFound, err.Error())
} }
services.AddEvent(user, "challenges.start", data.ID, c.IP(), c.Get(fiber.HeaderUserAgent))
return c.JSON(fiber.Map{ return c.JSON(fiber.Map{
"display_name": user.Nick, "display_name": user.Nick,
"challenge": challenge, "challenge": challenge,
@ -90,6 +91,7 @@ func doChallenge(c *fiber.Ctx) error {
func exchangeToken(c *fiber.Ctx) error { func exchangeToken(c *fiber.Ctx) error {
var data struct { var data struct {
Code string `json:"code" form:"code"` Code string `json:"code" form:"code"`
RefreshToken string `json:"refresh_token" form:"refresh_token"`
ClientID string `json:"client_id" form:"client_id"` ClientID string `json:"client_id" form:"client_id"`
ClientSecret string `json:"client_secret" form:"client_secret"` ClientSecret string `json:"client_secret" form:"client_secret"`
RedirectUri string `json:"redirect_uri" form:"redirect_uri"` RedirectUri string `json:"redirect_uri" form:"redirect_uri"`
@ -125,7 +127,7 @@ func exchangeToken(c *fiber.Ctx) error {
}) })
case "refresh_token": case "refresh_token":
// Refresh Token // Refresh Token
access, refresh, err := security.RefreshToken(data.Code) access, refresh, err := security.RefreshToken(data.RefreshToken)
if err != nil { if err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error()) return fiber.NewError(fiber.StatusBadRequest, err.Error())
} }

View File

@ -4,6 +4,7 @@ import (
"code.smartsheep.studio/hydrogen/passport/pkg/database" "code.smartsheep.studio/hydrogen/passport/pkg/database"
"code.smartsheep.studio/hydrogen/passport/pkg/models" "code.smartsheep.studio/hydrogen/passport/pkg/models"
"code.smartsheep.studio/hydrogen/passport/pkg/security" "code.smartsheep.studio/hydrogen/passport/pkg/security"
"code.smartsheep.studio/hydrogen/passport/pkg/services"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/samber/lo" "github.com/samber/lo"
"strings" "strings"
@ -67,13 +68,12 @@ func doConnect(c *fiber.Ctx) error {
switch response { switch response {
case "code": case "code":
// OAuth Authorization Mode // OAuth Authorization Mode
expired := time.Now().Add(7 * 24 * time.Hour)
session, err := security.GrantOauthSession( session, err := security.GrantOauthSession(
user, user,
client, client,
strings.Split(scope, " "), strings.Split(scope, " "),
[]string{"Hydrogen.Passport", client.Alias}, []string{"Hydrogen.Passport", client.Alias},
&expired, nil,
lo.ToPtr(time.Now()), lo.ToPtr(time.Now()),
c.IP(), c.IP(),
c.Get(fiber.HeaderUserAgent), c.Get(fiber.HeaderUserAgent),
@ -82,6 +82,7 @@ func doConnect(c *fiber.Ctx) error {
if err != nil { if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error()) return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else { } else {
services.AddEvent(user, "oauth.connect", client.Alias, c.IP(), c.Get(fiber.HeaderUserAgent))
return c.JSON(fiber.Map{ return c.JSON(fiber.Map{
"session": session, "session": session,
"redirect_uri": redirect, "redirect_uri": redirect,
@ -89,13 +90,12 @@ func doConnect(c *fiber.Ctx) error {
} }
case "token": case "token":
// OAuth Implicit Mode // OAuth Implicit Mode
expired := time.Now().Add(7 * 24 * time.Hour)
session, err := security.GrantOauthSession( session, err := security.GrantOauthSession(
user, user,
client, client,
strings.Split(scope, " "), strings.Split(scope, " "),
[]string{"Hydrogen.Passport", client.Alias}, []string{"Hydrogen.Passport", client.Alias},
&expired, nil,
lo.ToPtr(time.Now()), lo.ToPtr(time.Now()),
c.IP(), c.IP(),
c.Get(fiber.HeaderUserAgent), c.Get(fiber.HeaderUserAgent),
@ -106,6 +106,7 @@ func doConnect(c *fiber.Ctx) error {
} else if access, refresh, err := security.GetToken(session); err != nil { } else if access, refresh, err := security.GetToken(session); err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error()) return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else { } else {
services.AddEvent(user, "oauth.connect", client.Alias, c.IP(), c.Get(fiber.HeaderUserAgent))
return c.JSON(fiber.Map{ return c.JSON(fiber.Map{
"access_token": access, "access_token": access,
"refresh_token": refresh, "refresh_token": refresh,

View File

@ -25,6 +25,8 @@ func NewServer() {
api := A.Group("/api").Name("API") api := A.Group("/api").Name("API")
{ {
api.Get("/users/me", auth, getPrincipal) api.Get("/users/me", auth, getPrincipal)
api.Get("/users/me/events", auth, getEvents)
api.Post("/users", doRegister) api.Post("/users", doRegister)
api.Post("/users/me/confirm", doRegisterConfirm) api.Post("/users/me/confirm", doRegisterConfirm)

20
pkg/services/events.go Normal file
View File

@ -0,0 +1,20 @@
package services
import (
"code.smartsheep.studio/hydrogen/passport/pkg/database"
"code.smartsheep.studio/hydrogen/passport/pkg/models"
)
func AddEvent(user models.Account, event, target, ip, ua string) models.ActionEvent {
evt := models.ActionEvent{
Type: event,
Target: target,
IpAddress: ip,
UserAgent: ua,
AccountID: user.ID,
}
database.C.Save(&evt)
return evt
}

View File

@ -18,7 +18,7 @@ export default function RootLayout(props: any) {
if (ready()) { if (ready()) {
keepGate(location.pathname); keepGate(location.pathname);
} }
}); }, [ready, userinfo]);
function keepGate(path: string, e?: BeforeLeaveEventArgs) { function keepGate(path: string, e?: BeforeLeaveEventArgs) {
const whitelist = ["/auth/login", "/auth/register", "/users/me/confirm"]; const whitelist = ["/auth/login", "/auth/register", "/users/me/confirm"];

View File

@ -214,7 +214,7 @@ export default function LoginPage() {
<Show when={searchParams["redirect_uri"]}> <Show when={searchParams["redirect_uri"]}>
<div id="redirect-info" class="mt-3"> <div id="redirect-info" class="mt-3">
<div role="alert" class="alert shadow-xl"> <div role="alert" class="alert shadow">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
class="stroke-info shrink-0 w-6 h-6"> class="stroke-info shrink-0 w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"

View File

@ -1,13 +1,47 @@
import { useUserinfo } from "../stores/userinfo.tsx"; import { getAtk, useUserinfo } from "../stores/userinfo.tsx";
import { Show } from "solid-js"; import { createSignal, For, Show } from "solid-js";
export default function DashboardPage() { export default function DashboardPage() {
const userinfo = useUserinfo(); const userinfo = useUserinfo();
function getGreeting() {
const currentHour = new Date().getHours();
if (currentHour >= 0 && currentHour < 12) {
return "Good morning! Wishing you a day filled with joy and success. ☀️";
} else if (currentHour >= 12 && currentHour < 18) {
return "Afternoon! Hope you have a productive and joyful afternoon! ☀️";
} else {
return "Good evening! Wishing you a relaxing and pleasant evening. 🌙";
}
}
const [events, setEvents] = createSignal<any[]>([]);
const [eventCount, setEventCount] = createSignal(0);
const [error, setError] = createSignal<string | null>(null);
async function readEvents() {
const res = await fetch("/api/users/me/events?take=10", {
headers: { Authorization: `Bearer ${getAtk()}` }
});
if (res.status !== 200) {
setError(await res.text());
} else {
const data = await res.json();
setEvents(data["data"]);
setEventCount(data["count"]);
}
}
readEvents();
return ( return (
<div class="max-w-[720px] mx-auto px-5 pt-12"> <div class="max-w-[720px] mx-auto px-5 pt-12">
<h1 class="text-2xl font-bold">Welcome, {userinfo?.displayName}</h1> <div id="greeting" class="px-5">
<p>What's a nice day!</p> <h1 class="text-2xl font-bold">Welcome, {userinfo?.displayName}</h1>
<p>{getGreeting()}</p>
</div>
<div id="alerts"> <div id="alerts">
<Show when={!userinfo?.meta?.confirmed_at}> <Show when={!userinfo?.meta?.confirmed_at}>
@ -23,6 +57,164 @@ export default function DashboardPage() {
</div> </div>
</div> </div>
</Show> </Show>
<Show when={error()}>
<div role="alert" class="alert alert-error mt-5">
<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none"
viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span class="capitalize">{error()}</span>
</div>
</Show>
</div>
<div id="overview" class="mt-5">
<div class="stats shadow w-full">
<div class="stat">
<div class="stat-figure text-secondary">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
class="inline-block w-8 h-8 stroke-current">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
</div>
<div class="stat-title">Challenges</div>
<div class="stat-value">{userinfo?.meta?.challenges?.length}</div>
</div>
<div class="stat">
<div class="stat-figure text-secondary">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
class="inline-block w-8 h-8 stroke-current">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"></path>
</svg>
</div>
<div class="stat-title">Sessions</div>
<div class="stat-value">{userinfo?.meta?.sessions?.length}</div>
</div>
<div class="stat">
<div class="stat-figure text-secondary">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
class="inline-block w-8 h-8 stroke-current">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4"></path>
</svg>
</div>
<div class="stat-title">Events</div>
<div class="stat-value">{eventCount()}</div>
</div>
</div>
</div>
<div id="data-area" class="mt-5 shadow">
<div class="join join-vertical w-full">
<details class="collapse collapse-plus join-item border border-base-300">
<summary class="collapse-title text-lg font-medium">
Challenges
</summary>
<div class="collapse-content mx-[-16px]">
<div class="overflow-x-auto">
<table class="table">
<thead>
<tr>
<th></th>
<th>State</th>
<th>IP Address</th>
<th>User Agent</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<For each={userinfo?.meta?.challenges ?? []}>
{item => <tr>
<th>{item.id}</th>
<td>{item.state}</td>
<td>{item.ip_address}</td>
<td>
<span class="tooltip" data-tip={item.user_agent}>
{item.user_agent.substring(0, 10) + "..."}
</span>
</td>
<td>{new Date(item.created_at).toLocaleString()}</td>
</tr>}
</For>
</tbody>
</table>
</div>
</div>
</details>
<details class="collapse collapse-plus join-item border border-base-300">
<summary class="collapse-title text-lg font-medium">
Sessions
</summary>
<div class="collapse-content mx-[-16px]">
<table class="table">
<thead>
<tr>
<th></th>
<th>Third Client</th>
<th>Audiences</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<For each={userinfo?.meta?.sessions ?? []}>
{item => <tr>
<th>{item.id}</th>
<td>{item.client_id ? "Linked" : "Non-linked"}</td>
<td>{item.audiences?.join(", ")}</td>
<td>{new Date(item.created_at).toLocaleString()}</td>
</tr>}
</For>
</tbody>
</table>
</div>
</details>
<details class="collapse collapse-plus join-item border border-base-300">
<summary class="collapse-title text-lg font-medium">
Events
</summary>
<div class="collapse-content mx-[-16px]">
<div class="overflow-x-auto">
<table class="table">
<thead>
<tr>
<th></th>
<th>Type</th>
<th>Target</th>
<th>IP Address</th>
<th>User Agent</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<For each={events()}>
{item => <tr>
<th>{item.id}</th>
<td>{item.type}</td>
<td>{item.target}</td>
<td>{item.ip_address}</td>
<td>
<span class="tooltip" data-tip={item.user_agent}>
{item.user_agent.substring(0, 10) + "..."}
</span>
</td>
<td>{new Date(item.created_at).toLocaleString()}</td>
</tr>}
</For>
</tbody>
</table>
</div>
</div>
</details>
</div>
</div> </div>
</div> </div>
); );

View File

@ -31,7 +31,7 @@ export async function refreshAtk() {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
code: rtk, refresh_token: rtk,
grant_type: "refresh_token" grant_type: "refresh_token"
}) })
}); });