Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@sourceloop/audit-log

sourcefuse9.2k9.0.0TypeScript support: included

Audit Log extension.

loopback-extension, loopback

readme

ARC By SourceFuse logo

@sourceloop/audit-log

npm version Sonar Quality Gate Synk Status GitHub contributors downloads License Powered By LoopBack #

Overview

The @sourceloop/audit-log package is a powerful LoopBack 4 extension designed to seamlessly implement audit logs in your LoopBack applications. With this extension, you can effortlessly track and record audit data for all database transactions within your application.

This package provides a generic model that enables the storage of audit logs, which can be backed by any datasource of your choice. Whether you're using MySQL, PostgreSQL, MongoDB, or any other database, the Audit Logs package ensures compatibility and flexibility.

By incorporating the Audit Logs package into your application, you gain valuable insights into the history of data changes, user actions, and system events. Maintain a comprehensive audit trail for compliance, troubleshooting, and analysis purposes.

Install

npm install @sourceloop/audit-log

Usage

In order to use this component into your LoopBack application, please follow below steps.

  • If you wish to modify the one provided by this extension create your own model class just the one shown below. You can use lb4 model command to create new model
import {Entity, model, property} from '@loopback/repository';
import {Action} from '@sourceloop/audit-log';

@model({
  name: 'audit_logs',
  settings: {
    strict: false,
  },
})
export class AuditLog extends Entity {
  @property({
    type: 'string',
    id: true,
    generated: false,
  })
  id?: string;

  @property({
    type: 'string',
    required: true,
  })
  action: Action;

  @property({
    name: 'acted_at',
    type: 'date',
    required: true,
  })
  actedAt: Date;

  @property({
    name: 'acted_on',
    type: 'string',
  })
  actedOn?: string;

  @property({
    name: 'action_key',
    type: 'string',
    required: true,
  })
  actionKey: string;

  @property({
    name: 'entity_id',
    type: 'string',
    required: true,
  })
  entityId: string;

  @property({
    type: 'string',
    required: true,
  })
  actor: string;

  @property({
    type: 'object',
  })
  before?: object;

  @property({
    type: 'object',
  })
  after?: object;

  // Define well-known properties here

  // Indexer property to allow additional data
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [prop: string]: any;

  constructor(data?: Partial<AuditLog>) {
    super(data);
  }
}
  • Using lb4 datasource command create your own datasource using your preferred connector. Here is an example of datasource using postgres connector. Notice the statement static dataSourceName = AuditDbSourceName;. Make sure you change the data source name as per this in order to ensure connection work from extension.
import {inject, lifeCycleObserver, LifeCycleObserver} from '@loopback/core';
import {juggler} from '@loopback/repository';
import {AuditDbSourceName} from '@sourceloop/audit-log';

const config = {
  name: 'audit',
  connector: 'postgresql',
  url: '',
  host: '',
  port: 0,
  user: '',
  password: '',
  database: '',
};

@lifeCycleObserver('datasource')
export class AuditDataSource
  extends juggler.DataSource
  implements LifeCycleObserver
{
  static dataSourceName = AuditDbSourceName;
  static readonly defaultConfig = config;

  constructor(
    @inject('datasources.config.audit', {optional: true})
    dsConfig: object = config,
  ) {
    super(dsConfig);
  }
}
  • If you have a custom model and you wish to use that in your repository class you can Using lb4 repository command, create a repository file. After that, change the inject paramater as below so as to refer to correct data source name. @inject(datasources.${AuditDbSourceName}) dataSource: AuditDataSource,

One example below.

import {inject} from '@loopback/core';
import {DefaultCrudRepository} from '@loopback/repository';
import {AuditDbSourceName} from '@sourceloop/audit-log';

import {AuditDataSource} from '../datasources';
import {AuditLog} from '../models';

export class AuditLogRepository extends DefaultCrudRepository<
  AuditLog,
  typeof AuditLog.prototype.id
> {
  constructor(
    @inject(`datasources.${AuditDbSourceName}`) dataSource: AuditDataSource,
  ) {
    super(AuditLog, dataSource);
  }
}
  • The component exposes a mixin for your repository classes. Just extend your repository class with AuditRepositoryMixin, for all those repositories where you need audit data. See an example below. For a model Group, here we are extending the GroupRepository with AuditRepositoryMixin.
