mosaicmap/app/api/login/route.ts
2025-08-11 21:26:46 +08:00

66 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { gql, GraphQLClient } from 'graphql-request';
const LOGIN_MUTATION = gql`
mutation Login($username: String!, $password: String!) {
login(input: { username: $username, password: $password }) {
token
}
}
`
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { username, password } = body;
if (!username || !password) {
return NextResponse.json(
{ error: 'Missing username or password' },
{ status: 400 }
);
}
const client = new GraphQLClient(process.env.GRAPHQL_BACKEND_URL || 'http://localhost:3050/graphql');
const response: any = await client.request(LOGIN_MUTATION, { username, password });
const jwt = response.login.token;
const res = NextResponse.json({ ok: true, token: jwt })
res.cookies.set('jwt', jwt, {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24, // 1d
})
return res
} catch (error) {
console.error('Login error:', error);
return NextResponse.json(
{
error: 'Internal server error',
message: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}
export async function GET(request: NextRequest) {
return NextResponse.json({
message: 'BFF endpoint - use POST for GraphQL queries',
usage: {
method: 'POST',
body: {
query: 'GraphQL query string',
variables: 'Query variables object (optional)',
operationName: 'Operation name (optional)'
}
}
});
}