diff --git a/mysql-schema/027-userlog3.sql b/mysql-schema/027-userlog3.sql new file mode 100644 index 00000000..ff41548a --- /dev/null +++ b/mysql-schema/027-userlog3.sql @@ -0,0 +1,9 @@ +SET NAMES utf8mb4; +START TRANSACTION; + +INSERT INTO changelog VALUES (27, UNIX_TIMESTAMP()); + +ALTER TABLE user_log ADD + user_agent TEXT NULL; + +COMMIT; diff --git a/src/log/formats/csv.ts b/src/log/formats/csv.ts index 746078a1..b1d2866b 100644 --- a/src/log/formats/csv.ts +++ b/src/log/formats/csv.ts @@ -2,13 +2,14 @@ import { eventTypeString, LogEntry } from '../types'; export default function csv(log: LogEntry[]): string { - const header = 'time,eventType,ip\n'; + const header = 'time,eventType,ip,userAgent\n'; return header + log.map( entry => { return [ entry.time.toISOString(), eventTypeString.get(entry.eventType), - entry.ip + entry.ip, + entry.userAgent ]; }).join('\n'); diff --git a/src/log/service.ts b/src/log/service.ts index f93de863..b6c35b25 100644 --- a/src/log/service.ts +++ b/src/log/service.ts @@ -4,31 +4,34 @@ import { User } from '../user/types'; import { EventType, LogEntry } from './types'; export function log(eventType: EventType, ctx: Context): Promise; -export function log(eventType: EventType, ip: string, userId: number): Promise; +export function log(eventType: EventType, ip: string, userId: number, userAgent: string): Promise; export default async function log( eventType: EventType, arg1: string | Context, arg2?: number, + arg3?: string ) { if (isContext(arg1)) { - addLogEntry( + await addLogEntry( eventType, arg1.ip(), - arg1.state.session.user && arg1.state.session.user.id ? arg1.state.session.user.id : null + arg1.state.session.user && arg1.state.session.user.id ? arg1.state.session.user.id : null, + arg1.request.headers.get('User-Agent'), ); } else { - addLogEntry(eventType, arg1, arg2); + await addLogEntry(eventType, arg1, arg2, arg3); } } -export async function addLogEntry(eventType: EventType, ip: string, userId: number): Promise { +export async function addLogEntry(eventType: EventType, ip: string, userId: number, userAgent: string): Promise { await db.query('INSERT INTO user_log SET time = UNIX_TIMESTAMP(), ?', { user_id: userId, event_type: eventType, - ip: ip + ip: ip, + user_agent: userAgent }); } @@ -39,6 +42,7 @@ type LogRow = { ip: string, time: number, event_type: EventType, + user_agent: string }; export async function findByUser(user: User): Promise { @@ -52,6 +56,7 @@ export async function findByUser(user: User): Promise { time: new Date(row.time * 1000), ip: row.ip, eventType: row.event_type, + userAgent: row.user_agent }; }); diff --git a/src/log/types.ts b/src/log/types.ts index 40776838..4b51da65 100644 --- a/src/log/types.ts +++ b/src/log/types.ts @@ -13,6 +13,7 @@ export type LogEntry = { userId: number, ip: string, eventType: EventType, + userAgent: string }; export const eventTypeString = new Map([