initial webapp

This commit is contained in:
2025-07-15 18:58:21 +02:00
parent 835b73552b
commit 253111f741
32 changed files with 3885 additions and 77 deletions

108
app/api/auth/route.ts Normal file
View File

@@ -0,0 +1,108 @@
import { NextRequest, NextResponse } from 'next/server';
import { db, users } from '@/lib/db';
import { generateMemorableToken, isValidToken } from '@/lib/auth/tokens';
import { setTokenCookie, getTokenCookie } from '@/lib/auth/cookies';
import { eq } from 'drizzle-orm';
export async function GET(request: NextRequest) {
try {
// Check if user already has a token
const existingToken = await getTokenCookie();
if (existingToken) {
// Verify token exists in database
const [user] = await db.select().from(users).where(eq(users.token, existingToken));
if (user) {
return NextResponse.json({
authenticated: true,
token: existingToken,
userId: user.id,
});
}
}
return NextResponse.json({ authenticated: false });
} catch (error) {
console.error('Auth check error:', error);
return NextResponse.json({ authenticated: false }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { action, token } = body;
if (action === 'create') {
// Generate new token and create user
const newToken = generateMemorableToken();
const [newUser] = await db
.insert(users)
.values({
token: newToken,
})
.returning();
await setTokenCookie(newToken);
return NextResponse.json({
success: true,
token: newToken,
userId: newUser.id,
});
}
if (action === 'login' && token) {
// Validate token format
if (!isValidToken(token)) {
return NextResponse.json(
{
success: false,
error: 'Invalid token format',
},
{ status: 400 },
);
}
// Check if token exists
const [user] = await db.select().from(users).where(eq(users.token, token));
if (!user) {
return NextResponse.json(
{
success: false,
error: 'Token not found',
},
{ status: 404 },
);
}
await setTokenCookie(token);
return NextResponse.json({
success: true,
token,
userId: user.id,
});
}
return NextResponse.json(
{
success: false,
error: 'Invalid action',
},
{ status: 400 },
);
} catch (error) {
console.error('Auth error:', error);
return NextResponse.json(
{
success: false,
error: 'Internal server error',
},
{ status: 500 },
);
}
}

View File

@@ -0,0 +1,55 @@
import { NextRequest, NextResponse } from 'next/server';
import { db, habits, users, habitLogs } from '@/lib/db';
import { getTokenCookie } from '@/lib/auth/cookies';
import { eq, and } from 'drizzle-orm';
async function getUserFromToken() {
const token = await getTokenCookie();
if (!token) return null;
const [user] = await db.select().from(users).where(eq(users.token, token));
return user;
}
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params;
const habitId = parseInt(id);
if (isNaN(habitId)) {
return NextResponse.json({ error: 'Invalid habit ID' }, { status: 400 });
}
const user = await getUserFromToken();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Verify habit belongs to user
const [habit] = await db
.select()
.from(habits)
.where(and(eq(habits.id, habitId), eq(habits.userId, user.id)));
if (!habit) {
return NextResponse.json({ error: 'Habit not found' }, { status: 404 });
}
const body = await request.json();
const { note } = body;
// Create log entry
const [log] = await db
.insert(habitLogs)
.values({
habitId,
note,
})
.returning();
return NextResponse.json({ log });
} catch (error) {
console.error('Log habit error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}

105
app/api/habits/route.ts Normal file
View File

@@ -0,0 +1,105 @@
import { NextRequest, NextResponse } from 'next/server';
import { db, habits, users, habitLogs } from '@/lib/db';
import { getTokenCookie } from '@/lib/auth/cookies';
import { eq, and, desc, sql } from 'drizzle-orm';
async function getUserFromToken() {
const token = await getTokenCookie();
if (!token) return null;
const [user] = await db.select().from(users).where(eq(users.token, token));
return user;
}
export async function GET(request: NextRequest) {
try {
const user = await getUserFromToken();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Get all non-archived habits with their latest log and statistics
const userHabits = await db
.select({
id: habits.id,
name: habits.name,
type: habits.type,
targetFrequency: habits.targetFrequency,
color: habits.color,
icon: habits.icon,
createdAt: habits.createdAt,
// Get the latest log time
lastLoggedAt: sql<Date>`(
SELECT MAX(logged_at)
FROM ${habitLogs}
WHERE habit_id = ${habits.id}
)`.as('lastLoggedAt'),
// Get total logs count
totalLogs: sql<number>`(
SELECT COUNT(*)
FROM ${habitLogs}
WHERE habit_id = ${habits.id}
)`.as('totalLogs'),
// Get logs in last 7 days
logsLastWeek: sql<number>`(
SELECT COUNT(*)
FROM ${habitLogs}
WHERE habit_id = ${habits.id}
AND logged_at >= NOW() - INTERVAL '7 days'
)`.as('logsLastWeek'),
// Get logs in last 30 days
logsLastMonth: sql<number>`(
SELECT COUNT(*)
FROM ${habitLogs}
WHERE habit_id = ${habits.id}
AND logged_at >= NOW() - INTERVAL '30 days'
)`.as('logsLastMonth'),
})
.from(habits)
.where(and(eq(habits.userId, user.id), eq(habits.isArchived, false)))
.orderBy(desc(habits.createdAt));
return NextResponse.json({ habits: userHabits });
} catch (error) {
console.error('Get habits error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const user = await getUserFromToken();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await request.json();
const { name, type, targetFrequency, color, icon } = body;
if (!name || !type) {
return NextResponse.json(
{
error: 'Name and type are required',
},
{ status: 400 },
);
}
const [newHabit] = await db
.insert(habits)
.values({
userId: user.id,
name,
type,
targetFrequency,
color,
icon,
})
.returning();
return NextResponse.json({ habit: newHabit });
} catch (error) {
console.error('Create habit error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}