import {repository} from '@loopback/repository';
import {Group, GroupRelations} from '../models';
import {PgdbDataSource} from '../datasources';
import {inject, Getter, Constructor} from '@loopback/core';
import {AuthenticationBindings, IAuthUser} from 'loopback4-authentication';
import {AuditRepositoryMixin, AuditLogRepository} from '@sourceloop/audit-log';

const groupAuditOpts: IAuditMixinOptions = {
  actionKey: 'Group_Logs',
};

export class GroupRepository extends AuditRepositoryMixin<
  Group,
  typeof Group.prototype.id,
  GroupRelations,
  string,
  Constructor<
    DefaultCrudRepository<Group, typeof Group.prototype.id, GroupRelations>
  >
>(DefaultCrudRepository, groupAuditOpts) {
  constructor(
    @inject('datasources.pgdb') dataSource: PgdbDataSource,
    @inject.getter(AuthenticationBindings.CURRENT_USER)
    public getCurrentUser: Getter<IAuthUser>,
    @repository.getter(AuditLogRepository)
    public getAuditLogRepository: Getter<AuditLogRepository>,
  ) {
    super(Group, dataSource, getCurrentUser);
  }
}

and also bind the component of this extension in your application.ts

import {AuditLogComponent} from '@sourceloop/audit-log';

this.component(AuditLogComponent);
  • The above code uses the default repository provided by this extension
  • If you wish to use your custom repository and model class do the following
import {repository} from '@loopback/repository';
import {Group, GroupRelations} from '../models';
import {PgdbDataSource} from '../datasources';
import {inject, Getter, Constructor} from '@loopback/core';
import {AuthenticationBindings, IAuthUser} from 'loopback4-authentication';
import {AuditRepositoryMixin} from '@sourceloop/audit-log';
import {CustomAuditLogRepository} from './audit-log.repository';
import {CustomAuditLogModel} from '../models';

const groupAuditOpts: IAuditMixinOptions = {
  actionKey: 'Group_Logs',
};

export class GroupRepository extends AuditRepositoryMixin<
  Group,
  typeof Group.prototype.id,
  GroupRelations,
  string,
  Constructor<
    DefaultCrudRepository<Group, typeof Group.prototype.id, GroupRelations>
  >,
  // pass the below two parameters when you want your custom model to be used
  // otheriwise the default model and repository will be used
  CustomAuditLogModel,
  CustomAuditLogRepository
>(DefaultCrudRepository, groupAuditOpts) {
  constructor(
    @inject('datasources.pgdb') dataSource: PgdbDataSource,
    @inject.getter(AuthenticationBindings.CURRENT_USER)
    public getCurrentUser: Getter<IAuthUser>,
    @repository.getter(CustomAuditLogRepository)
    public getAuditLogRepository: Getter<CustomAuditLogRepository>,
  ) {
    super(Group, dataSource, getCurrentUser);
  }
}

You can pass any extra attributes to save into audit table using the IAuditMixinOptions parameter of mixin function. You can also pass some dynamic values to the extra columns of the audit-log table via the method options.

const groupAuditOpts: IAuditMixinOptions = {
  actionKey: 'Group_Logs',
  extra: 'static value',
};
repo.create(data, {extra: 'random calculated value'});

So the method options will have a priority over repository mixin options.

Make sure you provide getCurrentUser and getAuditLogRepository Getter functions in constructor.

This will create all insert, update, delete audits for this model.

  • Option to disable audit logging on specific functions by just passing noAudit:true flag with options
create(data, {noAudit: true});
  • The Actor field is configurable and can save any string type value in the field. Though the default value will be userId a developer can save any string field from the current User that is being passed.
export interface User<ID = string, TID = string, UTID = string> {
  id?: string;
  username: string;
  password?: string;
  identifier?: ID;
  permissions: string[];
  authClientId: number;
  email?: string;
  role: string;
  firstName: string;
  lastName: string;
  middleName?: string;
  tenantId?: TID;
  userTenantId?: UTID;
  passwordExpiryTime?: Date;
  allowedResources?: string[];
}

Steps

  1. All you need to do is bind a User key to the ActorIdKey in application.ts
this.bind(AuthServiceBindings.ActorIdKey).to('username');
  1. Pass the actorIdKey argument in the constructor
@inject(AuditBindings.ActorIdKey, {optional: true})
public actorIdKey?: ActorId,

