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

fix: improve ts types #227

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
6 changes: 3 additions & 3 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function makeClient (app: Application, _options?: Partial<ClientOptions>): Authe
const authManagement = app.service(path);

const client: AuthenticationManagementClient = {
checkUnique: async (identifyUser: IdentifyUser, ownId: NullableId, ifErrMsg?: boolean) => {
checkUnique: async (identifyUser: IdentifyUser, ownId?: NullableId, ifErrMsg?: boolean) => {
await authManagement.create({
action: 'checkUnique',
value: identifyUser,
Expand Down Expand Up @@ -129,7 +129,7 @@ function makeClient (app: Application, _options?: Partial<ClientOptions>): Authe
try {
if (!user || !user.isVerified) {
await app.logout();
return cb(new Error(user ? 'User\'s email is not verified.' : 'No user returned.'));
return cb && cb(new Error(user ? 'User\'s email is not verified.' : 'No user returned.'));
}

if (cb) {
Expand All @@ -140,7 +140,7 @@ function makeClient (app: Application, _options?: Partial<ClientOptions>): Authe
return user;
} catch (err) {
if (!cbCalled && cb) {
cb(err);
cb(err as Error);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/hash-password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export async function hashPassword (
field: string
): Promise<string> {
if (!field) throw new Error('Field is missing');
const context = {
const context: Partial<HookContext> = {
type: 'before',
data: { [field]: password },
params: { provider: null },
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/sanitize-user-for-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { cloneObject } from './clone-object';
import type { User } from '../types';

export function sanitizeUserForClient (
_user: User
_user: Partial<User>
): Record<string, unknown> {
const user = cloneObject(_user);

Expand Down
2 changes: 1 addition & 1 deletion src/helpers/sanitize-user-for-notifier.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { cloneObject } from './clone-object';
import type { User } from '../types';

export function sanitizeUserForNotifier (_user: User): Record<string, unknown> {
export function sanitizeUserForNotifier (_user: Partial<User>): Record<string, unknown> {
const user = cloneObject(_user);
delete user.password;
return user;
Expand Down
3 changes: 3 additions & 0 deletions src/helpers/typescript.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function typedObjectKeys<T extends object>(o: T): Array<keyof T> {
return Object.keys(o) as Array<keyof T>;
}
5 changes: 3 additions & 2 deletions src/hooks/add-verification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ export function addVerification <H extends HookContext = HookContext>(
);

return context;
} catch (err) {
throw new GeneralError(err);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
throw new GeneralError(err?.message);
}
};
}
4 changes: 2 additions & 2 deletions src/hooks/remove-verification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ export function removeVerification <H extends HookContext = HookContext> (
return (context: H): H => {
checkContext(context, 'after');
// Retrieve the items from the hook
const items: User | User[] = getItems(context);
if (!items) return;
const items: Partial<User> | Partial<User>[] = getItems(context);
if (!items) return context;
const isArray = Array.isArray(items);
const users = (isArray ? items : [items]);

Expand Down
14 changes: 8 additions & 6 deletions src/methods/check-unique.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BadRequest } from '@feathersjs/errors';
import makeDebug from 'debug';

import { typedObjectKeys } from '../helpers/typescript';
import type { NullableId, Params } from '@feathersjs/feathers';
import type {
CheckUniqueOptions,
Expand Down Expand Up @@ -33,10 +34,10 @@ export default async function checkUnique (
} = options;

const usersService = app.service(service);
const usersServiceId = usersService.id;
const usersServiceId = usersService.id!;
const errProps = [];

const keys = Object.keys(identifyUser).filter(
const keys = typedObjectKeys(identifyUser).filter(
key => identifyUser[key] != null
);

Expand All @@ -59,16 +60,17 @@ export default async function checkUnique (
errProps.push(prop);
}
}
} catch (err) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
throw new BadRequest(
meta?.noErrMsg ? null : 'checkUnique unexpected error.',
{ errors: { msg: err.message, $className: 'unexpected' } }
{ errors: { msg: err?.message, $className: 'unexpected' } }
);
}

if (errProps.length) {
const errs = {};
errProps.forEach(prop => { errs[prop] = 'Already taken.'; });
const errs: Record<string, string> = {};
errProps.forEach((prop ) => { errs[prop] = 'Already taken.'; });

throw new BadRequest(
meta?.noErrMsg ? null : 'Values already taken.',
Expand Down
2 changes: 1 addition & 1 deletion src/methods/identity-change.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default async function identityChange (
}

const usersService = options.app.service(options.service);
const usersServiceId = usersService.id;
const usersServiceId = usersService.id!;
const {
delay,
identifyUserProps,
Expand Down
2 changes: 1 addition & 1 deletion src/methods/password-change.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default async function passwordChange (
} = options;

const usersService = app.service(service);
const usersServiceId = usersService.id;
const usersServiceId = usersService.id!;

ensureValuesAreStrings(oldPassword, password);
ensureObjPropsValid(identifyUser, identifyUserProps);
Expand Down
4 changes: 2 additions & 2 deletions src/methods/resend-verify-signup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const debug = makeDebug('authLocalMgnt:resendVerifySignup');
export default async function resendVerifySignup (
options: ResendVerifySignupOptions,
identifyUser: IdentifyUser,
notifierOptions: NotifierOptions,
notifierOptions?: NotifierOptions,
params?: Params
): Promise<SanitizedUser> {
debug('identifyUser=', identifyUser);
Expand All @@ -46,7 +46,7 @@ export default async function resendVerifySignup (
} = options;

const usersService = app.service(service);
const usersServiceId = usersService.id;
const usersServiceId = usersService.id!;

ensureObjPropsValid(identifyUser,
identifyUserProps.concat('verifyToken', 'verifyShortToken')
Expand Down
7 changes: 4 additions & 3 deletions src/methods/reset-password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
hashPassword,
notify
} from '../helpers';
import { typedObjectKeys } from '../helpers/typescript';
import type { Id, Params } from '@feathersjs/feathers';

import type {
Expand Down Expand Up @@ -90,7 +91,7 @@ async function resetPassword (
} = options;

const usersService = app.service(service);
const usersServiceId = usersService.id;
const usersServiceId = usersService.id!;
let users;

if (tokens.resetToken) {
Expand All @@ -114,7 +115,7 @@ async function resetPassword (
const user = getUserData(users, checkProps);

// compare all tokens (hashed)
const tokenChecks = Object.keys(tokens).map(async key => {
const tokenChecks = typedObjectKeys(tokens).map(async key => {
if (reuseResetToken) {
// Comparing token directly as reused resetToken is not hashed
if (tokens[key] !== user[key]) {
Expand All @@ -124,7 +125,7 @@ async function resetPassword (
}
} else {
return await comparePasswords(
tokens[key],
tokens[key]!,
user[key] as string,
() =>
new BadRequest(
Expand Down
2 changes: 1 addition & 1 deletion src/methods/send-reset-pwd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export default async function sendResetPwd (
} = options;

const usersService = app.service(service);
const usersServiceId = usersService.id;
const usersServiceId = usersService.id!;

ensureObjPropsValid(identifyUser, identifyUserProps);

Expand Down
5 changes: 3 additions & 2 deletions src/methods/verify-signup-set-password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
isDateAfterNow,
notify
} from '../helpers';
import { typedObjectKeys } from '../helpers/typescript';
import type { Id, Params } from '@feathersjs/feathers';
import type { VerifyChanges } from '..';

Expand Down Expand Up @@ -91,7 +92,7 @@ async function verifySignupSetPassword (
} = options;

const usersService = app.service(service);
const usersServiceId = usersService.id;
const usersServiceId = usersService.id!;

const users = await usersService.find({
...params,
Expand All @@ -103,7 +104,7 @@ async function verifySignupSetPassword (
'verifyNotExpired'
]);

if (!Object.keys(tokens).every((key) => tokens[key] === user[key])) {
if (!typedObjectKeys(tokens).every((key) => tokens[key] === user[key])) {
await eraseVerifyProps(user, user.isVerified, params);

throw new BadRequest(
Expand Down
5 changes: 3 additions & 2 deletions src/methods/verify-signup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
notify,
isDateAfterNow
} from '../helpers';
import { typedObjectKeys } from '../helpers/typescript';
import type { Id, Params } from '@feathersjs/feathers';

import type {
Expand Down Expand Up @@ -82,7 +83,7 @@ async function verifySignup (
} = options;

const usersService = app.service(service);
const usersServiceId = usersService.id;
const usersServiceId = usersService.id!;

const users = await usersService.find(
{
Expand All @@ -98,7 +99,7 @@ async function verifySignup (

let userErasedVerify: User;

if (!Object.keys(tokens).every(key => tokens[key] === user[key])) {
if (!typedObjectKeys(tokens).every((key) => tokens[key] === user[key])) {
userErasedVerify = await eraseVerifyProps(user, user.isVerified);

throw new BadRequest(
Expand Down
2 changes: 1 addition & 1 deletion src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const defaultPath = 'authManagement';
export const optionsDefault: AuthenticationManagementServiceOptions = {
service: '/users', // need exactly this for test suite
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
notifier: async (type: NotificationType, user: User, notifierOptions) => {},
notifier: async (type: NotificationType, user: Partial<User>, notifierOptions) => {},
longTokenLen: 15, // token's length will be twice this
shortTokenLen: 6,
shortTokenDigits: true,
Expand Down
7 changes: 5 additions & 2 deletions src/services/AuthenticationManagementBase.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { MethodNotAllowed } from '@feathersjs/errors';
import type { Application, Params } from '@feathersjs/feathers';

export abstract class AuthenticationManagementBase<T, R, O> {
publish: unknown;
publish: undefined | ((fn: ((...any: any[]) => unknown)) => void);
app: Application;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore not defined in constructor but is used.
options: O;

abstract _create (data: T, params?: Params): Promise<R>;
Expand Down Expand Up @@ -31,7 +34,7 @@ export abstract class AuthenticationManagementBase<T, R, O> {
}

async setup (): Promise<void> {
if (typeof this.publish === 'function') {
if (typeof this.publish === 'function') {
this.publish(() => null);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export interface AuthenticationManagementServiceOptions {
* @default 'password' */
passwordField: string
/** Pass params from f-a-m service to `/users` service */
passParams: (params) => Params | Promise<Params>
passParams?: (params: any) => Params | Promise<Params>
}

export type AuthenticationManagementSetupOptions = AuthenticationManagementServiceOptions & { path: string };
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"sourceMap": false,
"declaration": true,
"strictNullChecks": false,
"noImplicitAny": true,
},
"include": [
"src/**/*"
Expand Down
Loading