Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: refactor logger #284

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ import { Authentication } from './auth.js';
import { IAuthentication } from './interfaces/Authentication.js';
import { RadiusServer } from './radius/RadiusServer.js';
import { ConsoleLogger, LogLevel } from './logger/ConsoleLogger.js';
import { Logger } from './logger/Logger.js';

function isValidLogLevel(debug?: string): debug is LogLevel | undefined {
switch (debug) {
@@ -23,14 +24,15 @@ function isValidLogLevel(debug?: string): debug is LogLevel | undefined {
}

(async () => {
const logger = new ConsoleLogger(
const consoleLogger = new ConsoleLogger(
(isValidLogLevel(process.env.LOGLEVEL) && process.env.LOGLEVEL) ||
(isValidLogLevel(config.loglevel) && config.loglevel) ||
(process.env.NODE_ENV === 'development' && LogLevel.Debug) ||
LogLevel.Log
);
Logger.registerLogger(consoleLogger);

const ctxLogger = logger.context('app');
const logger = new Logger('app');

const { argv } = yargs(hideBin(process.argv))
.usage('NODE RADIUS Server\nUsage: radius-server')
@@ -49,32 +51,32 @@ function isValidLogLevel(debug?: string): debug is LogLevel | undefined {
argv: { port?: number; secret?: string; authentication?: string; authenticationOptions?: any };
};

ctxLogger.log(`Listener Port: ${argv.port || 1812}`);
ctxLogger.log(`RADIUS Secret: ${argv.secret}`);
ctxLogger.log(`Auth ${argv.authentication}`);
ctxLogger.debug(`Auth Config: ${JSON.stringify(argv.authenticationOptions, undefined, 3)}`);
logger.log(`Listener Port: ${argv.port || 1812}`);
logger.log(`RADIUS Secret: ${argv.secret}`);
logger.log(`Auth ${argv.authentication}`);
logger.debug(`Auth Config: ${JSON.stringify(argv.authenticationOptions, undefined, 3)}`);

// configure auth mechanism
let auth: IAuthentication;
try {
const AuthMechanism = (await import(`./auth/${config.authentication}.js`))[
config.authentication
];
auth = new AuthMechanism(config.authenticationOptions, logger);
auth = new AuthMechanism(config.authenticationOptions);
} catch (err) {
ctxLogger.error('cannot load auth mechanisms', config.authentication);
logger.error('cannot load auth mechanisms', config.authentication);
throw err;
}
// start radius server
const authentication = new Authentication(auth, logger);
const authentication = new Authentication(auth);

const server = new RadiusServer({
secret: config.secret,
port: config.port,
address: '0.0.0.0',
tlsOptions: config.certificate,
authentication,
logger,
logger: consoleLogger,
});

// start server
10 changes: 4 additions & 6 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
import NodeCache from 'node-cache';
import { Cache, ExpirationStrategy, MemoryStorage } from '@hokify/node-ts-cache';
import { IAuthentication } from './interfaces/Authentication.js';
import { IContextLogger, ILogger } from './interfaces/Logger.js';
import { Logger } from './logger/Logger.js';

const cacheStrategy = new ExpirationStrategy(new MemoryStorage());
/**
* this is just a simple abstraction to provide
* an application layer for caching credentials
*/
export class Authentication implements IAuthentication {
private cache = new NodeCache();
private logger = new Logger('Authentication');

private logger: IContextLogger;
private cache = new NodeCache();

constructor(private authenticator: IAuthentication, logger: ILogger) {
this.logger = logger.context('Authentication');
}
constructor(private authenticator: IAuthentication) {}

@Cache(cacheStrategy, { ttl: 60000 })
async authenticate(username: string, password: string): Promise<boolean> {
11 changes: 5 additions & 6 deletions src/auth/GoogleLDAPAuth.ts
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@ import ldapjs, { ClientOptions } from 'ldapjs';
import * as tls from 'tls';
import * as fs from 'fs';
import { IAuthentication } from '../interfaces/Authentication.js';
import { IContextLogger, ILogger } from '../interfaces/Logger.js';
import { Logger } from '../logger/Logger.js';

const usernameFields = ['posixUid', 'mail'];

@@ -27,6 +27,8 @@ interface IGoogleLDAPAuthOptions {
}

export class GoogleLDAPAuth implements IAuthentication {
private logger = new Logger('GoogleLDAPAuth');

private base: string;

private config: ClientOptions;
@@ -35,12 +37,9 @@ export class GoogleLDAPAuth implements IAuthentication {

private dnsFetch: Promise<{ [key: string]: string }> | undefined;

private logger: IContextLogger;

constructor(config: IGoogleLDAPAuthOptions, logger: ILogger) {
constructor(config: IGoogleLDAPAuthOptions) {
this.base = config.base;
this.searchBase = config.searchBase || `ou=users,${this.base}`;
this.logger = logger.context('GoogleLDAPAuth');

const tlsOptions = {
key: fs.readFileSync(config.tls.keyFile),
@@ -114,7 +113,7 @@ export class GoogleLDAPAuth implements IAuthentication {
}, 60 * 60 * 12 * 1000); // reset cache after 12h
return dnResult;
} catch (err) {
console.error('dns fetch err', err);
this.logger.error('dns fetch err', err);
// retry dns fetch next time
this.dnsFetch = undefined;
throw err;
9 changes: 4 additions & 5 deletions src/auth/HTTPAuth.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import fetch from 'node-fetch';
import { IAuthentication } from '../interfaces/Authentication.js';
import { IContextLogger, ILogger } from '../interfaces/Logger.js';
import { Logger } from '../logger/Logger.js';

interface IHTTPAuthOptions {
url: string;
}

export class HTTPAuth implements IAuthentication {
private url: string;
private logger = new Logger('HTTPAuth');

private logger: IContextLogger;
private url: string;

constructor(config: IHTTPAuthOptions, logger: ILogger) {
constructor(config: IHTTPAuthOptions) {
this.url = config.url;
this.logger = logger.context('HTTPAuth');
}

async authenticate(username: string, password: string) {
11 changes: 5 additions & 6 deletions src/auth/IMAPAuth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as imaps from 'imap-simple';
import { IAuthentication } from '../interfaces/Authentication.js';
import { IContextLogger, ILogger } from '../interfaces/Logger.js';
import { Logger } from '../logger/Logger.js';

interface IIMAPAuthOptions {
host: string;
@@ -10,6 +10,8 @@ interface IIMAPAuthOptions {
}

export class IMAPAuth implements IAuthentication {
private logger = new Logger('IMAPAuth');

private host: string;

private port = 143;
@@ -18,9 +20,7 @@ export class IMAPAuth implements IAuthentication {

private validHosts?: string[];

private logger: IContextLogger;

constructor(config: IIMAPAuthOptions, logger: ILogger) {
constructor(config: IIMAPAuthOptions) {
this.host = config.host;
if (config.port !== undefined) {
this.port = config.port;
@@ -31,14 +31,13 @@ export class IMAPAuth implements IAuthentication {
if (config.validHosts !== undefined) {
this.validHosts = config.validHosts;
}
this.logger = logger.context('IMAPAuth');
}

async authenticate(username: string, password: string) {
if (this.validHosts) {
const domain = username.split('@').pop();
if (!domain || !this.validHosts.includes(domain)) {
this.logger.log('invalid or no domain in username', username, domain);
this.logger.log(`invalid or no domain in username ${username} ${domain}`);
return false;
}
}
9 changes: 4 additions & 5 deletions src/auth/LDAPAuth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as LdapAuth from 'ldapauth-fork';
import * as fs from 'fs';
import { IAuthentication } from '../interfaces/Authentication.js';
import { IContextLogger, ILogger } from '../interfaces/Logger.js';
import { Logger } from '../logger/Logger.js';

interface ILDAPAuthOptions {
/** ldap url
@@ -28,17 +28,16 @@ interface ILDAPAuthOptions {
}

export class LDAPAuth implements IAuthentication {
private ldap: LdapAuth;
private logger = new Logger('LDAPAuth');

private logger: IContextLogger;
private ldap: LdapAuth;

constructor(config: ILDAPAuthOptions, logger: ILogger) {
constructor(config: ILDAPAuthOptions) {
const tlsOptions = {
key: fs.readFileSync(config.tls.keyFile),
cert: fs.readFileSync(config.tls.certFile),
...config.tlsOptions,
};
this.logger = logger.context('LDAPAuth');

this.ldap = new LdapAuth({
url: config.url,
11 changes: 5 additions & 6 deletions src/auth/SMTPAuth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { SMTPClient } from 'smtp-client';
import { IAuthentication } from '../interfaces/Authentication.js';
import { IContextLogger, ILogger } from '../interfaces/Logger.js';
import { Logger } from '../logger/Logger.js';

interface ISMTPAuthOptions {
host: string;
@@ -10,6 +10,8 @@ interface ISMTPAuthOptions {
}

export class SMTPAuth implements IAuthentication {
private logger = new Logger('SMTPAuth');

private host: string;

private port = 25;
@@ -18,10 +20,7 @@ export class SMTPAuth implements IAuthentication {

private validHosts?: string[];

private logger: IContextLogger;

constructor(options: ISMTPAuthOptions, logger: ILogger) {
this.logger = logger.context('SMTPAuth');
constructor(options: ISMTPAuthOptions) {
this.host = options.host;

if (options.port !== undefined) {
@@ -41,7 +40,7 @@ export class SMTPAuth implements IAuthentication {
if (this.validHosts) {
const domain = username.split('@').pop();
if (!domain || !this.validHosts.includes(domain)) {
this.logger.log('invalid or no domain in username', username, domain);
this.logger.log(`invalid or no domain in username ${username} ${domain}`);
return false;
}
}
8 changes: 4 additions & 4 deletions src/auth/StaticAuth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { IAuthentication } from '../interfaces/Authentication.js';
import { IContextLogger, ILogger } from '../interfaces/Logger.js';
import { Logger } from '../logger/Logger.js';

interface IStaticAuthOtions {
validCredentials: {
@@ -9,11 +9,11 @@ interface IStaticAuthOtions {
}

export class StaticAuth implements IAuthentication {
private logger = new Logger('StaticAuth');

private validCredentials: { username: string; password: string }[];
private logger: IContextLogger;

constructor(options: IStaticAuthOtions, logger: ILogger) {
this.logger = logger.context('StaticAuth');
constructor(options: IStaticAuthOtions) {
this.validCredentials = options.validCredentials;
}

10 changes: 8 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { IAuthentication } from './interfaces/Authentication.js';
import { RadiusServerOptions } from './interfaces/RadiusServerOptions.js';
import { IRadiusServerOptions } from './interfaces/RadiusServerOptions.js';
import { RadiusServer } from './radius/RadiusServer.js';
import { ILogger } from './interfaces/Logger.js';

export { IAuthentication as RadiusAuthentication, RadiusServerOptions, RadiusServer };
export {
IAuthentication as RadiusAuthentication,
IRadiusServerOptions as RadiusServerOptions,
RadiusServer,
ILogger as RadiusLogger,
};

/*
Export RadiusServer and relevant interfaces, so it can be used in other projects (e.g. a NestJS backend)
19 changes: 5 additions & 14 deletions src/interfaces/Logger.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,7 @@
export interface ILogger {
log(context: string, message: unknown, ...optionalParams: any[]): void;
error(context: string, message: unknown, ...optionalParams: any[]): void;
warn(context: string, message: unknown, ...optionalParams: any[]): void;
debug(context: string, message: unknown, ...optionalParams: any[]): void;
verbose?(context: string, message: unknown, ...optionalParams: any[]): void;
context(context: string): IContextLogger;
}

export interface IContextLogger extends ILogger {
log(message: unknown, ...optionalParams: any[]): void;
error(message: unknown, ...optionalParams: any[]): void;
warn(message: unknown, ...optionalParams: any[]): void;
debug(message: unknown, ...optionalParams: any[]): void;
verbose?(message: unknown, ...optionalParams: any[]): void;
log(context: string, message: string, ...optionalParams: unknown[]): void;
error(context: string, message: string, ...optionalParams: unknown[]): void;
warn(context: string, message: string, ...optionalParams: unknown[]): void;
debug(context: string, message: string, ...optionalParams: unknown[]): void;
verbose(context: string, message: string, ...optionalParams: unknown[]): void;
}
14 changes: 3 additions & 11 deletions src/interfaces/RadiusServerOptions.ts
Original file line number Diff line number Diff line change
@@ -3,21 +3,13 @@ import { IAuthentication } from './Authentication.js';
import { ILogger } from './Logger.js';
import { LogLevel } from '../logger/ConsoleLogger.js';

export type RadiusServerOptions = IRadiusServerOptions &
(
| {
logger?: ILogger;
}
| {
logLevel: LogLevel;
}
);

interface IRadiusServerOptions {
export interface IRadiusServerOptions {
secret: string;
tlsOptions: SecureContextOptions;
authentication: IAuthentication;
vlan?: number;
port?: number;
address?: string;
logger?: ILogger;
logLevel?: LogLevel;
}
Loading