Making current user not mandatory

Incase you dont have current user binded in your application context and wish to log the activities within your application then in that case you can pass the actor id along with the options just like

await productRepo.create(product, {noAudit: false, actorId: 'userId'});
  • The package exposes a conditional mixin for your repository classes. Just extend your repository class with ConditionalAuditRepositoryMixin, for all those repositories where you need audit data based on condition whether ADD_AUDIT_LOG_MIXIN is set true. See an example below. For a model Group, here we are extending the GroupRepository with AuditRepositoryMixin.
import {repository} from '@loopback/repository';
import {Group, GroupRelations} from '../models';
import {PgdbDataSource} from '../datasources';
import {inject, Getter, Constructor} from '@loopback/core';
import {AuthenticationBindings, IAuthUser} from 'loopback4-authentication';
import {
  ConditionalAuditRepositoryMixin,
  AuditLogRepository,
} from '@sourceloop/audit-log';

const groupAuditOpts: IAuditMixinOptions = {
  actionKey: 'Group_Logs',
};

export class GroupRepository extends ConditionalAuditRepositoryMixin(
  DefaultUserModifyCrudRepository<
    Group,
    typeof Group.prototype.id,
    GroupRelations
  >,
  groupAuditOpts,
) {
  constructor(
    @inject('datasources.pgdb') dataSource: PgdbDataSource,
    @inject.getter(AuthenticationBindings.CURRENT_USER)
    public getCurrentUser: Getter<IAuthUser>,
    @repository.getter('AuditLogRepository')
    public getAuditLogRepository: Getter<AuditLogRepository>,
  ) {
    super(Group, dataSource, getCurrentUser);
  }
}

Using with Sequelize ORM

This extension provides support to both juggler (the default loopback ORM) and sequelize.

If your loopback project is already using SequelizeCrudRepository from @loopback/sequelize or equivalent add on repositories from sourceloop packages like SequelizeUserModifyCrudRepository. You'll need to make just two changes:

  1. The import statements should have the suffix /sequelize, like below:
import {repository} from '@loopback/repository';
import {Group, GroupRelations} from '../models';
import {PgdbDataSource} from '../datasources';
import {inject, Getter, Constructor} from '@loopback/core';
import {AuthenticationBindings, IAuthUser} from 'loopback4-authentication';
import {AuditRepositoryMixin} from '@sourceloop/audit-log';
import {AuditLogRepository as SequelizeAuditLogRepository} from '@sourceloop/auidt-log/sequelize';

const groupAuditOpts: IAuditMixinOptions = {
  actionKey: 'Group_Logs',
};

export class GroupRepository extends AuditRepositoryMixin<
  Group,
  typeof Group.prototype.id,
  GroupRelations,
  string,
  Constructor<
    DefaultCrudRepository<Group, typeof Group.prototype.id, GroupRelations>
  >,
  AuditLog,
  SequelizeAuditLogRepository
>(DefaultCrudRepository, groupAuditOpts) {
  constructor(
    @inject('datasources.pgdb') dataSource: PgdbDataSource,
    @inject.getter(AuthenticationBindings.CURRENT_USER)
    public getCurrentUser: Getter<IAuthUser>,
    @repository.getter(AuditLogRepository)
    public getAuditLogRepository: Getter<SequelizeAuditLogRepository>,
  ) {
    super(Group, dataSource, getCurrentUser);
  }
}

Also add the following to your application.ts file to bind the Sequelize repository

import {AuditLog} from '@sourceloop/auidt-log/';
import {AuditLogRepository} from '@sourceloop/audit-log/sequelize';

this.repositories = [AuditLogRepository<AuditLog>];

Feedback

If you've noticed a bug or have a question or have a feature request, search the issue tracker to see if someone else in the community has already created a ticket. If not, go ahead and make one! All feature requests are welcome. Implementation time may vary. Feel free to contribute the same, if you can. If you think this extension is useful, please star it. Appreciation really helps in keeping this project alive.

Contributing

Please read CONTRIBUTING.md for details on the process for submitting pull requests to us.

Code of conduct

Code of conduct guidelines here.

License

MIT

changelog

Release v8.0.6 April 21, 2025

