0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2024-12-16 20:26:19 -05:00

refactor: update log types in database and console

This commit is contained in:
Gao Sun 2022-12-20 13:47:12 +08:00
parent 2496b57fef
commit c24a57f2c4
No known key found for this signature in database
GPG key ID: 13EBE123E4773688
18 changed files with 69 additions and 25 deletions

View file

@ -8,13 +8,13 @@ import { logEventTitle } from '@/consts/logs';
import * as styles from './index.module.scss';
type Props = {
type: string;
eventKey: string;
isSuccess: boolean;
to?: string;
};
const EventName = ({ type, isSuccess, to }: Props) => {
const title = logEventTitle[type] ?? type;
const EventName = ({ eventKey, isSuccess, to }: Props) => {
const title = logEventTitle[eventKey] ?? eventKey;
return (
<div className={styles.eventName}>

View file

@ -115,7 +115,7 @@ const AuditLogTable = ({ userId }: Props) => {
)}
{isLoading && <TableLoading columns={tableColumnCount} />}
{logs?.length === 0 && <TableEmpty columns={tableColumnCount} />}
{logs?.map(({ type, payload, createdAt, id }) => (
{logs?.map(({ key, payload, createdAt, id }) => (
<tr
key={id}
className={tableStyles.clickable}
@ -124,7 +124,7 @@ const AuditLogTable = ({ userId }: Props) => {
}}
>
<td>
<EventName type={type} isSuccess={payload.result === LogResult.Success} />
<EventName eventKey={key} isSuccess={payload.result === LogResult.Success} />
</td>
{showUserColumn && (
<td>{payload.userId ? <UserName userId={payload.userId} /> : '-'}</td>

View file

@ -1,6 +1,9 @@
import type { LogKey } from '@logto/schemas';
type LogEventTitle = Record<string, string>;
export const logEventTitle: LogEventTitle = Object.freeze({
/** @deprecated Don't use or update. */
const logEventTitleLegacy: LogEventTitle = Object.freeze({
RegisterUsernamePassword: 'Register with username and password',
RegisterEmailSendPasscode: 'Register with email (send passcode)',
RegisterEmail: 'Register with email',
@ -19,3 +22,12 @@ export const logEventTitle: LogEventTitle = Object.freeze({
RefreshTokenExchangeToken: 'Exchange token by refresh token',
RevokeToken: 'Revoke token',
});
export const logEventTitle: Record<string, string | undefined> & Partial<Record<LogKey, string>> =
Object.freeze({
...logEventTitleLegacy,
'ExchangeTokenBy.AuthorizationCode': 'Exchange token by auth code',
'ExchangeTokenBy.RefreshToken': 'Exchange token by refresh token',
'Interaction.Create': 'Interaction started',
'Interaction.End': 'Interaction ended',
});

View file

@ -57,11 +57,11 @@ const AuditLogDetails = () => {
<Card className={styles.header}>
<EventIcon isSuccess={data.payload.result === 'Success'} />
<div className={styles.content}>
<div className={styles.eventName}>{logEventTitle[data.type]}</div>
<div className={styles.eventName}>{logEventTitle[data.key]}</div>
<div className={styles.basicInfo}>
<div className={styles.infoItem}>
<div className={styles.label}>{t('log_details.event_type')}</div>
<div>{data.type}</div>
<div className={styles.label}>{t('log_details.event_key')}</div>
<div>{data.key}</div>
</div>
<div className={styles.infoItem}>
<div className={styles.label}>{t('log_details.application')}</div>

View file

@ -71,7 +71,7 @@ const initLogger = (basePayload?: Readonly<BaseLogPayload>) => {
await insertLog({
id: nanoid(),
type: logger.type,
key: logger.type,
payload: {
...logger.basePayload,
...logger.payload,

View file

@ -139,7 +139,7 @@ export default function koaAuditLog<
entries.map(async ({ payload }) => {
return insertLog({
id: nanoid(),
type: payload.key,
key: payload.key,
payload: { ip, userAgent, ...payload },
});
})

View file

@ -20,7 +20,7 @@ export type LogCondition = {
const buildLogConditionSql = (logCondition: LogCondition) =>
conditionalSql(logCondition, ({ logType, applicationId, userId }) => {
const subConditions = [
conditionalSql(logType, (logType) => sql`${fields.type}=${logType}`),
conditionalSql(logType, (logType) => sql`${fields.key}=${logType}`),
conditionalSql(userId, (userId) => sql`${fields.payload}->>'userId'=${userId}`),
conditionalSql(
applicationId,
@ -59,7 +59,7 @@ export const getDailyActiveUserCountsByTimeInterval = async (
from ${table}
where ${fields.createdAt} > to_timestamp(${startTimeExclusive}::double precision / 1000)
and ${fields.createdAt} <= to_timestamp(${endTimeInclusive}::double precision / 1000)
and ${fields.type} like ${`${token.Flow.ExchangeTokenBy}.%`}
and ${fields.key} like ${`${token.Flow.ExchangeTokenBy}.%`}
and ${fields.payload}->>'result' = 'Success'
group by date(${fields.createdAt})
`);
@ -73,6 +73,6 @@ export const countActiveUsersByTimeInterval = async (
from ${table}
where ${fields.createdAt} > to_timestamp(${startTimeExclusive}::double precision / 1000)
and ${fields.createdAt} <= to_timestamp(${endTimeInclusive}::double precision / 1000)
and ${fields.type} like ${`${token.Flow.ExchangeTokenBy}.%`}
and ${fields.key} like ${`${token.Flow.ExchangeTokenBy}.%`}
and ${fields.payload}->>'result' = 'Success'
`);

View file

@ -20,7 +20,7 @@ describe('admin console logs (legacy)', () => {
const logs = await getLogs();
const registerLog = logs.filter(
({ type, payload }) => type === 'RegisterUsernamePassword' && payload.username === username
({ key, payload }) => key === 'RegisterUsernamePassword' && payload.username === username
);
expect(registerLog.length).toBeGreaterThan(0);

View file

@ -3,7 +3,7 @@ const log_details = {
back_to_user: 'Zurück zu {{name}}',
success: 'Erfolgreich',
failed: 'Fehlgeschlagen',
event_type: 'Event Typ',
event_key: 'Event Key', // UNTRANSLATED
application: 'Anwendung',
ip_address: 'IP Adresse',
user: 'Benutzer',

View file

@ -3,7 +3,7 @@ const log_details = {
back_to_user: 'Back to {{name}}',
success: 'Success',
failed: 'Failed',
event_type: 'Event type',
event_key: 'Event Key',
application: 'Application',
ip_address: 'IP address',
user: 'User',

View file

@ -3,7 +3,7 @@ const log_details = {
back_to_user: 'Retour à {{name}}',
success: 'Succès',
failed: 'Échoué',
event_type: "Type d'événement",
event_key: 'Event Key', // UNTRANSLATED
application: 'Application',
ip_address: 'Addresse IP',
user: 'Utilisateur',

View file

@ -3,7 +3,7 @@ const log_details = {
back_to_user: '{{name}}으로 돌아가기',
success: '성공',
failed: '실패',
event_type: '활동 종류',
event_key: 'Event Key', // UNTRANSLATED
application: '어플리케이션',
ip_address: 'IP 주소',
user: '사용자',

View file

@ -3,7 +3,7 @@ const log_details = {
back_to_user: 'Voltar para {{name}}',
success: 'Sucesso',
failed: 'Falhou',
event_type: 'Tipo de evento',
event_key: 'Event Key', // UNTRANSLATED
application: 'Aplicativo',
ip_address: 'Endereço de IP',
user: 'Usuário',

View file

@ -3,7 +3,7 @@ const log_details = {
back_to_user: 'De volta a {{name}}',
success: 'Sucesso',
failed: 'Falha',
event_type: 'Tipo de evento',
event_key: 'Event Key', // UNTRANSLATED
application: 'Aplicação',
ip_address: 'Endereço IP',
user: 'Utilizador',

View file

@ -3,7 +3,7 @@ const log_details = {
back_to_user: '{{name}}e geri dön',
success: 'Başarılı',
failed: 'Başarısız',
event_type: 'Etkinlik tipi',
event_key: 'Event Key', // UNTRANSLATED
application: 'Uygulama',
ip_address: 'IP adresi',
user: 'Kullanıcı',

View file

@ -3,7 +3,7 @@ const log_details = {
back_to_user: '返回 {{name}}',
success: '成功',
failed: '失败',
event_type: '事件类型',
event_key: 'Event Key', // UNTRANSLATED
application: '应用',
ip_address: 'IP 地址',
user: '用户',

View file

@ -0,0 +1,32 @@
import { sql } from 'slonik';
import type { AlterationScript } from '../lib/types/alteration.js';
const alteration: AlterationScript = {
up: async (pool) => {
await pool.query(sql`
-- Update metadata
alter table logs rename column type to key;
alter table logs alter column key type varchar(128);
alter index logs__type rename to logs__key;
-- Update token exchange keys
update logs set "key" = 'ExchangeTokenBy.AuthorizationCode' where "key" = 'CodeExchangeToken';
update logs set "key" = 'ExchangeTokenBy.RefreshToken' where "key" = 'RefreshTokenExchangeToken';
`);
},
down: async (pool) => {
await pool.query(sql`
-- Update token exchange keys
update logs set "key" = 'CodeExchangeToken' where "key" = 'ExchangeTokenBy.AuthorizationCode';
update logs set "key" = 'RefreshTokenExchangeToken' where "key" = 'ExchangeTokenBy.RefreshToken';
-- Update metadata
alter table logs alter column key type varchar(64);
alter table logs rename column key to type;
alter index logs__key rename to logs__type;
`);
},
};
export default alteration;

View file

@ -1,13 +1,13 @@
create table logs
(
id varchar(21) not null,
type varchar(64) not null,
key varchar(128) not null,
payload jsonb /* @use ArbitraryObject */ not null default '{}'::jsonb,
created_at timestamptz not null default (now()),
primary key (id)
);
create index logs__type on logs (type);
create index logs__key on logs (key);
create index logs__created_at on logs (created_at);
create index logs__user_id on logs ((payload->>'user_id') nulls last);
create index logs__application_id on logs ((payload->>'application_id') nulls last);