Add registration flow and improve admin post management

This commit is contained in:
爱喝水的木子
2026-03-19 20:17:56 +08:00
parent 50a1e476c8
commit 17f5f6adcb
28 changed files with 799 additions and 192 deletions

View File

@@ -1,66 +1,42 @@
# OPC 信息流平台 # OPC Solo Feed 信息流
面向 OPCOne Person Company一人公司的轻量信息流发布站。 OPCOne Person Company一人即是公司)信息流项目,用于个人/小团队以“信息流平台”的方式发布动态、记录进展与沉淀内容。
个人即公司:记录更新、发布进展、同步给关注你的人;简单、克制、能持续。
## 你会得到什么 ## 功能概览
- 一个可公开访问的“个人公司动态墙” - 信息流首页:搜索、标签筛选
- 支持 Markdown 的内容发布 - 内容详情:Markdown 渲染、分享链接/二维码、阅读统计
- 文章详情页可长期访问(稳定 URL - 后台管理:登录、注册、发布/编辑/删除、统计面板
- RSS 订阅与站点地图,方便搜索与关注 - 登录有效期24 小时,过期需重新登录
- 后台口令发布与统计,维护成本低
## 典型使用场景
- 个人产品更新、周报、交付日志
- 公开路线图、里程碑、版本发布
- 内容实验、灵感记录、对外同步
## 技术栈 ## 技术栈
- Next.js 14App Router - Next.js 14App Router
- MongoDB Atlas(免费云数据库) - MongoDB Atlas
- Tailwind CSS - Tailwind CSS
- Markdown 渲染 - Markdown
## 快速开始 ## 本地开发
1. 安装依赖 1. 安装依赖
```bash ```bash
npm install npm install
``` ```
2. 新建 `.env.local` 2. 配置环境变量:新建 `.env.local`
``` ```
MONGODB_URI=你的Mongo连接串 MONGODB_URI=你的Mongo连接串
MONGODB_DB=pushinfo MONGODB_DB=pushinfo
ADMIN_PASS=自定义后台口令 SESSION_SECRET=用于签名的随机长字符串
SESSION_SECRET=任意长随机字符串 NEXT_PUBLIC_SITE_URL=https://你的站点域名
NEXT_PUBLIC_SITE_URL=https://你的域名
``` ```
3. 开发运行 3. 启动开发服务器
```bash ```bash
npm run dev npm run dev
``` ```
## 功能清单 4. 打开页面并注册账号
- 首页信息流:最新发布置顶 - 注册:`/register`
- 文章详情页Markdown 渲染 - 登录:`/login`
- 后台:口令登录、发布、编辑/删除、统计
- 标签聚合页与标签详情页
- 搜索与分页
- RSS`/rss`标题不务正业的木子文案less is more
- Sitemap`/sitemap.xml`
## 部署建议 ## 说明
- 前端Vercel - 后台入口:`/admin`
- 数据库MongoDB Atlas 免费套餐 - 登录后右上角显示当前用户名
- 图片:图床(如 `https://img.020417.xyz`
## 设计原则
- 低摩擦发布
- 少即是多
- 长期可维护
## TODO
- 草稿与置顶
- 私密分享链接
- 全文索引MongoDB Text Index

View File

@@ -2,6 +2,7 @@ import { getDb } from "@/lib/mongo";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { EditPostForm } from "@/components/EditPostForm"; import { EditPostForm } from "@/components/EditPostForm";
import { Post } from "@/types/post"; import { Post } from "@/types/post";
import { DEFAULT_OPC_SIGNAL } from "@/lib/opc";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
@@ -16,7 +17,8 @@ async function fetchPost(slug: string): Promise<Post | null> {
markdown: post.markdown ?? "", markdown: post.markdown ?? "",
cover: post.cover, cover: post.cover,
tags: post.tags ?? [], tags: post.tags ?? [],
author: post.author ?? "admin", signal: post.signal ?? DEFAULT_OPC_SIGNAL,
author: post.author ?? "佚名",
createdAt: post.createdAt ?? new Date().toISOString(), createdAt: post.createdAt ?? new Date().toISOString(),
updatedAt: post.updatedAt ?? post.createdAt ?? new Date().toISOString(), updatedAt: post.updatedAt ?? post.createdAt ?? new Date().toISOString(),
views: post.views ?? 0 views: post.views ?? 0

View File

@@ -4,14 +4,40 @@ import { getDb } from "@/lib/mongo";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
const cardClass =
"rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100 transition-[transform,box-shadow] duration-300 will-change-transform transform-gpu hover:shadow-lg hover:[transform:perspective(900px)_translateY(-4px)_rotateX(2deg)_rotateY(-2deg)]";
async function fetchStats() { async function fetchStats() {
const db = await getDb(); const db = await getDb();
const collection = db.collection("posts"); const collection = db.collection("posts");
const total = await collection.countDocuments(); const total = await collection.countDocuments();
const latest = await collection.find({}, { projection: { title: 1, createdAt: 1 } }).sort({ createdAt: -1 }).limit(1).toArray(); const latest = await collection
const top = await collection.find({}, { projection: { title: 1, views: 1, slug: 1 } }).sort({ views: -1 }).limit(3).toArray(); .find({}, { projection: { title: 1, createdAt: 1 } })
.sort({ createdAt: -1 })
.limit(1)
.toArray();
const top = await collection
.find({}, { projection: { title: 1, views: 1, slug: 1 } })
.sort({ views: -1 })
.limit(3)
.toArray();
const viewsAgg = await collection
.aggregate([{ $group: { _id: null, totalViews: { $sum: { $ifNull: ["$views", 0] } } } }])
.toArray();
const totalViews = viewsAgg[0]?.totalViews ?? 0;
const avgViews = total > 0 ? Math.round(totalViews / total) : 0;
const tagCount = (await collection.distinct("tags")).filter(Boolean).length;
const authorCount = (await collection.distinct("author")).filter(Boolean).length;
return { total, latest: latest[0] || null, top }; return {
total,
latest: latest[0] || null,
top,
totalViews,
avgViews,
tagCount,
authorCount
};
} }
async function fetchRecentPosts() { async function fetchRecentPosts() {
@@ -25,6 +51,7 @@ async function fetchRecentPosts() {
return posts.map((p: any) => ({ return posts.map((p: any) => ({
...p, ...p,
_id: p._id?.toString(), _id: p._id?.toString(),
author: p.author ?? "佚名",
createdAtText: new Date(p.createdAt).toLocaleString("zh-CN", { createdAtText: new Date(p.createdAt).toLocaleString("zh-CN", {
hour12: false, hour12: false,
timeZone: "Asia/Shanghai" timeZone: "Asia/Shanghai"
@@ -32,19 +59,91 @@ async function fetchRecentPosts() {
})); }));
} }
async function fetchAllTags() {
const db = await getDb();
const tags = await db
.collection("posts")
.aggregate([
{ $unwind: "$tags" },
{ $group: { _id: "$tags", count: { $sum: 1 } } },
{ $sort: { count: -1, _id: 1 } }
])
.toArray();
return tags.map((t: any) => t._id).filter(Boolean);
}
async function fetchTagStats() {
const db = await getDb();
const tags = await db
.collection("posts")
.aggregate([
{ $unwind: "$tags" },
{ $group: { _id: "$tags", count: { $sum: 1 } } },
{ $sort: { count: -1, _id: 1 } },
{ $limit: 12 }
])
.toArray();
return tags.map((t: any) => ({ tag: t._id, count: t.count }));
}
async function fetchAuthorStats() {
const db = await getDb();
const authors = await db
.collection("posts")
.aggregate([
{ $group: { _id: { $ifNull: ["$author", "佚名"] }, count: { $sum: 1 } } },
{ $sort: { count: -1, _id: 1 } },
{ $limit: 10 }
])
.toArray();
return authors.map((a: any) => ({ author: a._id, count: a.count }));
}
async function fetchDailyStats() {
const db = await getDb();
const now = new Date();
const days: { key: string; label: string }[] = [];
for (let i = 6; i >= 0; i -= 1) {
const d = new Date(now);
d.setDate(now.getDate() - i);
const key = d.toISOString().slice(0, 10);
const label = `${d.getMonth() + 1}/${d.getDate()}`;
days.push({ key, label });
}
const since = `${days[0].key}T00:00:00.000Z`;
const raw = await db
.collection("posts")
.aggregate([
{ $match: { createdAt: { $gte: since } } },
{ $addFields: { day: { $dateToString: { format: "%Y-%m-%d", date: { $toDate: "$createdAt" } } } } },
{ $group: { _id: "$day", count: { $sum: 1 } } }
])
.toArray();
const map = new Map<string, number>();
raw.forEach((item: any) => map.set(item._id, item.count));
return days.map((d) => ({ label: d.label, count: map.get(d.key) ?? 0 }));
}
export default async function AdminPage() { export default async function AdminPage() {
const stats = await fetchStats(); const stats = await fetchStats();
const recentPosts = await fetchRecentPosts(); const recentPosts = await fetchRecentPosts();
const availableTags = await fetchAllTags();
const tagStats = await fetchTagStats();
const authorStats = await fetchAuthorStats();
const dailyStats = await fetchDailyStats();
const tagMax = Math.max(...tagStats.map((t) => t.count), 1);
const authorMax = Math.max(...authorStats.map((a) => a.count), 1);
const dailyMax = Math.max(...dailyStats.map((d) => d.count), 1);
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<section className="grid gap-4 sm:grid-cols-3"> <section className="grid gap-4 sm:grid-cols-3">
<div className="rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100"> <div className={cardClass}>
<p className="text-sm text-slate-500"></p> <p className="text-sm text-slate-500"></p>
<p className="mt-1 text-3xl font-semibold">{stats.total}</p> <p className="mt-1 text-3xl font-semibold">{stats.total}</p>
</div> </div>
<div className="rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100"> <div className={cardClass}>
<p className="text-sm text-slate-500"></p> <p className="text-sm text-slate-500"></p>
<p className="mt-1 text-base font-semibold">{stats.latest?.title ?? "暂无"}</p> <p className="mt-1 text-base font-semibold">{stats.latest?.title ?? "暂无"}</p>
<p className="text-xs text-slate-500"> <p className="text-xs text-slate-500">
{stats.latest?.createdAt {stats.latest?.createdAt
@@ -52,20 +151,112 @@ export default async function AdminPage() {
: ""} : ""}
</p> </p>
</div> </div>
<div className="rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100"> <div className={cardClass}>
<p className="text-sm text-slate-500">Top </p> <p className="text-sm text-slate-500">Top </p>
<ul className="mt-1 space-y-1 text-sm"> <ul className="mt-1 space-y-1 text-sm">
{stats.top.map((item: any) => ( {stats.top.map((item: any) => (
<li key={item.slug} className="flex items-center justify-between"> <li key={item.slug} className="flex items-center justify-between">
<span className="truncate">{item.title}</span> <span className="truncate">{item.title}</span>
<span className="text-slate-500">{item.views ?? 0} </span> <span className="text-slate-500">{item.views ?? 0} </span>
</li> </li>
))} ))}
</ul> </ul>
</div> </div>
</section> </section>
<CreatePostForm /> <section className="rounded-2xl bg-white/80 p-5 shadow-sm ring-1 ring-slate-100">
<h3 className="text-lg font-semibold"></h3>
<div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<div className={cardClass}>
<p className="text-sm text-slate-500"></p>
<p className="mt-1 text-2xl font-semibold">{stats.totalViews}</p>
</div>
<div className={cardClass}>
<p className="text-sm text-slate-500"></p>
<p className="mt-1 text-2xl font-semibold">{stats.avgViews}</p>
</div>
<div className={cardClass}>
<p className="text-sm text-slate-500"></p>
<p className="mt-1 text-2xl font-semibold">{stats.tagCount}</p>
</div>
<div className={cardClass}>
<p className="text-sm text-slate-500"></p>
<p className="mt-1 text-2xl font-semibold">{stats.authorCount}</p>
</div>
</div>
<div className="mt-6 grid gap-4 lg:grid-cols-2">
<div className="rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100">
<h4 className="text-sm font-semibold text-slate-700"></h4>
<div className="mt-3 space-y-3">
{tagStats.length === 0 ? (
<p className="text-xs text-slate-500"></p>
) : (
tagStats.map((item) => (
<div key={item.tag} className="space-y-1">
<div className="flex items-center justify-between text-xs text-slate-600">
<span>#{item.tag}</span>
<span>{item.count}</span>
</div>
<div className="h-2 rounded-full bg-slate-100">
<div
className="h-2 rounded-full bg-brand-500/80"
style={{ width: `${(item.count / tagMax) * 100}%` }}
/>
</div>
</div>
))
)}
</div>
</div>
<div className="rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100">
<h4 className="text-sm font-semibold text-slate-700"></h4>
<div className="mt-3 space-y-3">
{authorStats.length === 0 ? (
<p className="text-xs text-slate-500"></p>
) : (
authorStats.map((item) => (
<div key={item.author} className="space-y-1">
<div className="flex items-center justify-between text-xs text-slate-600">
<span>{item.author}</span>
<span>{item.count}</span>
</div>
<div className="h-2 rounded-full bg-slate-100">
<div
className="h-2 rounded-full bg-indigo-500/80"
style={{ width: `${(item.count / authorMax) * 100}%` }}
/>
</div>
</div>
))
)}
</div>
</div>
</div>
<div className="mt-6 rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100">
<h4 className="text-sm font-semibold text-slate-700"> 7 </h4>
<div className="mt-3 space-y-3">
{dailyStats.map((item) => (
<div key={item.label} className="space-y-1">
<div className="flex items-center justify-between text-xs text-slate-600">
<span>{item.label}</span>
<span>{item.count}</span>
</div>
<div className="h-2 rounded-full bg-slate-100">
<div
className="h-2 rounded-full bg-emerald-500/80"
style={{ width: `${(item.count / dailyMax) * 100}%` }}
/>
</div>
</div>
))}
</div>
</div>
</section>
<CreatePostForm availableTags={availableTags} />
<AdminPostList initialPosts={recentPosts} /> <AdminPostList initialPosts={recentPosts} />
</div> </div>

View File

@@ -1,26 +1,48 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { signSession, cookieName } from "@/lib/auth"; import { signSession, cookieName } from "@/lib/auth";
import { getDb } from "@/lib/mongo";
import { verifyPassword } from "@/lib/password";
import { z } from "zod";
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const body = await req.json().catch(() => ({})); const body = await req.json().catch(() => ({}));
const password = body.password as string | undefined; const schema = z.object({
const target = process.env.ADMIN_PASS; username: z.string().trim().min(2).max(32),
password: z.string().min(6).max(128)
});
const parsed = schema.safeParse(body);
if (!target) { if (!parsed.success) {
return NextResponse.json({ error: "ADMIN_PASS is not set on server" }, { status: 500 }); return NextResponse.json({ error: "请输入正确的用户名与密码" }, { status: 400 });
} }
if (!password || password !== target) { const { username, password } = parsed.data;
return NextResponse.json({ error: "密码错误" }, { status: 401 }); const db = await getDb();
const user = await db.collection("users").findOne({ usernameLower: username.toLowerCase() });
if (
!user ||
typeof user.passwordSalt !== "string" ||
typeof user.passwordHash !== "string" ||
!verifyPassword(password, user.passwordSalt, user.passwordHash)
) {
return NextResponse.json({ error: "用户名或密码错误" }, { status: 401 });
} }
const token = await signSession({ role: "admin", iat: Date.now() }); const name = user.displayName || user.username || username;
const res = NextResponse.json({ ok: true }); const exp = Date.now() + 24 * 60 * 60 * 1000;
const token = await signSession({
role: "admin",
iat: Date.now(),
exp,
uid: user._id?.toString(),
name
});
const res = NextResponse.json({ ok: true, name });
res.cookies.set(cookieName, token, { res.cookies.set(cookieName, token, {
httpOnly: true, httpOnly: true,
sameSite: "lax", sameSite: "lax",
secure: true, secure: process.env.NODE_ENV === "production",
maxAge: 60 * 60 * 24 * 30, maxAge: 60 * 60 * 24,
path: "/" path: "/"
}); });
return res; return res;

View File

@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/mongo"; import { getDb } from "@/lib/mongo";
import { ObjectId } from "mongodb"; import { ObjectId } from "mongodb";
import { z } from "zod"; import { z } from "zod";
import { OPC_SIGNAL_VALUES } from "@/lib/opc";
export async function GET(_: NextRequest, { params }: { params: { slug: string } }) { export async function GET(_: NextRequest, { params }: { params: { slug: string } }) {
const db = await getDb(); const db = await getDb();
@@ -17,6 +18,7 @@ export async function GET(_: NextRequest, { params }: { params: { slug: string }
return NextResponse.json({ return NextResponse.json({
...post.value, ...post.value,
author: post.value.author ?? "佚名",
_id: (post.value._id as ObjectId)?.toString() _id: (post.value._id as ObjectId)?.toString()
}); });
} }
@@ -28,7 +30,7 @@ export async function PATCH(req: NextRequest, { params }: { params: { slug: stri
markdown: z.string().min(5).optional(), markdown: z.string().min(5).optional(),
cover: z.string().url().nullable().optional(), cover: z.string().url().nullable().optional(),
tags: z.array(z.string().trim()).optional(), tags: z.array(z.string().trim()).optional(),
author: z.string().optional() signal: z.enum(OPC_SIGNAL_VALUES).optional()
}); });
const parsed = schema.safeParse(body); const parsed = schema.safeParse(body);
if (!parsed.success) { if (!parsed.success) {
@@ -49,7 +51,7 @@ export async function PATCH(req: NextRequest, { params }: { params: { slug: stri
set.cover = data.cover; set.cover = data.cover;
} }
if (Array.isArray(data.tags)) set.tags = data.tags; if (Array.isArray(data.tags)) set.tags = data.tags;
if (typeof data.author === "string") set.author = data.author; if (typeof data.signal === "string") set.signal = data.signal;
const update: Record<string, unknown> = { $set: set }; const update: Record<string, unknown> = { $set: set };
if (Object.keys(unset).length > 0) update.$unset = unset; if (Object.keys(unset).length > 0) update.$unset = unset;

View File

@@ -2,13 +2,15 @@ import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/mongo"; import { getDb } from "@/lib/mongo";
import { z } from "zod"; import { z } from "zod";
import { generateSlug } from "@/lib/slug"; import { generateSlug } from "@/lib/slug";
import { DEFAULT_OPC_SIGNAL, OPC_SIGNAL_VALUES } from "@/lib/opc";
import { cookieName, verifySession } from "@/lib/auth";
const postSchema = z.object({ const postSchema = z.object({
title: z.string().min(2).max(80), title: z.string().min(2).max(80),
markdown: z.string().min(5), markdown: z.string().min(5),
cover: z.string().url().optional(), cover: z.string().url().optional(),
tags: z.array(z.string().trim()).optional(), tags: z.array(z.string().trim()).optional(),
author: z.string().default("admin") signal: z.enum(OPC_SIGNAL_VALUES).default(DEFAULT_OPC_SIGNAL)
}); });
export async function GET() { export async function GET() {
@@ -23,6 +25,7 @@ export async function GET() {
return NextResponse.json( return NextResponse.json(
posts.map((p) => ({ posts.map((p) => ({
...p, ...p,
author: p.author ?? "佚名",
_id: p._id?.toString() _id: p._id?.toString()
})) }))
); );
@@ -37,6 +40,12 @@ export async function POST(req: NextRequest) {
} }
const data = parsed.data; const data = parsed.data;
const token = req.cookies.get(cookieName)?.value;
const session = await verifySession(token);
if (!session) {
return NextResponse.json({ error: "未登录" }, { status: 401 });
}
const author = session.name ?? "佚名";
const now = new Date().toISOString(); const now = new Date().toISOString();
let slug = generateSlug(); let slug = generateSlug();
const db = await getDb(); const db = await getDb();
@@ -53,6 +62,7 @@ export async function POST(req: NextRequest) {
const doc = { const doc = {
...data, ...data,
author,
slug, slug,
createdAt: now, createdAt: now,
updatedAt: now, updatedAt: now,

59
app/api/register/route.ts Normal file
View File

@@ -0,0 +1,59 @@
import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/mongo";
import { hashPassword } from "@/lib/password";
import { signSession, cookieName } from "@/lib/auth";
import { z } from "zod";
export async function POST(req: NextRequest) {
const body = await req.json().catch(() => ({}));
const schema = z.object({
username: z.string().trim().min(2).max(32),
password: z.string().min(6).max(128),
displayName: z.string().trim().min(2).max(32).optional()
});
const parsed = schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: "请填写有效的用户名与密码" }, { status: 400 });
}
const { username, password, displayName } = parsed.data;
const usernameLower = username.toLowerCase();
const db = await getDb();
const exists = await db.collection("users").findOne({ usernameLower });
if (exists) {
return NextResponse.json({ error: "用户名已存在" }, { status: 409 });
}
const { hash, salt } = hashPassword(password);
const now = new Date().toISOString();
const doc = {
username,
usernameLower,
displayName: displayName || username,
passwordHash: hash,
passwordSalt: salt,
createdAt: now
};
const result = await db.collection("users").insertOne(doc);
const name = doc.displayName;
const exp = Date.now() + 24 * 60 * 60 * 1000;
const token = await signSession({
role: "admin",
iat: Date.now(),
exp,
uid: result.insertedId?.toString(),
name
});
const res = NextResponse.json({ ok: true, name });
res.cookies.set(cookieName, token, {
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
maxAge: 60 * 60 * 24,
path: "/"
});
return res;
}

View File

@@ -2,13 +2,19 @@ import "./globals.css";
import type { Metadata } from "next"; import type { Metadata } from "next";
import Link from "next/link"; import Link from "next/link";
import { ReactNode } from "react"; import { ReactNode } from "react";
import { cookies } from "next/headers";
import { cookieName, getAdminName, verifySession } from "@/lib/auth";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Push Info", title: "OPC Solo Feed",
description: "轻量信息流发布平台,支持 Markdown 与多端浏览。" description: "轻量信息流发布平台,支持 Markdown 与多端浏览。"
}; };
export default function RootLayout({ children }: { children: ReactNode }) { export default async function RootLayout({ children }: { children: ReactNode }) {
const token = cookies().get(cookieName)?.value;
const session = await verifySession(token);
const userName = session?.name ?? getAdminName();
return ( return (
<html lang="zh-CN"> <html lang="zh-CN">
<body className="text-slate-900 antialiased"> <body className="text-slate-900 antialiased">
@@ -16,11 +22,12 @@ export default function RootLayout({ children }: { children: ReactNode }) {
<header className="mb-8 flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-white/70 p-4 shadow-sm ring-1 ring-slate-100 backdrop-blur"> <header className="mb-8 flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-white/70 p-4 shadow-sm ring-1 ring-slate-100 backdrop-blur">
<Link href="/" className="flex items-center gap-2 font-semibold text-slate-900"> <Link href="/" className="flex items-center gap-2 font-semibold text-slate-900">
<span className="rounded-xl bg-brand-100 px-2 py-1 text-xs font-bold uppercase text-brand-700"> <span className="rounded-xl bg-brand-100 px-2 py-1 text-xs font-bold uppercase text-brand-700">
Push Solo
</span> </span>
<span></span> <span>solo-feed</span>
</Link> </Link>
<nav className="flex items-center gap-3 text-sm text-slate-600"> <div className="flex items-center gap-3 text-sm text-slate-600">
<nav className="flex items-center gap-3">
<Link href="/" className="hover:text-brand-600"> <Link href="/" className="hover:text-brand-600">
</Link> </Link>
@@ -28,14 +35,27 @@ export default function RootLayout({ children }: { children: ReactNode }) {
</Link> </Link>
<Link href="/admin" className="hover:text-brand-600"> <Link href="/admin" className="hover:text-brand-600">
</Link> </Link>
</nav> </nav>
{session ? (
<span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700">
{userName}
</span>
) : (
<Link
href="/login"
className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700 hover:text-brand-600"
>
</Link>
)}
</div>
</header> </header>
<main className="flex-1">{children}</main> <main className="flex-1">{children}</main>
<footer className="mt-10 flex items-center justify-between border-t border-slate-200 pt-6 text-xs text-slate-500"> <footer className="mt-10 flex items-center justify-between border-t border-slate-200 pt-6 text-xs text-slate-500">
<span>img.020417.xyz</span> <span> img.020417.xyz</span>
<span>Made for friends · {new Date().getFullYear()}</span> <span> · {new Date().getFullYear()}</span>
</footer> </footer>
</div> </div>
</body> </body>

View File

@@ -1,14 +1,14 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation"; import { useRouter } from "next/navigation";
export default function LoginForm() { export default function LoginForm() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState(""); const [error, setError] = useState("");
const router = useRouter(); const router = useRouter();
const params = useSearchParams();
async function handleSubmit(e: React.FormEvent) { async function handleSubmit(e: React.FormEvent) {
e.preventDefault(); e.preventDefault();
@@ -18,14 +18,13 @@ export default function LoginForm() {
const res = await fetch("/api/login", { const res = await fetch("/api/login", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password }) body: JSON.stringify({ username, password })
}); });
if (!res.ok) { if (!res.ok) {
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
setError(data.error || "登录失败"); setError(data.error || "登录失败");
} else { } else {
const next = params.get("next") || "/admin"; router.replace("/");
router.push(next);
router.refresh(); router.refresh();
} }
} finally { } finally {
@@ -36,14 +35,25 @@ export default function LoginForm() {
return ( return (
<form onSubmit={handleSubmit} className="space-y-4"> <form onSubmit={handleSubmit} className="space-y-4">
<label className="block space-y-1"> <label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span> <span className="text-sm font-medium text-slate-700"></span>
<input
type="text"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
placeholder="请输入用户名"
/>
</label>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span>
<input <input
type="password" type="password"
required required
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none" className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
placeholder="输入 ADMIN_PASS" placeholder="输入密码"
/> />
</label> </label>
{error ? <p className="text-sm text-red-500">{error}</p> : null} {error ? <p className="text-sm text-red-500">{error}</p> : null}
@@ -52,7 +62,7 @@ export default function LoginForm() {
disabled={loading} disabled={loading}
className="w-full rounded-full bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60" className="w-full rounded-full bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
> >
{loading ? "登录中" : "登录"} {loading ? "登录中..." : "登录"}
</button> </button>
</form> </form>
); );

View File

@@ -1,22 +1,23 @@
import LoginForm from "./login-form"; import LoginForm from "./login-form";
import { Suspense } from "react";
export const metadata = { export const metadata = {
title: "登录 - Push Info" title: "登录 - OPC Solo Feed"
}; };
export default function LoginPage() { export default function LoginPage() {
return ( return (
<div className="mx-auto max-w-md rounded-2xl bg-white/90 p-8 shadow-sm ring-1 ring-slate-100"> <div className="mx-auto max-w-md rounded-2xl bg-white/90 p-8 shadow-sm ring-1 ring-slate-100">
<h1 className="text-2xl font-semibold text-slate-900"></h1> <h1 className="text-2xl font-semibold text-slate-900"></h1>
<p className="mt-2 text-sm text-slate-600"> <p className="mt-2 text-sm text-slate-600">使</p>
/ ADMIN_PASS
</p>
<div className="mt-6"> <div className="mt-6">
<Suspense fallback={null}>
<LoginForm /> <LoginForm />
</Suspense>
</div> </div>
<p className="mt-4 text-sm text-slate-500">
{" "}
<a href="/register" className="text-brand-600 hover:text-brand-700">
</a>
</p>
</div> </div>
); );
} }

View File

@@ -5,6 +5,7 @@ import { normalizeImageUrl } from "@/lib/normalize";
import { Post } from "@/types/post"; import { Post } from "@/types/post";
import { SharePanel } from "@/components/SharePanel"; import { SharePanel } from "@/components/SharePanel";
import { getSiteUrl } from "@/lib/site"; import { getSiteUrl } from "@/lib/site";
import { DEFAULT_OPC_SIGNAL } from "@/lib/opc";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
@@ -25,7 +26,8 @@ async function fetchPost(slug: string): Promise<Post | null> {
markdown: doc.markdown ?? "", markdown: doc.markdown ?? "",
cover: doc.cover, cover: doc.cover,
tags: doc.tags ?? [], tags: doc.tags ?? [],
author: doc.author ?? "admin", signal: doc.signal ?? DEFAULT_OPC_SIGNAL,
author: doc.author ?? "佚名",
createdAt: doc.createdAt ?? new Date().toISOString(), createdAt: doc.createdAt ?? new Date().toISOString(),
updatedAt: doc.updatedAt ?? doc.createdAt ?? new Date().toISOString(), updatedAt: doc.updatedAt ?? doc.createdAt ?? new Date().toISOString(),
views: doc.views ?? 0 views: doc.views ?? 0
@@ -49,7 +51,7 @@ export default async function PostPage({ params }: Props) {
<SharePanel url={shareUrl} /> <SharePanel url={shareUrl} />
</div> </div>
<p className="mt-2 text-sm text-slate-500"> <p className="mt-2 text-sm text-slate-500">
{new Date(post.createdAt).toLocaleString("zh-CN", { hour12: false })} {post.author || "佚名"} · {new Date(post.createdAt).toLocaleString("zh-CN", { hour12: false })}
</p> </p>
{coverUrl ? ( {coverUrl ? (
<img <img

View File

@@ -35,6 +35,7 @@ async function fetchPosts(params: {
return { return {
posts: docs.map((d: any) => ({ posts: docs.map((d: any) => ({
...d, ...d,
author: d.author ?? "佚名",
_id: d._id?.toString() _id: d._id?.toString()
})), })),
total, total,
@@ -62,32 +63,50 @@ export default async function HomePage({
return qs ? `/?${qs}` : "/"; return qs ? `/?${qs}` : "/";
}; };
const clearSearchHref = (() => {
const params = new URLSearchParams();
if (tag) params.set("tag", tag);
const qs = params.toString();
return qs ? `/?${qs}` : "/";
})();
const clearTagHref = (() => {
const params = new URLSearchParams();
if (q) params.set("q", q);
const qs = params.toString();
return qs ? `/?${qs}` : "/";
})();
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="rounded-2xl bg-gradient-to-r from-brand-500 to-brand-700 p-6 text-white shadow-lg"> <div className="rounded-2xl bg-gradient-to-r from-brand-500 to-brand-700 p-6 text-white shadow-lg">
<h1 className="text-2xl font-semibold"> · </h1> <h1 className="text-2xl font-semibold">OPC </h1>
<p className="mt-2 text-sm text-white/80"> <p className="mt-2 text-sm text-white/80">
Markdown · · · MongoDB Atlas Markdown
</p> </p>
{tag ? ( {tag ? (
<div className="mt-3 inline-flex items-center gap-2 rounded-full bg-white/15 px-3 py-1 text-xs font-medium"> <div className="mt-3 inline-flex items-center gap-2 rounded-full bg-white/15 px-3 py-1 text-xs font-medium">
<span>#{tag}</span> <span> #{tag}</span>
<a <a
href="/" href={clearTagHref}
className="rounded-full bg-white/20 px-2 py-1 text-white/90 hover:bg-white/30" className="rounded-full bg-white/20 px-2 py-1 text-white/90 hover:bg-white/30"
> >
</a> </a>
</div> </div>
) : null} ) : null}
</div> </div>
<form action="/" method="get" className="flex flex-wrap items-center gap-3 rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100"> <form
action="/"
method="get"
className="flex flex-wrap items-center gap-3 rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100"
>
{tag ? <input type="hidden" name="tag" value={tag} /> : null} {tag ? <input type="hidden" name="tag" value={tag} /> : null}
<input <input
name="q" name="q"
defaultValue={q || ""} defaultValue={q || ""}
placeholder="搜索标题或正文" placeholder="搜索标题或内容"
className="min-w-[200px] flex-1 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none" className="min-w-[200px] flex-1 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
/> />
<button <button
@@ -97,10 +116,7 @@ export default async function HomePage({
</button> </button>
{q ? ( {q ? (
<a <a href={clearSearchHref} className="text-sm text-slate-500 hover:text-brand-600">
href={tag ? `/?tag=${encodeURIComponent(tag)}` : "/"}
className="text-sm text-slate-500 hover:text-brand-600"
>
</a> </a>
) : null} ) : null}
@@ -109,7 +125,7 @@ export default async function HomePage({
{posts.length === 0 ? ( {posts.length === 0 ? (
<p className="rounded-xl bg-white/70 p-4 text-sm text-slate-500 ring-1 ring-slate-100"> <p className="rounded-xl bg-white/70 p-4 text-sm text-slate-500 ring-1 ring-slate-100">
</p> </p>
) : ( ) : (
<div className="grid gap-4"> <div className="grid gap-4">

23
app/register/page.tsx Normal file
View File

@@ -0,0 +1,23 @@
import RegisterForm from "./register-form";
export const metadata = {
title: "注册 - OPC Solo Feed"
};
export default function RegisterPage() {
return (
<div className="mx-auto max-w-md rounded-2xl bg-white/90 p-8 shadow-sm ring-1 ring-slate-100">
<h1 className="text-2xl font-semibold text-slate-900"></h1>
<p className="mt-2 text-sm text-slate-600"> 24 </p>
<div className="mt-6">
<RegisterForm />
</div>
<p className="mt-4 text-sm text-slate-500">
{" "}
<a href="/login" className="text-brand-600 hover:text-brand-700">
</a>
</p>
</div>
);
}

View File

@@ -0,0 +1,88 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
export default function RegisterForm() {
const [username, setUsername] = useState("");
const [displayName, setDisplayName] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const router = useRouter();
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError("");
try {
const res = await fetch("/api/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
username,
password,
displayName: displayName.trim() || undefined
})
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError(data.error || "注册失败");
} else {
router.replace("/");
router.refresh();
}
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span>
<input
type="text"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
placeholder="2-32 个字符"
/>
</label>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span>
<input
type="text"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
placeholder="不填则使用用户名"
/>
</label>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span>
<input
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
placeholder="至少 6 位"
/>
</label>
{error ? <p className="text-sm text-red-500">{error}</p> : null}
<button
type="submit"
disabled={loading}
className="w-full rounded-full bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
>
{loading ? "注册中..." : "注册"}
</button>
</form>
);
}

View File

@@ -32,6 +32,7 @@ async function fetchTagPosts(params: {
return { return {
posts: docs.map((d: any) => ({ posts: docs.map((d: any) => ({
...d, ...d,
author: d.author ?? "佚名",
_id: d._id?.toString() _id: d._id?.toString()
})), })),
total, total,
@@ -63,8 +64,8 @@ export default async function TagDetailPage({
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="rounded-2xl bg-white/80 p-6 shadow-sm ring-1 ring-slate-100"> <div className="rounded-2xl bg-white/80 p-6 shadow-sm ring-1 ring-slate-100">
<h1 className="text-2xl font-semibold">#{tag}</h1> <h1 className="text-2xl font-semibold"> · {tag}</h1>
<p className="mt-2 text-sm text-slate-500"> {total} </p> <p className="mt-2 text-sm text-slate-500"> {total} </p>
</div> </div>
<form <form
@@ -75,7 +76,7 @@ export default async function TagDetailPage({
<input <input
name="q" name="q"
defaultValue={q || ""} defaultValue={q || ""}
placeholder="在标签搜索" placeholder="在当前标签搜索"
className="min-w-[200px] flex-1 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none" className="min-w-[200px] flex-1 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
/> />
<button <button
@@ -96,7 +97,7 @@ export default async function TagDetailPage({
{posts.length === 0 ? ( {posts.length === 0 ? (
<p className="rounded-xl bg-white/70 p-4 text-sm text-slate-500 ring-1 ring-slate-100"> <p className="rounded-xl bg-white/70 p-4 text-sm text-slate-500 ring-1 ring-slate-100">
</p> </p>
) : ( ) : (
<div className="grid gap-4"> <div className="grid gap-4">

View File

@@ -18,13 +18,13 @@ export default async function TagsPage() {
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="rounded-2xl bg-white/80 p-6 shadow-sm ring-1 ring-slate-100"> <div className="rounded-2xl bg-white/80 p-6 shadow-sm ring-1 ring-slate-100">
<h1 className="text-2xl font-semibold"></h1> <h1 className="text-2xl font-semibold"></h1>
<p className="mt-2 text-sm text-slate-500"></p> <p className="mt-2 text-sm text-slate-500"></p>
</div> </div>
{tags.length === 0 ? ( {tags.length === 0 ? (
<p className="rounded-xl bg-white/70 p-4 text-sm text-slate-500 ring-1 ring-slate-100"> <p className="rounded-xl bg-white/70 p-4 text-sm text-slate-500 ring-1 ring-slate-100">
</p> </p>
) : ( ) : (
<div className="flex flex-wrap gap-3"> <div className="flex flex-wrap gap-3">

View File

@@ -1,16 +1,23 @@
"use client"; "use client";
import Link from "next/link"; import Link from "next/link";
import { useState } from "react"; import { useMemo, useState } from "react";
import { Post } from "@/types/post"; import { Post } from "@/types/post";
type AdminPost = Post & { createdAtText?: string }; type AdminPost = Post & { createdAtText?: string };
export function AdminPostList({ initialPosts }: { initialPosts: AdminPost[] }) { export function AdminPostList({ initialPosts }: { initialPosts: AdminPost[] }) {
const [posts, setPosts] = useState<AdminPost[]>(initialPosts); const [posts, setPosts] = useState<AdminPost[]>(initialPosts);
const [tagQuery, setTagQuery] = useState("");
const visiblePosts = useMemo(() => {
const q = tagQuery.trim().toLowerCase();
if (!q) return posts;
return posts.filter((post) => post.tags?.some((tag) => tag.toLowerCase().includes(q)));
}, [posts, tagQuery]);
async function handleDelete(slug: string) { async function handleDelete(slug: string) {
if (!window.confirm("确定要删除这篇文章吗?此操作不可恢复。")) return; if (!window.confirm("确定要删除这条内容吗?此操作不可恢复。")) return;
const res = await fetch(`/api/posts/${slug}`, { method: "DELETE" }); const res = await fetch(`/api/posts/${slug}`, { method: "DELETE" });
if (!res.ok) { if (!res.ok) {
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
@@ -23,19 +30,41 @@ export function AdminPostList({ initialPosts }: { initialPosts: AdminPost[] }) {
if (posts.length === 0) { if (posts.length === 0) {
return ( return (
<div className="rounded-2xl bg-white/80 p-4 text-sm text-slate-500 shadow-sm ring-1 ring-slate-100"> <div className="rounded-2xl bg-white/80 p-4 text-sm text-slate-500 shadow-sm ring-1 ring-slate-100">
</div> </div>
); );
} }
const summary = tagQuery ? `匹配 ${visiblePosts.length} / 总 ${posts.length}` : `${posts.length}`;
return ( return (
<div className="space-y-3 rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100"> <div className="space-y-3 rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100">
<div className="flex items-center justify-between"> <div className="flex flex-wrap items-center justify-between gap-3">
<h3 className="text-lg font-semibold"></h3> <div>
<span className="text-xs text-slate-400"> {posts.length} </span> <h3 className="text-lg font-semibold"></h3>
<p className="text-xs text-slate-400">{summary}</p>
</div> </div>
<div className="flex items-center gap-2">
<input
value={tagQuery}
onChange={(e) => setTagQuery(e.target.value)}
placeholder="按标签搜索"
className="w-40 rounded-full border border-slate-200 bg-white px-3 py-1 text-xs shadow-inner focus:border-brand-500 focus:outline-none"
/>
{tagQuery ? (
<button
type="button"
onClick={() => setTagQuery("")}
className="rounded-full bg-slate-100 px-3 py-1 text-xs text-slate-600 ring-1 ring-slate-200 hover:text-brand-600"
>
</button>
) : null}
</div>
</div>
<div className="space-y-3"> <div className="space-y-3">
{posts.map((post) => ( {visiblePosts.map((post) => (
<div <div
key={post.slug} key={post.slug}
className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-100 bg-white/70 p-3" className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-100 bg-white/70 p-3"
@@ -45,19 +74,18 @@ export function AdminPostList({ initialPosts }: { initialPosts: AdminPost[] }) {
{post.title} {post.title}
</Link> </Link>
<p className="text-xs text-slate-500"> <p className="text-xs text-slate-500">
{post.createdAtText || {(post.author || "佚名") +
" · " +
(post.createdAtText ||
new Date(post.createdAt).toLocaleString("zh-CN", { new Date(post.createdAt).toLocaleString("zh-CN", {
hour12: false, hour12: false,
timeZone: "Asia/Shanghai" timeZone: "Asia/Shanghai"
})} }))}
</p> </p>
{post.tags && post.tags.length > 0 ? ( {post.tags && post.tags.length > 0 ? (
<div className="mt-2 flex flex-wrap gap-2"> <div className="mt-2 flex flex-wrap gap-2">
{post.tags.map((tag) => ( {post.tags.map((tag) => (
<span <span key={tag} className="rounded-full bg-slate-100 px-2 py-1 text-xs text-slate-600">
key={tag}
className="rounded-full bg-slate-100 px-2 py-1 text-xs text-slate-600"
>
#{tag} #{tag}
</span> </span>
))} ))}

View File

@@ -3,21 +3,37 @@
import { FormEvent, useState } from "react"; import { FormEvent, useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { normalizeImageUrl } from "@/lib/normalize"; import { normalizeImageUrl } from "@/lib/normalize";
import { MarkdownPreview } from "@/components/MarkdownPreview";
const defaultIntro = `## 新帖内容 const defaultIntro = `## solo-feed 记录模板
- 这里支持 **Markdown** - 今日目标:
- 图片请上传到 img.020417.xyz 后填入链接 - 产品/交付:
- 客户/收入:
- 增长/运营:
- 学习/复盘:
`; `;
export function CreatePostForm() { export function CreatePostForm({ availableTags = [] }: { availableTags?: string[] }) {
const [title, setTitle] = useState(""); const [title, setTitle] = useState("");
const [cover, setCover] = useState(""); const [cover, setCover] = useState("");
const [tags, setTags] = useState(""); const [tags, setTags] = useState("");
const [markdown, setMarkdown] = useState(defaultIntro); const [markdown, setMarkdown] = useState(defaultIntro);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [preview, setPreview] = useState(false);
const router = useRouter(); const router = useRouter();
const addTag = (tag: string) => {
const current = new Set(
tags
.split(",")
.map((t) => t.trim())
.filter(Boolean)
);
current.add(tag);
setTags(Array.from(current).join(", "));
};
async function handleSubmit(e: FormEvent) { async function handleSubmit(e: FormEvent) {
e.preventDefault(); e.preventDefault();
setLoading(true); setLoading(true);
@@ -56,19 +72,28 @@ export function CreatePostForm() {
return ( return (
<form onSubmit={handleSubmit} className="space-y-4 rounded-2xl bg-white/80 p-5 shadow-sm ring-1 ring-slate-100"> <form onSubmit={handleSubmit} className="space-y-4 rounded-2xl bg-white/80 p-5 shadow-sm ring-1 ring-slate-100">
<div className="flex items-center justify-between"> <div className="flex flex-wrap items-center justify-between gap-3">
<div> <div>
<h3 className="text-lg font-semibold"></h3> <h3 className="text-lg font-semibold"></h3>
<p className="text-sm text-slate-500"></p> <p className="text-sm text-slate-500"></p>
</div> </div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setPreview((prev) => !prev)}
className="rounded-full bg-slate-100 px-4 py-2 text-sm font-medium text-slate-700 ring-1 ring-slate-200 hover:text-brand-600"
>
{preview ? "编辑" : "预览"}
</button>
<button <button
type="submit" type="submit"
disabled={loading} disabled={loading}
className="rounded-full bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60" className="rounded-full bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
> >
{loading ? "发布中" : "发布"} {loading ? "发布中..." : "发布"}
</button> </button>
</div> </div>
</div>
<label className="block space-y-1"> <label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span> <span className="text-sm font-medium text-slate-700"></span>
@@ -77,12 +102,12 @@ export function CreatePostForm() {
value={title} value={title}
onChange={(e) => setTitle(e.target.value)} onChange={(e) => setTitle(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none" className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
placeholder="如:周末聚会安排" placeholder="如:本周交付进展"
/> />
</label> </label>
<label className="block space-y-1"> <label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span> <span className="text-sm font-medium text-slate-700"> URL</span>
<input <input
value={cover} value={cover}
onChange={(e) => setCover(e.target.value)} onChange={(e) => setCover(e.target.value)}
@@ -92,17 +117,32 @@ export function CreatePostForm() {
</label> </label>
<label className="block space-y-1"> <label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span> <span className="text-sm font-medium text-slate-700"></span>
<input <input
value={tags} value={tags}
onChange={(e) => setTags(e.target.value)} onChange={(e) => setTags(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none" className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
placeholder="朋友, 聚会, 通知" placeholder="产品, 交付, 复盘"
/> />
{availableTags.length > 0 ? (
<div className="mt-2 flex flex-wrap gap-2">
{availableTags.map((tag) => (
<button
key={tag}
type="button"
onClick={() => addTag(tag)}
className="rounded-full bg-slate-100 px-2 py-1 text-xs text-slate-600 ring-1 ring-slate-200 hover:text-brand-600"
>
#{tag}
</button>
))}
</div>
) : null}
</label> </label>
<label className="block space-y-1"> <div className="space-y-1">
<span className="text-sm font-medium text-slate-700">Markdown</span> <span className="text-sm font-medium text-slate-700">Markdown </span>
{!preview ? (
<textarea <textarea
required required
value={markdown} value={markdown}
@@ -110,7 +150,12 @@ export function CreatePostForm() {
rows={12} rows={12}
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none" className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
/> />
</label> ) : (
<div className="rounded-xl border border-slate-200 bg-white p-4">
<MarkdownPreview markdown={markdown || "(暂无内容)"} />
</div>
)}
</div>
</form> </form>
); );
} }

View File

@@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
import { useState } from "react"; import { useState } from "react";
import { normalizeImageUrl } from "@/lib/normalize"; import { normalizeImageUrl } from "@/lib/normalize";
import { Post } from "@/types/post"; import { Post } from "@/types/post";
import { MarkdownPreview } from "@/components/MarkdownPreview";
export function EditPostForm({ post }: { post: Post }) { export function EditPostForm({ post }: { post: Post }) {
const router = useRouter(); const router = useRouter();
@@ -12,6 +13,7 @@ export function EditPostForm({ post }: { post: Post }) {
const [tags, setTags] = useState(post.tags ? post.tags.join(", ") : ""); const [tags, setTags] = useState(post.tags ? post.tags.join(", ") : "");
const [markdown, setMarkdown] = useState(post.markdown); const [markdown, setMarkdown] = useState(post.markdown);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [preview, setPreview] = useState(false);
async function handleSave(e: React.FormEvent) { async function handleSave(e: React.FormEvent) {
e.preventDefault(); e.preventDefault();
@@ -48,7 +50,7 @@ export function EditPostForm({ post }: { post: Post }) {
} }
async function handleDelete() { async function handleDelete() {
if (!window.confirm("确定要删除这篇文章吗?此操作不可恢复。")) return; if (!window.confirm("确定要删除这条内容吗?此操作不可恢复。")) return;
const res = await fetch(`/api/posts/${post.slug}`, { method: "DELETE" }); const res = await fetch(`/api/posts/${post.slug}`, { method: "DELETE" });
if (!res.ok) { if (!res.ok) {
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
@@ -63,8 +65,8 @@ export function EditPostForm({ post }: { post: Post }) {
<form onSubmit={handleSave} className="space-y-4 rounded-2xl bg-white/80 p-5 shadow-sm ring-1 ring-slate-100"> <form onSubmit={handleSave} className="space-y-4 rounded-2xl bg-white/80 p-5 shadow-sm ring-1 ring-slate-100">
<div className="flex flex-wrap items-center justify-between gap-3"> <div className="flex flex-wrap items-center justify-between gap-3">
<div> <div>
<h3 className="text-lg font-semibold"></h3> <h3 className="text-lg font-semibold"></h3>
<p className="text-sm text-slate-500"></p> <p className="text-sm text-slate-500"></p>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <button
@@ -79,7 +81,7 @@ export function EditPostForm({ post }: { post: Post }) {
disabled={loading} disabled={loading}
className="rounded-full bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60" className="rounded-full bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
> >
{loading ? "保存中" : "保存"} {loading ? "保存中..." : "保存"}
</button> </button>
</div> </div>
</div> </div>
@@ -95,7 +97,7 @@ export function EditPostForm({ post }: { post: Post }) {
</label> </label>
<label className="block space-y-1"> <label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span> <span className="text-sm font-medium text-slate-700"> URL</span>
<input <input
value={cover} value={cover}
onChange={(e) => setCover(e.target.value)} onChange={(e) => setCover(e.target.value)}
@@ -105,17 +107,27 @@ export function EditPostForm({ post }: { post: Post }) {
</label> </label>
<label className="block space-y-1"> <label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span> <span className="text-sm font-medium text-slate-700"></span>
<input <input
value={tags} value={tags}
onChange={(e) => setTags(e.target.value)} onChange={(e) => setTags(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none" className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
placeholder="朋友, 聚会, 通知" placeholder="产品, 交付, 复盘"
/> />
</label> </label>
<label className="block space-y-1"> <div className="space-y-1">
<span className="text-sm font-medium text-slate-700">Markdown</span> <div className="flex items-center justify-between">
<span className="text-sm font-medium text-slate-700">Markdown </span>
<button
type="button"
onClick={() => setPreview((prev) => !prev)}
className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700 ring-1 ring-slate-200 hover:text-brand-600"
>
{preview ? "编辑" : "预览"}
</button>
</div>
{!preview ? (
<textarea <textarea
required required
value={markdown} value={markdown}
@@ -123,7 +135,12 @@ export function EditPostForm({ post }: { post: Post }) {
rows={12} rows={12}
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none" className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
/> />
</label> ) : (
<div className="rounded-xl border border-slate-200 bg-white p-4">
<MarkdownPreview markdown={markdown || "(暂无内容)"} />
</div>
)}
</div>
</form> </form>
); );
} }

View File

@@ -0,0 +1,12 @@
"use client";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
export function MarkdownPreview({ markdown }: { markdown: string }) {
return (
<article className="prose prose-slate max-w-none prose-a:text-brand-600 prose-img:rounded-xl">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{markdown}</ReactMarkdown>
</article>
);
}

View File

@@ -8,8 +8,9 @@ type Props = {
export function PostCard({ post }: Props) { export function PostCard({ post }: Props) {
const coverUrl = normalizeImageUrl(post.cover); const coverUrl = normalizeImageUrl(post.cover);
const author = post.author || "佚名";
return ( return (
<article className="group rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100 transition hover:-translate-y-1 hover:shadow-md"> <article className="group rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100 transition-[transform,box-shadow] duration-300 will-change-transform transform-gpu hover:shadow-lg hover:[transform:perspective(900px)_translateY(-4px)_rotateX(2deg)_rotateY(-2deg)]">
<div className="flex items-start justify-between gap-3"> <div className="flex items-start justify-between gap-3">
<div className="space-y-1"> <div className="space-y-1">
<Link <Link
@@ -19,7 +20,7 @@ export function PostCard({ post }: Props) {
{post.title} {post.title}
</Link> </Link>
<p className="text-sm text-slate-500"> <p className="text-sm text-slate-500">
{new Date(post.createdAt).toLocaleString("zh-CN", { hour12: false })} {author} · {new Date(post.createdAt).toLocaleString("zh-CN", { hour12: false })}
</p> </p>
</div> </div>
{coverUrl ? ( {coverUrl ? (

View File

@@ -93,7 +93,7 @@ export function SharePanel({ url }: { url: string }) {
loading="lazy" loading="lazy"
/> />
</div> </div>
<p className="text-xs text-slate-500"></p> <p className="text-xs text-slate-500">使</p>
</div> </div>
)} )}
</div> </div>

View File

@@ -3,6 +3,8 @@ import { NextRequest } from "next/server";
const COOKIE_NAME = "admin_session"; const COOKIE_NAME = "admin_session";
const encoder = new TextEncoder(); const encoder = new TextEncoder();
let cachedKey: CryptoKey | null = null;
let cachedSecret: string | null = null;
function getSecret() { function getSecret() {
const secret = process.env.SESSION_SECRET; const secret = process.env.SESSION_SECRET;
@@ -15,16 +17,32 @@ function getSecret() {
export type SessionPayload = { export type SessionPayload = {
role: "admin"; role: "admin";
iat: number; iat: number;
exp?: number;
uid?: string;
name?: string;
}; };
async function hmacSha256(data: string, secret: string): Promise<string> { export function getAdminName() {
const key = await crypto.subtle.importKey( return process.env.ADMIN_NAME?.trim() || "Admin";
}
async function getHmacKey(secret: string) {
if (cachedKey && cachedSecret === secret) {
return cachedKey;
}
cachedSecret = secret;
cachedKey = await crypto.subtle.importKey(
"raw", "raw",
encoder.encode(secret), encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" }, { name: "HMAC", hash: "SHA-256" },
false, false,
["sign"] ["sign"]
); );
return cachedKey;
}
async function hmacSha256(data: string, secret: string): Promise<string> {
const key = await getHmacKey(secret);
const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(data)); const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
return Buffer.from(sig).toString("base64url"); return Buffer.from(sig).toString("base64url");
} }
@@ -45,6 +63,12 @@ export async function verifySession(token?: string): Promise<SessionPayload | nu
if (check !== sig) return null; if (check !== sig) return null;
try { try {
const payload = JSON.parse(Buffer.from(base, "base64url").toString()); const payload = JSON.parse(Buffer.from(base, "base64url").toString());
if (typeof payload?.exp !== "number") {
return null;
}
if (Date.now() > payload.exp) {
return null;
}
return payload; return payload;
} catch { } catch {
return null; return null;
@@ -57,11 +81,12 @@ export async function requireAdminFromRequest(req: NextRequest): Promise<boolean
} }
export function setAdminCookie(token: string) { export function setAdminCookie(token: string) {
const isProd = process.env.NODE_ENV === "production";
cookies().set(COOKIE_NAME, token, { cookies().set(COOKIE_NAME, token, {
httpOnly: true, httpOnly: true,
sameSite: "lax", sameSite: "lax",
secure: true, secure: isProd,
maxAge: 60 * 60 * 24 * 30 maxAge: 60 * 60 * 24
}); });
} }

23
lib/opc.ts Normal file
View File

@@ -0,0 +1,23 @@
export const OPC_SIGNAL_VALUES = ["solo-feed"] as const;
export type OpcSignalValue = (typeof OPC_SIGNAL_VALUES)[number];
export const OPC_SIGNAL_LABELS: Record<OpcSignalValue, string> = {
"solo-feed": "solo-feed"
};
export const DEFAULT_OPC_SIGNAL: OpcSignalValue = "solo-feed";
const OPC_SIGNAL_SET = new Set<string>(OPC_SIGNAL_VALUES);
export function isOpcSignal(value?: string | null): value is OpcSignalValue {
if (!value) return false;
return OPC_SIGNAL_SET.has(value);
}
export function getOpcSignalLabel(value?: string | null): string {
if (value && OPC_SIGNAL_SET.has(value)) {
return OPC_SIGNAL_LABELS[value as OpcSignalValue];
}
return OPC_SIGNAL_LABELS[DEFAULT_OPC_SIGNAL];
}

20
lib/password.ts Normal file
View File

@@ -0,0 +1,20 @@
import crypto from "crypto";
const ITERATIONS = 100_000;
const KEY_LENGTH = 32;
const DIGEST = "sha256";
const SALT_BYTES = 16;
export function hashPassword(password: string, salt?: string) {
const realSalt = salt ?? crypto.randomBytes(SALT_BYTES).toString("hex");
const hash = crypto.pbkdf2Sync(password, realSalt, ITERATIONS, KEY_LENGTH, DIGEST).toString("hex");
return { salt: realSalt, hash };
}
export function verifyPassword(password: string, salt: string, hash: string) {
const next = hashPassword(password, salt).hash;
const a = Buffer.from(next, "hex");
const b = Buffer.from(hash, "hex");
if (a.length !== b.length) return false;
return crypto.timingSafeEqual(a, b);
}

11
package-lock.json generated
View File

@@ -23,6 +23,7 @@
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^20.11.28", "@types/node": "^20.11.28",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.2.63", "@types/react": "^18.2.63",
"@types/react-dom": "^18.2.19", "@types/react-dom": "^18.2.19",
"eslint": "^8.57.0", "eslint": "^8.57.0",
@@ -634,6 +635,16 @@
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/qrcode": {
"version": "1.5.6",
"resolved": "https://registry.npmmirror.com/@types/qrcode/-/qrcode-1.5.6.tgz",
"integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/react": { "node_modules/@types/react": {
"version": "18.3.28", "version": "18.3.28",
"resolved": "https://registry.npmmirror.com/@types/react/-/react-18.3.28.tgz", "resolved": "https://registry.npmmirror.com/@types/react/-/react-18.3.28.tgz",

1
test_cn.txt Normal file
View File

@@ -0,0 +1 @@
中文

View File

@@ -5,6 +5,7 @@ export type Post = {
markdown: string; markdown: string;
cover?: string; cover?: string;
tags?: string[]; tags?: string[];
signal?: string;
author: string; author: string;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;