Welcome to the April 21, 2025 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

  • :- fix(core): make model and respository customizable was commited on April 21, 2025 by yeshamavani

      • fix(core): make model and resposiory customizable
    • now user can use the default as well as their custom respository

    • GH-121

      • fix(core): readme in docs folder also updated
    • both the readme have to be in sync

    • GH-121

      • feat(mixin): make model and repository customizable
    • update the docs

    • GH-121


Clink on the above links to understand the changes in detail.


Release v8.0.5 January 7, 2025

Welcome to the January 7, 2025 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v8.0.4 December 20, 2024

Welcome to the December 20, 2024 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

  • :- chore(deps): core version update was commited on December 20, 2024 by Sunny Tyagi

      • chore(deps): core version update
    • core version update

    • gh-0

      • chore(deps): core update
    • core update

    • 0

      • chore(deps): jsdom update
    • jsdom update

    • 0

Clink on the above links to understand the changes in detail.


Release v8.0.3 December 17, 2024

Welcome to the December 17, 2024 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v8.0.2 June 4, 2024

Welcome to the June 4, 2024 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v8.0.1 May 15, 2024

Welcome to the May 15, 2024 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v5.2.0 August 7, 2023

Welcome to the August 7, 2023 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

  • Make actor field selection configurable :- feat(mixin): making the actor field configurable was commited on August 7, 2023 by yeshamavani

      • feat(mixin): feat(mixin): making the actor field configurable
    • added a key to that can be bounded to key of user that can be set as actor

    • GH-68

    • GH-68

      • feat(mixin): docs(mixin): add docs about how to configure actor id key
    • steps explaining how to pass the actor id via the repository constructor to

    • change its value

    • GH-68

    • GH-68

      • feat(mixin): added delete all hard and delete by id hard
    • in case current user is not available then can be passed through options

    • GH-68

      • feat(mixin): making the actor field configurable
    • adding a separate function for actor to avoid repetition

    • GH-68

      • feat(mixin): making actor id configurable
    • get actor from a private method

    • GH-68

  • :- was commited on August 1, 2023 by Shubham P
  • :- was commited on August 1, 2023 by Shubham P

Clink on the above links to understand the changes in detail.


Release v5.1.2 July 14, 2023

Welcome to the July 14, 2023 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v5.1.1 June 7, 2023

Welcome to the June 7, 2023 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v5.1.0 May 25, 2023

Welcome to the May 25, 2023 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v4.0.1 April 25, 2023

Welcome to the April 25, 2023 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v4.0.0 April 25, 2023

Welcome to the April 25, 2023 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

  • Add Audit Log Mixin Wrapper Around Audit Log Mixin :- feat(mixin): add conditional audit repository mixin was commited on April 25, 2023 by Sunny Tyagi

    • To be used when the actual audit mixin is to be applied conditionally from the

    • flag from the environment variables

    • rather than the code.

    • BREAKING CHANGE:

    • Audit Repository Mixin return type changed and now is being

    • returned as an abstract class. This

    • doesn't affect 99% of the users because in

    • crud repositories this mixin is already applied on the base class. Only those

    • who are directly assigning the mixin-ed class to some variable will have the

    • type error showing them.

    • GH-57

Clink on the above links to understand the changes in detail.


Release v3.2.3 April 24, 2023

Welcome to the April 24, 2023 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v3.2.2 March 13, 2023

Welcome to the March 13, 2023 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v3.2.1 February 17, 2023

Welcome to the February 17, 2023 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

Clink on the above links to understand the changes in detail.


Release v3.2.0 January 10, 2023

Welcome to the January 10, 2023 release of loopback4-audit-log. There are many updates in this version that we hope you will like, the key highlights include:

  • :- feat(chore): custom change log was commited on January 9, 2023 by yeshamavani

      • feat(chore): custom change log
    • The change log will now have issues as well as commit for the change

    • this is customizable in the

    • md file

    • GH-39

      • feat(chore): now we will generate out custom changelog
    • using git-release-notes npm package for this

    • GH-39

Clink on the above links to understand the changes in detail.


3.1.6 (2022-12-05)

3.1.5 (2022-11-03)

Bug Fixes

3.1.4 (2022-10-31)

3.1.3 (2022-09-09)

3.1.2 (2022-06-24)

Bug Fixes

  • component: missing return type (fb9b16a), closes #0

3.1.1 (2022-06-17)

3.1.0 (2022-05-26)

Features