57 lines
1.5 KiB
JavaScript
57 lines
1.5 KiB
JavaScript
/**
|
|
* @fileoverview Auth routes under /zapier/v1/auth
|
|
* @module routes/authRoutes
|
|
*/
|
|
|
|
import { Router } from 'express';
|
|
import { asyncHandler, AppError } from '../errors.js';
|
|
import { loginWithCredentials, loginWithApiKey, validateSession } from '../services/authService.js';
|
|
import { getUsageSummary } from '../store/usage.js';
|
|
import { getTenant } from '../store/tenants.js';
|
|
import { extractBearerToken } from '../lib/tokens.js';
|
|
|
|
export const authRoutes = Router();
|
|
|
|
authRoutes.post(
|
|
'/login',
|
|
asyncHandler(async (req, res) => {
|
|
const { username, password, api_key: apiKey } = req.body ?? {};
|
|
|
|
if (apiKey) {
|
|
const session = await loginWithApiKey(apiKey);
|
|
return res.json(session);
|
|
}
|
|
|
|
if (!username || !password) {
|
|
throw new AppError('username and password are required', {
|
|
status: 400,
|
|
code: 'VALIDATION_ERROR',
|
|
});
|
|
}
|
|
|
|
const session = await loginWithCredentials({ username, password });
|
|
res.json(session);
|
|
}),
|
|
);
|
|
|
|
authRoutes.get(
|
|
'/me',
|
|
asyncHandler(async (req, res) => {
|
|
const rawToken =
|
|
extractBearerToken(req.headers.authorization) ?? req.headers['x-api-key'] ?? null;
|
|
|
|
if (!rawToken) {
|
|
throw new AppError('Missing authorization token', { status: 401, code: 'UNAUTHORIZED' });
|
|
}
|
|
|
|
const validation = await validateSession(rawToken);
|
|
const tenant = getTenant(validation.tenantId);
|
|
const usage = getUsageSummary(validation.tenantId);
|
|
|
|
res.json({
|
|
...validation,
|
|
plan: tenant?.plan ?? validation.plan ?? 'free',
|
|
usage,
|
|
});
|
|
}),
|
|
);
|