Auth and session middleware.

This commit is contained in:
Mike Cao 2020-07-27 23:52:14 -07:00
parent 590a70c2ff
commit d81ee3932d
14 changed files with 142 additions and 73 deletions

8
lib/auth.js Normal file
View file

@ -0,0 +1,8 @@
import { parse } from 'cookie';
import { verifySecureToken } from './crypto';
export default async req => {
const token = parse(req.headers.cookie)['umami.auth'];
return verifySecureToken(token);
};

11
lib/date.js Normal file
View file

@ -0,0 +1,11 @@
import moment from 'moment-timezone';
import { addMinutes } from 'date-fns';
export function getTimezone() {
const tz = moment.tz.guess();
return moment.tz.zone(tz).abbr(new Date().getTimezoneOffset());
}
export function getLocalTime(t) {
return addMinutes(new Date(t), new Date().getTimezoneOffset());
}

View file

@ -32,6 +32,16 @@ export async function getWebsite(website_uuid) {
);
}
export async function getWebsites(user_id) {
return runQuery(
prisma.website.findMany({
where: {
user_id,
},
}),
);
}
export async function createSession(website_id, data) {
return runQuery(
prisma.session.create({
@ -126,3 +136,29 @@ export async function getPageviews(website_id, start_at, end_at) {
}),
);
}
export async function getPageviewData(
website_id,
start_at,
end_at,
timezone = 'utc',
unit = 'day',
count = '*',
) {
return runQuery(
prisma.queryRaw(
`
select date_trunc('${unit}', created_at at time zone '${timezone}') t,
count(${count}) y
from pageview
where website_id=$1
and created_at between $2 and $3
group by 1
order by 1
`,
website_id,
start_at,
end_at,
),
);
}

View file

@ -1,4 +1,6 @@
import cors from 'cors';
import session from './session';
import auth from './auth';
export function use(middleware) {
return (req, res) =>
@ -13,3 +15,21 @@ export function use(middleware) {
}
export const useCors = use(cors());
export const useSession = use(async (req, res, next) => {
try {
req.session = await session(req);
} catch {
return res.status(400).end();
}
next();
});
export const useAuth = use(async (req, res, next) => {
try {
req.auth = await auth(req);
} catch {
return res.status(401).end();
}
next();
});

View file

@ -1,5 +1,5 @@
import { getWebsite, getSession, createSession } from 'lib/db';
import { getCountry, getDevice, getIpAddress } from 'lib/utils';
import { getCountry, getDevice, getIpAddress } from 'lib/request';
import { uuid, isValidId, verifyToken } from 'lib/crypto';
export default async req => {
@ -46,6 +46,8 @@ export default async req => {
session_id,
session_uuid,
};
} else {
throw new Error(`Invalid website: ${website_uuid}`);
}
}
}