CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | /**
* Auth routes — register, login, logout (web + API).
*/
import { Hono } from "hono";
import { setCookie, deleteCookie } from "hono/cookie";
import { eq } from "drizzle-orm";
import { db } from "../db";
import { users, sessions } from "../db/schema";
import {
hashPassword,
verifyPassword,
generateSessionToken,
sessionCookieOptions,
sessionExpiry,
} from "../lib/auth";
import { Layout } from "../views/layout";
import type { AuthEnv } from "../middleware/auth";
const auth = new Hono<AuthEnv>();
// --- Web UI ---
auth.get("/register", (c) => {
const error = c.req.query("error");
return c.html(
<Layout title="Register">
<div class="auth-container">
<h2>Create account</h2>
{error && <div class="auth-error">{decodeURIComponent(error)}</div>}
<form method="post" action="/register">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
id="username"
name="username"
required
pattern="^[a-zA-Z0-9_-]+$"
minLength={2}
maxLength={39}
placeholder="your-username"
autocomplete="username"
/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="email"
id="email"
name="email"
required
placeholder="you@example.com"
autocomplete="email"
/>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
id="password"
name="password"
required
minLength={8}
placeholder="Min 8 characters"
autocomplete="new-password"
/>
</div>
<button type="submit" class="btn btn-primary">
Create account
</button>
</form>
<p class="auth-switch">
Already have an account? <a href="/login">Sign in</a>
</p>
</div>
</Layout>
);
});
auth.post("/register", async (c) => {
const body = await c.req.parseBody();
const username = String(body.username || "").trim();
const email = String(body.email || "").trim();
const password = String(body.password || "");
if (!username || !email || !password) {
return c.redirect("/register?error=All+fields+are+required");
}
if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
return c.redirect(
"/register?error=Username+may+only+contain+letters%2C+numbers%2C+hyphens+and+underscores"
);
}
if (password.length < 8) {
return c.redirect("/register?error=Password+must+be+at+least+8+characters");
}
// Check existing
const [existingUser] = await db
.select()
.from(users)
.where(eq(users.username, username))
.limit(1);
if (existingUser) {
return c.redirect("/register?error=Username+already+taken");
}
const [existingEmail] = await db
.select()
.from(users)
.where(eq(users.email, email))
.limit(1);
if (existingEmail) {
return c.redirect("/register?error=Email+already+registered");
}
const passwordHash = await hashPassword(password);
const [user] = await db
.insert(users)
.values({ username, email, passwordHash })
.returning();
// Create session
const token = generateSessionToken();
await db.insert(sessions).values({
userId: user.id,
token,
expiresAt: sessionExpiry(),
});
setCookie(c, "session", token, sessionCookieOptions());
const redirect = c.req.query("redirect") || "/";
return c.redirect(redirect);
});
auth.get("/login", (c) => {
const error = c.req.query("error");
const redirect = c.req.query("redirect") || "";
return c.html(
<Layout title="Sign in">
<div class="auth-container">
<h2>Sign in</h2>
{error && <div class="auth-error">{decodeURIComponent(error)}</div>}
<form
method="post"
action={`/login${redirect ? `?redirect=${encodeURIComponent(redirect)}` : ""}`}
>
<div class="form-group">
<label for="username">Username or email</label>
<input
type="text"
id="username"
name="username"
required
placeholder="username or email"
autocomplete="username"
/>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
id="password"
name="password"
required
placeholder="Password"
autocomplete="current-password"
/>
</div>
<button type="submit" class="btn btn-primary">
Sign in
</button>
</form>
<p class="auth-switch">
New to gluecron? <a href="/register">Create an account</a>
</p>
</div>
</Layout>
);
});
auth.post("/login", async (c) => {
const body = await c.req.parseBody();
const identifier = String(body.username || "").trim();
const password = String(body.password || "");
const redirect = c.req.query("redirect") || "/";
if (!identifier || !password) {
return c.redirect("/login?error=All+fields+are+required");
}
// Find user by username or email
const isEmail = identifier.includes("@");
const [user] = await db
.select()
.from(users)
.where(
isEmail
? eq(users.email, identifier)
: eq(users.username, identifier)
)
.limit(1);
if (!user) {
return c.redirect("/login?error=Invalid+credentials");
}
const valid = await verifyPassword(password, user.passwordHash);
if (!valid) {
return c.redirect("/login?error=Invalid+credentials");
}
const token = generateSessionToken();
await db.insert(sessions).values({
userId: user.id,
token,
expiresAt: sessionExpiry(),
});
setCookie(c, "session", token, sessionCookieOptions());
return c.redirect(redirect);
});
auth.get("/logout", async (c) => {
deleteCookie(c, "session", { path: "/" });
return c.redirect("/");
});
// --- API ---
auth.post("/api/auth/register", async (c) => {
const body = await c.req.json<{
username: string;
email: string;
password: string;
}>();
if (!body.username || !body.email || !body.password) {
return c.json({ error: "username, email, and password are required" }, 400);
}
if (!/^[a-zA-Z0-9_-]+$/.test(body.username)) {
return c.json({ error: "Invalid username" }, 400);
}
if (body.password.length < 8) {
return c.json({ error: "Password must be at least 8 characters" }, 400);
}
const [existing] = await db
.select()
.from(users)
.where(eq(users.username, body.username))
.limit(1);
if (existing) {
return c.json({ error: "Username already taken" }, 409);
}
const passwordHash = await hashPassword(body.password);
const [user] = await db
.insert(users)
.values({
username: body.username,
email: body.email,
passwordHash,
})
.returning();
const token = generateSessionToken();
await db.insert(sessions).values({
userId: user.id,
token,
expiresAt: sessionExpiry(),
});
return c.json(
{
user: { id: user.id, username: user.username, email: user.email },
token,
},
201
);
});
auth.post("/api/auth/login", async (c) => {
const body = await c.req.json<{ username: string; password: string }>();
if (!body.username || !body.password) {
return c.json({ error: "username and password are required" }, 400);
}
const isEmail = body.username.includes("@");
const [user] = await db
.select()
.from(users)
.where(
isEmail
? eq(users.email, body.username)
: eq(users.username, body.username)
)
.limit(1);
if (!user) return c.json({ error: "Invalid credentials" }, 401);
const valid = await verifyPassword(body.password, user.passwordHash);
if (!valid) return c.json({ error: "Invalid credentials" }, 401);
const token = generateSessionToken();
await db.insert(sessions).values({
userId: user.id,
token,
expiresAt: sessionExpiry(),
});
return c.json({
user: { id: user.id, username: user.username, email: user.email },
token,
});
});
export default auth;
|