Split logic for findSession.
parent
e487da72c3
commit
f2fa514a31
|
@ -1,4 +1,4 @@
|
||||||
import { User, Website, Team } from '@prisma/client';
|
import { User, Website, Team, TeamUser } from '@prisma/client';
|
||||||
import redis from '@umami/redis-client';
|
import redis from '@umami/redis-client';
|
||||||
import { lightFormat, startOfMonth } from 'date-fns';
|
import { lightFormat, startOfMonth } from 'date-fns';
|
||||||
import { getAllWebsitesByUser, getSession, getUser, getViewTotals, getWebsite } from '../queries';
|
import { getAllWebsitesByUser, getSession, getUser, getViewTotals, getWebsite } from '../queries';
|
||||||
|
@ -35,10 +35,10 @@ async function deleteObject(key, soft = false) {
|
||||||
|
|
||||||
async function fetchWebsite(id): Promise<
|
async function fetchWebsite(id): Promise<
|
||||||
Website & {
|
Website & {
|
||||||
team?: Team;
|
team?: Team & { teamUsers: TeamUser[] };
|
||||||
}
|
}
|
||||||
> {
|
> {
|
||||||
return fetchObject(`website:${id}`, () => getWebsite({ id }));
|
return fetchObject(`website:${id}`, () => getWebsite({ id }, true));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function storeWebsite(data) {
|
async function storeWebsite(data) {
|
||||||
|
|
|
@ -1,20 +1,57 @@
|
||||||
import { createMiddleware, unauthorized, badRequest, parseSecureToken } from 'next-basics';
|
|
||||||
import debug from 'debug';
|
|
||||||
import cors from 'cors';
|
|
||||||
import { validate } from 'uuid';
|
|
||||||
import redis from '@umami/redis-client';
|
import redis from '@umami/redis-client';
|
||||||
import { findSession } from 'lib/session';
|
import cors from 'cors';
|
||||||
|
import debug from 'debug';
|
||||||
import { getAuthToken, parseShareToken } from 'lib/auth';
|
import { getAuthToken, parseShareToken } from 'lib/auth';
|
||||||
import { secret } from 'lib/crypto';
|
|
||||||
import { ROLES } from 'lib/constants';
|
import { ROLES } from 'lib/constants';
|
||||||
|
import { secret } from 'lib/crypto';
|
||||||
|
import { isOverApiLimit, findSession, findWebsite, useSessionCache } from 'lib/session';
|
||||||
|
import {
|
||||||
|
badRequest,
|
||||||
|
createMiddleware,
|
||||||
|
parseSecureToken,
|
||||||
|
tooManyRequest,
|
||||||
|
unauthorized,
|
||||||
|
} from 'next-basics';
|
||||||
|
import { NextApiRequestCollect } from 'pages/api/collect';
|
||||||
|
import { validate } from 'uuid';
|
||||||
import { getUser } from '../queries';
|
import { getUser } from '../queries';
|
||||||
|
import { getJsonBody } from './detect';
|
||||||
|
|
||||||
const log = debug('umami:middleware');
|
const log = debug('umami:middleware');
|
||||||
|
|
||||||
export const useCors = createMiddleware(cors());
|
export const useCors = createMiddleware(cors());
|
||||||
|
|
||||||
export const useSession = createMiddleware(async (req: any, res, next) => {
|
export const useSession = createMiddleware(async (req: NextApiRequestCollect, res, next) => {
|
||||||
const session = await findSession(req);
|
// Verify payload
|
||||||
|
const { payload } = getJsonBody(req);
|
||||||
|
|
||||||
|
const { website: websiteId } = payload;
|
||||||
|
|
||||||
|
if (!payload) {
|
||||||
|
log('useSession: No payload');
|
||||||
|
return badRequest(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get session from cache
|
||||||
|
let session = await useSessionCache(req);
|
||||||
|
|
||||||
|
// Get or create session
|
||||||
|
if (!session) {
|
||||||
|
const website = await findWebsite(websiteId);
|
||||||
|
|
||||||
|
if (!website) {
|
||||||
|
log('useSession: Website not found');
|
||||||
|
return badRequest(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.env.ENABLE_COLLECT_LIMIT) {
|
||||||
|
if (isOverApiLimit(website)) {
|
||||||
|
return tooManyRequest(res, 'Collect currently exceeds monthly limit of 10000.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
session = await findSession(req, payload);
|
||||||
|
}
|
||||||
|
|
||||||
if (!session) {
|
if (!session) {
|
||||||
log('useSession: Session not found');
|
log('useSession: Session not found');
|
||||||
|
|
147
lib/session.ts
147
lib/session.ts
|
@ -2,84 +2,41 @@ import { Session, Team, Website } from '@prisma/client';
|
||||||
import cache from 'lib/cache';
|
import cache from 'lib/cache';
|
||||||
import clickhouse from 'lib/clickhouse';
|
import clickhouse from 'lib/clickhouse';
|
||||||
import { secret, uuid } from 'lib/crypto';
|
import { secret, uuid } from 'lib/crypto';
|
||||||
import { getClientInfo, getJsonBody } from 'lib/detect';
|
import { getClientInfo } from 'lib/detect';
|
||||||
import { parseToken } from 'next-basics';
|
import { parseToken } from 'next-basics';
|
||||||
import { createSession, getSession, getWebsite } from 'queries';
|
import { createSession, getSession, getWebsite } from 'queries';
|
||||||
import { validate } from 'uuid';
|
|
||||||
|
|
||||||
export async function findSession(req): Promise<{
|
export async function findSession(
|
||||||
error?: {
|
req,
|
||||||
status: number;
|
payload,
|
||||||
message: string;
|
): Promise<{
|
||||||
};
|
id: string;
|
||||||
session?: {
|
websiteId: string;
|
||||||
id: string;
|
hostname: string;
|
||||||
websiteId: string;
|
browser: string;
|
||||||
hostname: string;
|
os: string;
|
||||||
browser: string;
|
device: string;
|
||||||
os: string;
|
screen: string;
|
||||||
device: string;
|
language: string;
|
||||||
screen: string;
|
country: string;
|
||||||
language: string;
|
|
||||||
country: string;
|
|
||||||
};
|
|
||||||
website?: Website & { team?: Team };
|
|
||||||
}> {
|
}> {
|
||||||
const { payload } = getJsonBody(req);
|
|
||||||
|
|
||||||
if (!payload) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify payload
|
|
||||||
const { website: websiteId, hostname, screen, language } = payload;
|
const { website: websiteId, hostname, screen, language } = payload;
|
||||||
|
|
||||||
// Find website
|
|
||||||
let website: Website & { team?: Team } = null;
|
|
||||||
|
|
||||||
if (cache.enabled) {
|
|
||||||
website = await cache.fetchWebsite(websiteId);
|
|
||||||
} else {
|
|
||||||
website = await getWebsite({ id: websiteId });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!website || website.deletedAt) {
|
|
||||||
throw new Error(`Website not found: ${websiteId}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if cache token is passed
|
|
||||||
const cacheToken = req.headers['x-umami-cache'];
|
|
||||||
|
|
||||||
if (cacheToken) {
|
|
||||||
const result = await parseToken(cacheToken, secret());
|
|
||||||
|
|
||||||
if (result) {
|
|
||||||
return { session: result, website };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!validate(websiteId)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
|
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
|
||||||
const sessionId = uuid(websiteId, hostname, ip, userAgent);
|
const sessionId = uuid(websiteId, hostname, ip, userAgent);
|
||||||
|
|
||||||
// Clickhouse does not require session lookup
|
// Clickhouse does not require session lookup
|
||||||
if (clickhouse.enabled) {
|
if (clickhouse.enabled) {
|
||||||
return {
|
return {
|
||||||
session: {
|
id: sessionId,
|
||||||
id: sessionId,
|
websiteId,
|
||||||
websiteId,
|
hostname,
|
||||||
hostname,
|
browser,
|
||||||
browser,
|
os,
|
||||||
os,
|
device,
|
||||||
device,
|
screen,
|
||||||
screen,
|
language,
|
||||||
language,
|
country,
|
||||||
country,
|
|
||||||
},
|
|
||||||
website,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -113,5 +70,61 @@ export async function findSession(req): Promise<{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { session, website };
|
return session;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function useSessionCache(req: any): Promise<{
|
||||||
|
id: string;
|
||||||
|
websiteId: string;
|
||||||
|
hostname: string;
|
||||||
|
browser: string;
|
||||||
|
os: string;
|
||||||
|
device: string;
|
||||||
|
screen: string;
|
||||||
|
language: string;
|
||||||
|
country: string;
|
||||||
|
}> {
|
||||||
|
// Check if cache token is passed
|
||||||
|
const cacheToken = req.headers['x-umami-cache'];
|
||||||
|
|
||||||
|
if (cacheToken) {
|
||||||
|
const result = await parseToken(cacheToken, secret());
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function findWebsite(websiteId: string) {
|
||||||
|
let website: Website & { team?: Team } = null;
|
||||||
|
|
||||||
|
if (cache.enabled) {
|
||||||
|
website = await cache.fetchWebsite(websiteId);
|
||||||
|
} else {
|
||||||
|
website = await getWebsite({ id: websiteId }, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!website || website.deletedAt) {
|
||||||
|
throw new Error(`Website not found: ${websiteId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return website;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function isOverApiLimit(website) {
|
||||||
|
const userId = website.userId ? website.userId : website.team.teamu.userId;
|
||||||
|
|
||||||
|
const limit = await cache.fetchCollectLimit(userId);
|
||||||
|
|
||||||
|
// To-do: Need to implement logic to find user-specific limit. Defaulted to 10k.
|
||||||
|
if (limit > 10000) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
await cache.incrementCollectLimit(userId);
|
||||||
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,40 +1,24 @@
|
||||||
const { Resolver } = require('dns').promises;
|
const { Resolver } = require('dns').promises;
|
||||||
import isbot from 'isbot';
|
|
||||||
import ipaddr from 'ipaddr.js';
|
import ipaddr from 'ipaddr.js';
|
||||||
import {
|
import isbot from 'isbot';
|
||||||
createToken,
|
|
||||||
unauthorized,
|
|
||||||
send,
|
|
||||||
badRequest,
|
|
||||||
forbidden,
|
|
||||||
tooManyRequest,
|
|
||||||
} from 'next-basics';
|
|
||||||
import { savePageView, saveEvent } from 'queries';
|
|
||||||
import { useCors, useSession } from 'lib/middleware';
|
|
||||||
import { getJsonBody, getIpAddress } from 'lib/detect';
|
|
||||||
import { secret } from 'lib/crypto';
|
import { secret } from 'lib/crypto';
|
||||||
|
import { getIpAddress, getJsonBody } from 'lib/detect';
|
||||||
|
import { useCors, useSession } from 'lib/middleware';
|
||||||
import { NextApiRequest, NextApiResponse } from 'next';
|
import { NextApiRequest, NextApiResponse } from 'next';
|
||||||
import cache from 'lib/cache';
|
import { badRequest, createToken, forbidden, send, unauthorized } from 'next-basics';
|
||||||
import { Team, Website } from '@prisma/client';
|
import { saveEvent, savePageView } from 'queries';
|
||||||
|
|
||||||
export interface NextApiRequestCollect extends NextApiRequest {
|
export interface NextApiRequestCollect extends NextApiRequest {
|
||||||
session: {
|
session?: {
|
||||||
error?: {
|
id: string;
|
||||||
status: number;
|
websiteId: string;
|
||||||
message: string;
|
hostname: string;
|
||||||
};
|
browser: string;
|
||||||
session?: {
|
os: string;
|
||||||
id: string;
|
device: string;
|
||||||
websiteId: string;
|
screen: string;
|
||||||
hostname: string;
|
language: string;
|
||||||
browser: string;
|
country: string;
|
||||||
os: string;
|
|
||||||
device: string;
|
|
||||||
screen: string;
|
|
||||||
language: string;
|
|
||||||
country: string;
|
|
||||||
};
|
|
||||||
website?: Website & { team?: Team };
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -104,21 +88,7 @@ export default async (req: NextApiRequestCollect, res: NextApiResponse) => {
|
||||||
|
|
||||||
await useSession(req, res);
|
await useSession(req, res);
|
||||||
|
|
||||||
const { session, website } = req.session;
|
const session = req.session;
|
||||||
|
|
||||||
// Check collection limit
|
|
||||||
if (process.env.ENABLE_COLLECT_LIMIT) {
|
|
||||||
const userId = website.userId ? website.userId : website.team.userId;
|
|
||||||
|
|
||||||
const limit = await cache.fetchCollectLimit(userId);
|
|
||||||
|
|
||||||
// To-do: Need to implement logic to find user-specific limit. Defaulted to 10k.
|
|
||||||
if (limit > 10000) {
|
|
||||||
return tooManyRequest(res, 'Collect currently exceeds monthly limit of 10000.');
|
|
||||||
}
|
|
||||||
|
|
||||||
await cache.incrementCollectLimit(userId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (process.env.REMOVE_TRAILING_SLASH) {
|
if (process.env.REMOVE_TRAILING_SLASH) {
|
||||||
url = url.replace(/\/$/, '');
|
url = url.replace(/\/$/, '');
|
||||||
|
|
|
@ -1,18 +1,29 @@
|
||||||
import { Prisma, Team, Website } from '@prisma/client';
|
import { Prisma, Team, TeamUser, Website } from '@prisma/client';
|
||||||
import cache from 'lib/cache';
|
import cache from 'lib/cache';
|
||||||
import prisma from 'lib/prisma';
|
import prisma from 'lib/prisma';
|
||||||
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
|
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
|
||||||
|
|
||||||
export async function getWebsite(where: Prisma.WebsiteWhereUniqueInput): Promise<
|
export async function getWebsite(
|
||||||
|
where: Prisma.WebsiteWhereUniqueInput,
|
||||||
|
includeTeamData = false,
|
||||||
|
): Promise<
|
||||||
Website & {
|
Website & {
|
||||||
team?: Team;
|
team?: Team & { teamUsers: TeamUser[] };
|
||||||
}
|
}
|
||||||
> {
|
> {
|
||||||
|
prisma.client.team.findMany();
|
||||||
|
|
||||||
return prisma.client.website.findUnique({
|
return prisma.client.website.findUnique({
|
||||||
where,
|
where,
|
||||||
include: {
|
include: includeTeamData
|
||||||
team: true,
|
? {
|
||||||
},
|
team: {
|
||||||
|
include: {
|
||||||
|
teamUsers: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue