mirror of
https://github.com/umami-software/umami.git
synced 2026-02-06 05:37:20 +01:00
Merge branch 'dev' into os-names
This commit is contained in:
commit
37e28bbf74
472 changed files with 5460 additions and 5026 deletions
|
|
@ -1,13 +1,13 @@
|
|||
import { Report } from '@prisma/client';
|
||||
import debug from 'debug';
|
||||
import redis from '@umami/redis-client';
|
||||
import { PERMISSIONS, ROLE_PERMISSIONS, SHARE_TOKEN_HEADER } from 'lib/constants';
|
||||
import debug from 'debug';
|
||||
import { PERMISSIONS, ROLE_PERMISSIONS, SHARE_TOKEN_HEADER, ROLES } from 'lib/constants';
|
||||
import { secret } from 'lib/crypto';
|
||||
import { NextApiRequest } from 'next';
|
||||
import { createSecureToken, ensureArray, getRandomChars, parseToken } from 'next-basics';
|
||||
import { findTeamWebsiteByUserId, getTeamUser, getTeamWebsite } from 'queries';
|
||||
import { getTeamUser } from 'queries';
|
||||
import { loadWebsite } from './load';
|
||||
import { Auth } from './types';
|
||||
import { NextApiRequest } from 'next';
|
||||
|
||||
const log = debug('umami:auth');
|
||||
const cloudMode = process.env.CLOUD_MODE;
|
||||
|
|
@ -52,11 +52,17 @@ export async function canViewWebsite({ user, shareToken }: Auth, websiteId: stri
|
|||
|
||||
const website = await loadWebsite(websiteId);
|
||||
|
||||
if (user.id === website?.userId) {
|
||||
return true;
|
||||
if (website.userId) {
|
||||
return user.id === website.userId;
|
||||
}
|
||||
|
||||
return !!(await findTeamWebsiteByUserId(websiteId, user.id));
|
||||
if (website.teamId) {
|
||||
const teamUser = await getTeamUser(website.teamId, user.id);
|
||||
|
||||
return !!teamUser;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function canViewAllWebsites({ user }: Auth) {
|
||||
|
|
@ -82,7 +88,41 @@ export async function canUpdateWebsite({ user }: Auth, websiteId: string) {
|
|||
|
||||
const website = await loadWebsite(websiteId);
|
||||
|
||||
return user.id === website?.userId;
|
||||
if (website.userId) {
|
||||
return user.id === website.userId;
|
||||
}
|
||||
|
||||
if (website.teamId) {
|
||||
const teamUser = await getTeamUser(website.teamId, user.id);
|
||||
|
||||
return teamUser && hasPermission(teamUser.role, PERMISSIONS.websiteUpdate);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function canTransferWebsiteToUser({ user }: Auth, websiteId: string, userId: string) {
|
||||
const website = await loadWebsite(websiteId);
|
||||
|
||||
if (website.teamId && user.id === userId) {
|
||||
const teamUser = await getTeamUser(website.teamId, userId);
|
||||
|
||||
return teamUser?.role === ROLES.teamOwner;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function canTransferWebsiteToTeam({ user }: Auth, websiteId: string, teamId: string) {
|
||||
const website = await loadWebsite(websiteId);
|
||||
|
||||
if (website.userId === user.id) {
|
||||
const teamUser = await getTeamUser(teamId, user.id);
|
||||
|
||||
return teamUser?.role === ROLES.teamOwner;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function canDeleteWebsite({ user }: Auth, websiteId: string) {
|
||||
|
|
@ -92,7 +132,17 @@ export async function canDeleteWebsite({ user }: Auth, websiteId: string) {
|
|||
|
||||
const website = await loadWebsite(websiteId);
|
||||
|
||||
return user.id === website?.userId;
|
||||
if (website.userId) {
|
||||
return user.id === website.userId;
|
||||
}
|
||||
|
||||
if (website.teamId) {
|
||||
const teamUser = await getTeamUser(website.teamId, user.id);
|
||||
|
||||
return teamUser && hasPermission(teamUser.role, PERMISSIONS.websiteDelete);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function canViewReport(auth: Auth, report: Report) {
|
||||
|
|
@ -139,16 +189,28 @@ export async function canViewTeam({ user }: Auth, teamId: string) {
|
|||
return getTeamUser(teamId, user.id);
|
||||
}
|
||||
|
||||
export async function canUpdateTeam({ user }: Auth, teamId: string) {
|
||||
export async function canUpdateTeam({ user, grant }: Auth, teamId: string) {
|
||||
if (user.isAdmin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (cloudMode) {
|
||||
return !!grant?.find(a => a === PERMISSIONS.teamUpdate);
|
||||
}
|
||||
|
||||
const teamUser = await getTeamUser(teamId, user.id);
|
||||
|
||||
return teamUser && hasPermission(teamUser.role, PERMISSIONS.teamUpdate);
|
||||
}
|
||||
|
||||
export async function canAddUserToTeam({ user, grant }: Auth) {
|
||||
if (cloudMode) {
|
||||
return !!grant?.find(a => a === PERMISSIONS.teamUpdate);
|
||||
}
|
||||
|
||||
return user.isAdmin;
|
||||
}
|
||||
|
||||
export async function canDeleteTeam({ user }: Auth, teamId: string) {
|
||||
if (user.isAdmin) {
|
||||
return true;
|
||||
|
|
@ -173,24 +235,14 @@ export async function canDeleteTeamUser({ user }: Auth, teamId: string, removeUs
|
|||
return teamUser && hasPermission(teamUser.role, PERMISSIONS.teamUpdate);
|
||||
}
|
||||
|
||||
export async function canDeleteTeamWebsite({ user }: Auth, teamId: string, websiteId: string) {
|
||||
export async function canCreateTeamWebsite({ user }: Auth, teamId: string) {
|
||||
if (user.isAdmin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const teamWebsite = await getTeamWebsite(teamId, websiteId);
|
||||
const teamUser = await getTeamUser(teamId, user.id);
|
||||
|
||||
if (teamWebsite?.website?.userId === user.id) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (teamWebsite) {
|
||||
const teamUser = await getTeamUser(teamWebsite.teamId, user.id);
|
||||
|
||||
return hasPermission(teamUser.role, PERMISSIONS.teamUpdate);
|
||||
}
|
||||
|
||||
return false;
|
||||
return teamUser && hasPermission(teamUser.role, PERMISSIONS.websiteCreate);
|
||||
}
|
||||
|
||||
export async function canCreateUser({ user }: Auth) {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
import { User, Website } from '@prisma/client';
|
||||
import redis from '@umami/redis-client';
|
||||
import { getSession, getUserById, getWebsiteById } from '../queries';
|
||||
import { getSession, getUser, getWebsite } from '../queries';
|
||||
|
||||
async function fetchWebsite(id): Promise<Website> {
|
||||
return redis.client.getCache(`website:${id}`, () => getWebsiteById(id), 86400);
|
||||
async function fetchWebsite(websiteId: string): Promise<Website> {
|
||||
return redis.client.getCache(`website:${websiteId}`, () => getWebsite(websiteId), 86400);
|
||||
}
|
||||
|
||||
async function storeWebsite(data) {
|
||||
async function storeWebsite(data: { id: any }) {
|
||||
const { id } = data;
|
||||
const key = `website:${id}`;
|
||||
|
||||
|
|
@ -21,11 +21,7 @@ async function deleteWebsite(id) {
|
|||
}
|
||||
|
||||
async function fetchUser(id): Promise<User> {
|
||||
return redis.client.getCache(
|
||||
`user:${id}`,
|
||||
() => getUserById(id, { includePassword: true }),
|
||||
86400,
|
||||
);
|
||||
return redis.client.getCache(`user:${id}`, () => getUser(id, { includePassword: true }), 86400);
|
||||
}
|
||||
|
||||
async function storeUser(data) {
|
||||
|
|
|
|||
|
|
@ -46,22 +46,22 @@ function getClient() {
|
|||
return client;
|
||||
}
|
||||
|
||||
function getDateStringQuery(data, unit) {
|
||||
function getDateStringQuery(data: any, unit: string | number) {
|
||||
return `formatDateTime(${data}, '${CLICKHOUSE_DATE_FORMATS[unit]}')`;
|
||||
}
|
||||
|
||||
function getDateQuery(field, unit, timezone?) {
|
||||
function getDateQuery(field: string, unit: string, timezone?: string) {
|
||||
if (timezone) {
|
||||
return `date_trunc('${unit}', ${field}, '${timezone}')`;
|
||||
}
|
||||
return `date_trunc('${unit}', ${field})`;
|
||||
}
|
||||
|
||||
function getDateFormat(date) {
|
||||
function getDateFormat(date: Date) {
|
||||
return `'${dateFormat(date, 'UTC:yyyy-mm-dd HH:MM:ss')}'`;
|
||||
}
|
||||
|
||||
function mapFilter(column, operator, name, type = 'String') {
|
||||
function mapFilter(column: string, operator: string, name: string, type = 'String') {
|
||||
switch (operator) {
|
||||
case OPERATORS.equals:
|
||||
return `${column} = {${name}:${type}}`;
|
||||
|
|
@ -110,7 +110,7 @@ async function parseFilters(websiteId: string, filters: QueryFilters = {}, optio
|
|||
params: {
|
||||
...normalizeFilters(filters),
|
||||
websiteId,
|
||||
startDate: maxDate(filters.startDate, new Date(website.resetAt)),
|
||||
startDate: maxDate(filters.startDate, new Date(website?.resetAt)),
|
||||
websiteDomain: website.domain,
|
||||
},
|
||||
};
|
||||
|
|
@ -130,12 +130,10 @@ async function rawQuery(query: string, params: Record<string, unknown> = {}): Pr
|
|||
format: 'JSONEachRow',
|
||||
});
|
||||
|
||||
const data = await resultSet.json();
|
||||
|
||||
return data;
|
||||
return resultSet.json();
|
||||
}
|
||||
|
||||
async function findUnique(data) {
|
||||
async function findUnique(data: any[]) {
|
||||
if (data.length > 1) {
|
||||
throw `${data.length} records found when expecting 1.`;
|
||||
}
|
||||
|
|
@ -143,7 +141,7 @@ async function findUnique(data) {
|
|||
return findFirst(data);
|
||||
}
|
||||
|
||||
async function findFirst(data) {
|
||||
async function findFirst(data: any[]) {
|
||||
return data[0] ?? null;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -125,6 +125,7 @@ export const ROLES = {
|
|||
viewOnly: 'view-only',
|
||||
teamOwner: 'team-owner',
|
||||
teamMember: 'team-member',
|
||||
teamViewOnly: 'team-view-only',
|
||||
} as const;
|
||||
|
||||
export const PERMISSIONS = {
|
||||
|
|
@ -146,8 +147,19 @@ export const ROLE_PERMISSIONS = {
|
|||
PERMISSIONS.teamCreate,
|
||||
],
|
||||
[ROLES.viewOnly]: [],
|
||||
[ROLES.teamOwner]: [PERMISSIONS.teamUpdate, PERMISSIONS.teamDelete],
|
||||
[ROLES.teamMember]: [],
|
||||
[ROLES.teamOwner]: [
|
||||
PERMISSIONS.teamUpdate,
|
||||
PERMISSIONS.teamDelete,
|
||||
PERMISSIONS.websiteCreate,
|
||||
PERMISSIONS.websiteUpdate,
|
||||
PERMISSIONS.websiteDelete,
|
||||
],
|
||||
[ROLES.teamMember]: [
|
||||
PERMISSIONS.websiteCreate,
|
||||
PERMISSIONS.websiteUpdate,
|
||||
PERMISSIONS.websiteDelete,
|
||||
],
|
||||
[ROLES.teamViewOnly]: [],
|
||||
} as const;
|
||||
|
||||
export const THEME_COLORS = {
|
||||
|
|
@ -203,6 +215,7 @@ export const UUID_REGEX =
|
|||
/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/;
|
||||
export const HOSTNAME_REGEX =
|
||||
/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/;
|
||||
export const IP_REGEX = /^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}$/;
|
||||
|
||||
export const DESKTOP_SCREEN_WIDTH = 1920;
|
||||
export const LAPTOP_SCREEN_WIDTH = 1024;
|
||||
|
|
|
|||
215
src/lib/date.ts
215
src/lib/date.ts
|
|
@ -5,6 +5,7 @@ import {
|
|||
addDays,
|
||||
addMonths,
|
||||
addYears,
|
||||
subMinutes,
|
||||
subHours,
|
||||
subDays,
|
||||
subMonths,
|
||||
|
|
@ -23,13 +24,16 @@ import {
|
|||
differenceInMinutes,
|
||||
differenceInHours,
|
||||
differenceInCalendarDays,
|
||||
differenceInCalendarWeeks,
|
||||
differenceInCalendarMonths,
|
||||
differenceInCalendarYears,
|
||||
format,
|
||||
max,
|
||||
min,
|
||||
isDate,
|
||||
addWeeks,
|
||||
subWeeks,
|
||||
endOfMinute,
|
||||
} from 'date-fns';
|
||||
import { getDateLocale } from 'lib/lang';
|
||||
import { DateRange } from 'lib/types';
|
||||
|
|
@ -43,20 +47,75 @@ export const TIME_UNIT = {
|
|||
year: 'year',
|
||||
};
|
||||
|
||||
const dateFuncs = {
|
||||
minute: [differenceInMinutes, addMinutes, startOfMinute],
|
||||
hour: [differenceInHours, addHours, startOfHour],
|
||||
day: [differenceInCalendarDays, addDays, startOfDay],
|
||||
month: [differenceInCalendarMonths, addMonths, startOfMonth],
|
||||
year: [differenceInCalendarYears, addYears, startOfYear],
|
||||
export const CUSTOM_FORMATS = {
|
||||
'en-US': {
|
||||
p: 'ha',
|
||||
pp: 'h:mm:ss',
|
||||
},
|
||||
'fr-FR': {
|
||||
'M/d': 'd/M',
|
||||
'MMM d': 'd MMM',
|
||||
'EEE M/d': 'EEE d/M',
|
||||
},
|
||||
};
|
||||
|
||||
const DATE_FUNCTIONS = {
|
||||
minute: {
|
||||
diff: differenceInMinutes,
|
||||
add: addMinutes,
|
||||
sub: subMinutes,
|
||||
start: startOfMinute,
|
||||
end: endOfMinute,
|
||||
},
|
||||
hour: {
|
||||
diff: differenceInHours,
|
||||
add: addHours,
|
||||
sub: subHours,
|
||||
start: startOfHour,
|
||||
end: endOfHour,
|
||||
},
|
||||
day: {
|
||||
diff: differenceInCalendarDays,
|
||||
add: addDays,
|
||||
sub: subDays,
|
||||
start: startOfDay,
|
||||
end: endOfDay,
|
||||
},
|
||||
week: {
|
||||
diff: differenceInCalendarWeeks,
|
||||
add: addWeeks,
|
||||
sub: subWeeks,
|
||||
start: startOfWeek,
|
||||
end: endOfWeek,
|
||||
},
|
||||
month: {
|
||||
diff: differenceInCalendarMonths,
|
||||
add: addMonths,
|
||||
sub: subMonths,
|
||||
start: startOfMonth,
|
||||
end: endOfMonth,
|
||||
},
|
||||
year: {
|
||||
diff: differenceInCalendarYears,
|
||||
add: addYears,
|
||||
sub: subYears,
|
||||
start: startOfYear,
|
||||
end: endOfYear,
|
||||
},
|
||||
};
|
||||
|
||||
export function getTimezone() {
|
||||
return moment.tz.guess();
|
||||
}
|
||||
|
||||
export function getLocalTime(t: string | number | Date) {
|
||||
return addMinutes(new Date(t), new Date().getTimezoneOffset());
|
||||
export function parseDateValue(value: string) {
|
||||
const match = value.match?.(/^(?<num>[0-9-]+)(?<unit>hour|day|week|month|year)$/);
|
||||
|
||||
if (!match) return null;
|
||||
|
||||
const { num, unit } = match.groups;
|
||||
|
||||
return { num: +num, unit };
|
||||
}
|
||||
|
||||
export function parseDateRange(value: string | object, locale = 'en-US'): DateRange {
|
||||
|
|
@ -81,91 +140,95 @@ export function parseDateRange(value: string | object, locale = 'en-US'): DateRa
|
|||
return {
|
||||
startDate,
|
||||
endDate,
|
||||
unit: getMinimumUnit(startDate, endDate),
|
||||
value,
|
||||
...parseDateValue(value),
|
||||
offset: 0,
|
||||
unit: getMinimumUnit(startDate, endDate),
|
||||
};
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const dateLocale = getDateLocale(locale);
|
||||
const { num, unit } = parseDateValue(value);
|
||||
|
||||
const match = value?.match?.(/^(?<num>[0-9-]+)(?<unit>hour|day|week|month|year)$/);
|
||||
|
||||
if (!match) return null;
|
||||
|
||||
const { num, unit } = match.groups;
|
||||
const selectedUnit = { num: +num, unit };
|
||||
|
||||
if (+num === 1) {
|
||||
if (num === 1) {
|
||||
switch (unit) {
|
||||
case 'day':
|
||||
return {
|
||||
startDate: startOfDay(now),
|
||||
endDate: endOfDay(now),
|
||||
unit: 'hour',
|
||||
num: +num,
|
||||
offset: 0,
|
||||
value,
|
||||
selectedUnit,
|
||||
};
|
||||
case 'week':
|
||||
return {
|
||||
startDate: startOfWeek(now, { locale: dateLocale }),
|
||||
endDate: endOfWeek(now, { locale: dateLocale }),
|
||||
unit: 'day',
|
||||
num: +num,
|
||||
offset: 0,
|
||||
value,
|
||||
selectedUnit,
|
||||
};
|
||||
case 'month':
|
||||
return {
|
||||
startDate: startOfMonth(now),
|
||||
endDate: endOfMonth(now),
|
||||
unit: 'day',
|
||||
num: +num,
|
||||
offset: 0,
|
||||
value,
|
||||
selectedUnit,
|
||||
};
|
||||
case 'year':
|
||||
return {
|
||||
startDate: startOfYear(now),
|
||||
endDate: endOfYear(now),
|
||||
unit: 'month',
|
||||
num: +num,
|
||||
offset: 0,
|
||||
value,
|
||||
selectedUnit,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (+num === -1) {
|
||||
if (num === -1) {
|
||||
switch (unit) {
|
||||
case 'day':
|
||||
return {
|
||||
startDate: subDays(startOfDay(now), 1),
|
||||
endDate: subDays(endOfDay(now), 1),
|
||||
unit: 'hour',
|
||||
num: +num,
|
||||
offset: 0,
|
||||
value,
|
||||
selectedUnit,
|
||||
};
|
||||
case 'week':
|
||||
return {
|
||||
startDate: subDays(startOfWeek(now, { locale: dateLocale }), 7),
|
||||
endDate: subDays(endOfWeek(now, { locale: dateLocale }), 1),
|
||||
unit: 'day',
|
||||
num: +num,
|
||||
offset: 0,
|
||||
value,
|
||||
selectedUnit,
|
||||
};
|
||||
case 'month':
|
||||
return {
|
||||
startDate: subMonths(startOfMonth(now), 1),
|
||||
endDate: subMonths(endOfMonth(now), 1),
|
||||
unit: 'day',
|
||||
num: +num,
|
||||
offset: 0,
|
||||
value,
|
||||
selectedUnit,
|
||||
};
|
||||
case 'year':
|
||||
return {
|
||||
startDate: subYears(startOfYear(now), 1),
|
||||
endDate: subYears(endOfYear(now), 1),
|
||||
unit: 'month',
|
||||
num: +num,
|
||||
offset: 0,
|
||||
value,
|
||||
selectedUnit,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -175,66 +238,60 @@ export function parseDateRange(value: string | object, locale = 'en-US'): DateRa
|
|||
return {
|
||||
startDate: subDays(startOfDay(now), +num - 1),
|
||||
endDate: endOfDay(now),
|
||||
num: +num,
|
||||
offset: 0,
|
||||
unit,
|
||||
value,
|
||||
selectedUnit,
|
||||
};
|
||||
case 'hour':
|
||||
return {
|
||||
startDate: subHours(startOfHour(now), +num - 1),
|
||||
endDate: endOfHour(now),
|
||||
num: +num,
|
||||
offset: 0,
|
||||
unit,
|
||||
value,
|
||||
selectedUnit,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function incrementDateRange(
|
||||
value: { startDate: any; endDate: any; selectedUnit: any },
|
||||
increment: number,
|
||||
) {
|
||||
const { startDate, endDate, selectedUnit } = value;
|
||||
export function getOffsetDateRange(dateRange: DateRange, increment: number) {
|
||||
const { startDate, endDate, unit, num, offset, value } = dateRange;
|
||||
|
||||
const { num, unit } = selectedUnit;
|
||||
const change = num * increment;
|
||||
const { add } = DATE_FUNCTIONS[unit];
|
||||
const { unit: originalUnit } = parseDateValue(value);
|
||||
|
||||
const sub = Math.abs(num) * increment;
|
||||
|
||||
switch (unit) {
|
||||
case 'hour':
|
||||
return {
|
||||
...value,
|
||||
startDate: subHours(startDate, sub),
|
||||
endDate: subHours(endDate, sub),
|
||||
value: 'range',
|
||||
};
|
||||
case 'day':
|
||||
return {
|
||||
...value,
|
||||
startDate: subDays(startDate, sub),
|
||||
endDate: subDays(endDate, sub),
|
||||
value: 'range',
|
||||
};
|
||||
switch (originalUnit) {
|
||||
case 'week':
|
||||
return {
|
||||
...value,
|
||||
startDate: subWeeks(startDate, sub),
|
||||
endDate: subWeeks(endDate, sub),
|
||||
value: 'range',
|
||||
...dateRange,
|
||||
startDate: addWeeks(startDate, increment),
|
||||
endDate: addWeeks(endDate, increment),
|
||||
offset: offset + increment,
|
||||
};
|
||||
case 'month':
|
||||
return {
|
||||
...value,
|
||||
startDate: subMonths(startDate, sub),
|
||||
endDate: subMonths(endDate, sub),
|
||||
value: 'range',
|
||||
...dateRange,
|
||||
startDate: addMonths(startDate, increment),
|
||||
endDate: addMonths(endDate, increment),
|
||||
offset: offset + increment,
|
||||
};
|
||||
case 'year':
|
||||
return {
|
||||
...value,
|
||||
startDate: subYears(startDate, sub),
|
||||
endDate: subYears(endDate, sub),
|
||||
value: 'range',
|
||||
...dateRange,
|
||||
startDate: addYears(startDate, increment),
|
||||
endDate: addYears(endDate, increment),
|
||||
offset: offset + increment,
|
||||
};
|
||||
default:
|
||||
return {
|
||||
startDate: add(startDate, change),
|
||||
endDate: add(endDate, change),
|
||||
value,
|
||||
unit,
|
||||
num,
|
||||
offset: offset + increment,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -276,19 +333,19 @@ export function getDateFromString(str: string) {
|
|||
|
||||
export function getDateArray(data: any[], startDate: Date, endDate: Date, unit: string) {
|
||||
const arr = [];
|
||||
const [diff, add, normalize] = dateFuncs[unit];
|
||||
const { diff, add, start } = DATE_FUNCTIONS[unit];
|
||||
const n = diff(endDate, startDate) + 1;
|
||||
|
||||
function findData(date: Date) {
|
||||
const d = data.find(({ x }) => {
|
||||
return normalize(getDateFromString(x)).getTime() === date.getTime();
|
||||
return start(getDateFromString(x)).getTime() === date.getTime();
|
||||
});
|
||||
|
||||
return d?.y || 0;
|
||||
}
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
const t = normalize(add(startDate, i));
|
||||
const t = start(add(startDate, i));
|
||||
const y = findData(t);
|
||||
|
||||
arr.push({ x: t, y });
|
||||
|
|
@ -297,23 +354,6 @@ export function getDateArray(data: any[], startDate: Date, endDate: Date, unit:
|
|||
return arr;
|
||||
}
|
||||
|
||||
export function getDateLength(startDate: Date, endDate: Date, unit: string | number) {
|
||||
const [diff] = dateFuncs[unit];
|
||||
return diff(endDate, startDate) + 1;
|
||||
}
|
||||
|
||||
export const CUSTOM_FORMATS = {
|
||||
'en-US': {
|
||||
p: 'ha',
|
||||
pp: 'h:mm:ss',
|
||||
},
|
||||
'fr-FR': {
|
||||
'M/d': 'd/M',
|
||||
'MMM d': 'd MMM',
|
||||
'EEE M/d': 'EEE d/M',
|
||||
},
|
||||
};
|
||||
|
||||
export function formatDate(date: string | number | Date, str: string, locale = 'en-US') {
|
||||
return format(
|
||||
typeof date === 'string' ? new Date(date) : date,
|
||||
|
|
@ -331,3 +371,12 @@ export function maxDate(...args: Date[]) {
|
|||
export function minDate(...args: any[]) {
|
||||
return min(args.filter(n => isDate(n)));
|
||||
}
|
||||
|
||||
export function getLocalTime(t: string | number | Date) {
|
||||
return addMinutes(new Date(t), new Date().getTimezoneOffset());
|
||||
}
|
||||
|
||||
export function getDateLength(startDate: Date, endDate: Date, unit: string | number) {
|
||||
const { diff } = DATE_FUNCTIONS[unit];
|
||||
return diff(endDate, startDate) + 1;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,27 +17,23 @@ export function getDatabaseType(url = process.env.DATABASE_URL) {
|
|||
return POSTGRESQL;
|
||||
}
|
||||
|
||||
if (process.env.CLICKHOUSE_URL) {
|
||||
return CLICKHOUSE;
|
||||
}
|
||||
|
||||
return type;
|
||||
}
|
||||
|
||||
export async function runQuery(queries: any) {
|
||||
const db = getDatabaseType(process.env.CLICKHOUSE_URL || process.env.DATABASE_URL);
|
||||
|
||||
if (db === POSTGRESQL || db === MYSQL) {
|
||||
return queries[PRISMA]();
|
||||
}
|
||||
|
||||
if (db === CLICKHOUSE) {
|
||||
if (process.env.CLICKHOUSE_URL) {
|
||||
if (queries[KAFKA]) {
|
||||
return queries[KAFKA]();
|
||||
}
|
||||
|
||||
return queries[CLICKHOUSE]();
|
||||
}
|
||||
|
||||
const db = getDatabaseType();
|
||||
|
||||
if (db === POSTGRESQL || db === MYSQL) {
|
||||
return queries[PRISMA]();
|
||||
}
|
||||
}
|
||||
|
||||
export function notImplemented() {
|
||||
|
|
|
|||
|
|
@ -123,7 +123,7 @@ export async function getLocation(ip, req) {
|
|||
|
||||
export async function getClientInfo(req: NextApiRequestCollect, { screen }) {
|
||||
const userAgent = req.headers['user-agent'];
|
||||
const ip = getIpAddress(req);
|
||||
const ip = req.body.payload.ip || getIpAddress(req);
|
||||
const location = await getLocation(ip, req);
|
||||
const country = location?.country;
|
||||
const subdivision1 = location?.subdivision1;
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ export const languages = {
|
|||
'el-GR': { label: 'Ελληνικά', dateLocale: el },
|
||||
'en-GB': { label: 'English (UK)', dateLocale: enGB },
|
||||
'en-US': { label: 'English (US)', dateLocale: enUS },
|
||||
'es-MX': { label: 'Español', dateLocale: es },
|
||||
'es-ES': { label: 'Español', dateLocale: es },
|
||||
'fa-IR': { label: 'فارسی', dateLocale: faIR, dir: 'rtl' },
|
||||
'fi-FI': { label: 'Suomi', dateLocale: fi },
|
||||
'fo-FO': { label: 'Føroyskt' },
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import cache from 'lib/cache';
|
||||
import { getSession, getUserById, getWebsiteById } from 'queries';
|
||||
import { getSession, getUser, getWebsite } from 'queries';
|
||||
import { User, Website, Session } from '@prisma/client';
|
||||
|
||||
export async function loadWebsite(websiteId: string): Promise<Website> {
|
||||
|
|
@ -8,7 +8,7 @@ export async function loadWebsite(websiteId: string): Promise<Website> {
|
|||
if (cache.enabled) {
|
||||
website = await cache.fetchWebsite(websiteId);
|
||||
} else {
|
||||
website = await getWebsiteById(websiteId);
|
||||
website = await getWebsite(websiteId);
|
||||
}
|
||||
|
||||
if (!website || website.deletedAt) {
|
||||
|
|
@ -40,7 +40,7 @@ export async function loadUser(userId: string): Promise<User> {
|
|||
if (cache.enabled) {
|
||||
user = await cache.fetchUser(userId);
|
||||
} else {
|
||||
user = await getUserById(userId);
|
||||
user = await getUser(userId);
|
||||
}
|
||||
|
||||
if (!user || user.deletedAt) {
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import {
|
|||
unauthorized,
|
||||
} from 'next-basics';
|
||||
import { NextApiRequestCollect } from 'pages/api/send';
|
||||
import { getUserById } from '../queries';
|
||||
import { getUser } from '../queries';
|
||||
|
||||
const log = debug('umami:middleware');
|
||||
|
||||
|
|
@ -57,12 +57,12 @@ export const useAuth = createMiddleware(async (req, res, next) => {
|
|||
const { userId, authKey, grant } = payload || {};
|
||||
|
||||
if (userId) {
|
||||
user = await getUserById(userId);
|
||||
user = await getUser(userId);
|
||||
} else if (redis.enabled && authKey) {
|
||||
const key = await redis.client.get(authKey);
|
||||
|
||||
if (key?.userId) {
|
||||
user = await getUserById(key.userId);
|
||||
user = await getUser(key.userId);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ const POSTGRESQL_DATE_FORMATS = {
|
|||
};
|
||||
|
||||
function getAddIntervalQuery(field: string, interval: string): string {
|
||||
const db = getDatabaseType(process.env.DATABASE_URL);
|
||||
const db = getDatabaseType();
|
||||
|
||||
if (db === POSTGRESQL) {
|
||||
return `${field} + interval '${interval}'`;
|
||||
|
|
@ -36,7 +36,7 @@ function getAddIntervalQuery(field: string, interval: string): string {
|
|||
}
|
||||
|
||||
function getDayDiffQuery(field1: string, field2: string): string {
|
||||
const db = getDatabaseType(process.env.DATABASE_URL);
|
||||
const db = getDatabaseType();
|
||||
|
||||
if (db === POSTGRESQL) {
|
||||
return `${field1}::date - ${field2}::date`;
|
||||
|
|
@ -48,7 +48,7 @@ function getDayDiffQuery(field1: string, field2: string): string {
|
|||
}
|
||||
|
||||
function getCastColumnQuery(field: string, type: string): string {
|
||||
const db = getDatabaseType(process.env.DATABASE_URL);
|
||||
const db = getDatabaseType();
|
||||
|
||||
if (db === POSTGRESQL) {
|
||||
return `${field}::${type}`;
|
||||
|
|
@ -92,7 +92,7 @@ function getTimestampDiffQuery(field1: string, field2: string): string {
|
|||
}
|
||||
}
|
||||
|
||||
function mapFilter(column, operator, name, type = 'varchar') {
|
||||
function mapFilter(column: string, operator: string, name: string, type = 'varchar') {
|
||||
switch (operator) {
|
||||
case OPERATORS.equals:
|
||||
return `${column} = {{${name}::${type}}}`;
|
||||
|
|
@ -151,7 +151,7 @@ async function parseFilters(
|
|||
params: {
|
||||
...normalizeFilters(filters),
|
||||
websiteId,
|
||||
startDate: maxDate(filters.startDate, website.resetAt),
|
||||
startDate: maxDate(filters.startDate, website?.resetAt),
|
||||
websiteDomain: website.domain,
|
||||
},
|
||||
};
|
||||
|
|
@ -175,25 +175,14 @@ async function rawQuery(sql: string, data: object): Promise<any> {
|
|||
return prisma.rawQuery(query, params);
|
||||
}
|
||||
|
||||
function getPageFilters(filters: SearchFilter): [
|
||||
{
|
||||
orderBy: {
|
||||
[x: string]: string;
|
||||
}[];
|
||||
take: number;
|
||||
skip: number;
|
||||
},
|
||||
{
|
||||
pageSize: number;
|
||||
page: number;
|
||||
orderBy: string;
|
||||
},
|
||||
] {
|
||||
const { page = 1, pageSize = DEFAULT_PAGE_SIZE, orderBy, sortDescending = false } = filters || {};
|
||||
async function pagedQuery<T>(model: string, criteria: T, filters: SearchFilter) {
|
||||
const { page = 1, pageSize, orderBy, sortDescending = false } = filters || {};
|
||||
const size = +pageSize || DEFAULT_PAGE_SIZE;
|
||||
|
||||
return [
|
||||
{
|
||||
...(pageSize > 0 && { take: +pageSize, skip: +pageSize * (page - 1) }),
|
||||
const data = await prisma.client[model].findMany({
|
||||
...criteria,
|
||||
...{
|
||||
...(size > 0 && { take: +size, skip: +size * (page - 1) }),
|
||||
...(orderBy && {
|
||||
orderBy: [
|
||||
{
|
||||
|
|
@ -202,32 +191,61 @@ function getPageFilters(filters: SearchFilter): [
|
|||
],
|
||||
}),
|
||||
},
|
||||
{ page: +page, pageSize, orderBy },
|
||||
];
|
||||
});
|
||||
|
||||
const count = await prisma.client[model].count({ where: (criteria as any).where });
|
||||
|
||||
return { data, count, page: +page, pageSize: size, orderBy };
|
||||
}
|
||||
|
||||
function getSearchMode(): { mode?: Prisma.QueryMode } {
|
||||
function getQueryMode(): Prisma.QueryMode {
|
||||
const db = getDatabaseType();
|
||||
|
||||
if (db === POSTGRESQL) {
|
||||
return {
|
||||
mode: 'insensitive',
|
||||
};
|
||||
return 'insensitive';
|
||||
}
|
||||
|
||||
return {};
|
||||
return 'default';
|
||||
}
|
||||
|
||||
function getSearchParameters(query: string, filters: { [key: string]: any }[]) {
|
||||
if (!query) return;
|
||||
|
||||
const mode = getQueryMode();
|
||||
const parseFilter = (filter: { [key: string]: any }) => {
|
||||
const [[key, value]] = Object.entries(filter);
|
||||
|
||||
return {
|
||||
[key]:
|
||||
typeof value === 'string'
|
||||
? {
|
||||
[value]: query,
|
||||
mode,
|
||||
}
|
||||
: parseFilter(value),
|
||||
};
|
||||
};
|
||||
|
||||
const params = filters.map(filter => parseFilter(filter));
|
||||
|
||||
return {
|
||||
AND: {
|
||||
OR: params,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
...prisma,
|
||||
getAddIntervalQuery,
|
||||
getDayDiffQuery,
|
||||
getCastColumnQuery,
|
||||
getDayDiffQuery,
|
||||
getDateQuery,
|
||||
getTimestampDiffQuery,
|
||||
getFilterQuery,
|
||||
getSearchParameters,
|
||||
getTimestampDiffQuery,
|
||||
getQueryMode,
|
||||
pagedQuery,
|
||||
parseFilters,
|
||||
getPageFilters,
|
||||
getSearchMode,
|
||||
rawQuery,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { getAllowedUnits, getMinimumUnit } from './date';
|
|||
import { getWebsiteDateRange } from '../queries';
|
||||
|
||||
export async function parseDateRangeQuery(req: NextApiRequest) {
|
||||
const { id: websiteId, startAt, endAt, unit } = req.query;
|
||||
const { websiteId, startAt, endAt, unit } = req.query;
|
||||
|
||||
// All-time
|
||||
if (+startAt === 0 && +endAt === 1) {
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import {
|
|||
} from './constants';
|
||||
import * as yup from 'yup';
|
||||
import { TIME_UNIT } from './date';
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
|
||||
type ObjectValues<T> = T[keyof T];
|
||||
|
||||
|
|
@ -38,10 +39,13 @@ export interface TeamSearchFilter extends SearchFilter {
|
|||
userId?: string;
|
||||
}
|
||||
|
||||
export interface TeamUserSearchFilter extends SearchFilter {
|
||||
teamId?: string;
|
||||
}
|
||||
|
||||
export interface ReportSearchFilter extends SearchFilter {
|
||||
userId?: string;
|
||||
websiteId?: string;
|
||||
includeTeams?: boolean;
|
||||
}
|
||||
|
||||
export interface SearchFilter {
|
||||
|
|
@ -53,7 +57,7 @@ export interface SearchFilter {
|
|||
}
|
||||
|
||||
export interface FilterResult<T> {
|
||||
data: T[];
|
||||
data: T;
|
||||
count: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
|
|
@ -61,6 +65,13 @@ export interface FilterResult<T> {
|
|||
sortDescending?: boolean;
|
||||
}
|
||||
|
||||
export interface FilterQueryResult<T> {
|
||||
result: FilterResult<T>;
|
||||
query: any;
|
||||
params: SearchFilter;
|
||||
setParams: Dispatch<SetStateAction<T | SearchFilter>>;
|
||||
}
|
||||
|
||||
export interface DynamicData {
|
||||
[key: string]: number | string | DynamicData | number[] | string[] | DynamicData[];
|
||||
}
|
||||
|
|
@ -176,11 +187,12 @@ export interface RealtimeUpdate {
|
|||
}
|
||||
|
||||
export interface DateRange {
|
||||
value: string;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
value: string;
|
||||
unit?: TimeUnit;
|
||||
selectedUnit?: { num: number; unit: TimeUnit };
|
||||
num?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
export interface QueryFilters {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue