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/7549: add dynamic find function name for auth entity service #306

Merged
merged 2 commits into from
Dec 6, 2023
Merged
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
4 changes: 2 additions & 2 deletions plugins/auth-core/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion plugins/auth-core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@amplication/plugin-auth-core",
"version": "2.0.5",
"version": "2.0.6",
"description": "set auth for Amplication build",
"main": "dist/index.js",
"nx": {},
14 changes: 8 additions & 6 deletions plugins/auth-core/src/core/create-auth-service-spec.ts
Original file line number Diff line number Diff line change
@@ -13,18 +13,19 @@ import {
removeTSClassDeclares,
} from "../util/ast";
import { builders, namedTypes } from "ast-types";
import { camelCase } from "lodash";

const authServiceSpecPath = join(
templatesPath,
"auth.service.spec.template.ts"
"auth.service.spec.template.ts",
);

export async function createAuthServiceSpec(
dsgContext: DsgContext
dsgContext: DsgContext,
): Promise<Module> {
const { entities, resourceInfo, serverDirectories } = dsgContext;
const authEntity = entities?.find(
(x) => x.name === resourceInfo?.settings.authEntityName
(x) => x.name === resourceInfo?.settings.authEntityName,
);
if (!authEntity) {
dsgContext.logger.error(AUTH_ENTITY_LOG_ERROR);
@@ -40,18 +41,19 @@ export async function createAuthServiceSpec(

const entityServiceImport = importNames(
[authServiceNameId],
`../${entityNameToLower}/${entityNameToLower}.service`
`../${entityNameToLower}/${entityNameToLower}.service`,
);

addImports(
template,
[entityServiceImport].filter(
(x) => x //remove nulls and undefined
) as namedTypes.ImportDeclaration[]
(x) => x, //remove nulls and undefined
) as namedTypes.ImportDeclaration[],
);

const templateMapping = {
ENTITY_SERVICE: builders.identifier(entityServiceName),
FIND_ONE_FUNCTION: builders.identifier(`${camelCase(authEntity?.name)}`),
};

interpolate(template, templateMapping);
10 changes: 5 additions & 5 deletions plugins/auth-core/src/templates/auth.service.spec.template.ts
Original file line number Diff line number Diff line change
@@ -32,7 +32,7 @@ const USER: any = {
const SIGN_TOKEN = "SIGN_TOKEN";

const authEntityService = {
findOne(args: { where: { username: string } }): any | null {
FIND_ONE_FUNCTION(args: { where: { username: string } }): any | null {
if (args.where.username === VALID_CREDENTIALS.username) {
return USER;
}
@@ -86,8 +86,8 @@ describe("AuthService", () => {
await expect(
service.validateUser(
VALID_CREDENTIALS.username,
VALID_CREDENTIALS.password
)
VALID_CREDENTIALS.password,
),
).resolves.toEqual({
username: USER.username,
roles: USER.roles,
@@ -99,8 +99,8 @@ describe("AuthService", () => {
await expect(
service.validateUser(
INVALID_CREDENTIALS.username,
INVALID_CREDENTIALS.password
)
INVALID_CREDENTIALS.password,
),
).resolves.toBe(null);
});
});
4 changes: 2 additions & 2 deletions plugins/auth-jwt/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion plugins/auth-jwt/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@amplication/plugin-auth-jwt",
"version": "1.4.5",
"version": "1.4.6",
"description": "set jwt as provider for Amplication build",
"main": "dist/index.js",
"nx": {},
2 changes: 2 additions & 0 deletions plugins/auth-jwt/src/core/create-jwt-strategy-base.ts
Original file line number Diff line number Diff line change
@@ -16,6 +16,7 @@ import {
} from "../util/ast";
import { builders, namedTypes } from "ast-types";
import { print } from "@amplication/code-gen-utils";
import { camelCase } from "lodash";

const jwtStrategyBasePath = join(
templatesPath,
@@ -76,6 +77,7 @@ async function mapJwtStrategyTemplate(
const templateMapping = {
ENTITY_NAME_INFO: builders.identifier(`${authEntity.name}Info`),
ENTITY_SERVICE: builders.identifier(`${entityNameToLower}Service`),
FIND_ONE_FUNCTION: builders.identifier(`${camelCase(authEntity?.name) }`)
};

const filePath = `${serverDirectories.authDirectory}/jwt/base/${fileName}`;
2 changes: 2 additions & 0 deletions plugins/auth-jwt/src/core/create-jwt-strategy-spec.ts
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ import {
} from "../util/ast";
import { builders, namedTypes } from "ast-types";
import { print } from "@amplication/code-gen-utils";
import { camelCase } from "lodash";

const jwtStrategySpecPath = join(
templatesPath,
@@ -65,6 +66,7 @@ async function mapJwtStrategySpecTemplate(

const templateMapping = {
ENTITY_SERVICE: builders.identifier(`${entityServiceName}`),
FIND_ONE_FUNCTION: builders.identifier(`${camelCase(authEntity?.name) }`)
};

const filePath = `${serverDirectories.srcDirectory}/tests/auth/jwt/${fileName}`;
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@
import { IAuthStrategy } from "../../IAuthStrategy";

declare class ENTITY_NAME_INFO {}
declare class ENTITY_SERVICE {}

Check failure on line 7 in plugins/auth-jwt/src/templates/jwt.strategy.template.base.ts

GitHub Actions / Continuous Integration

'ENTITY_SERVICE' is defined but never used

export class JwtStrategyBase
extends PassportStrategy(Strategy)
@@ -20,7 +20,7 @@

async validate(payload: ENTITY_NAME_INFO): Promise<ENTITY_NAME_INFO> {
const { username } = payload;
const user = await this.ENTITY_SERVICE.findOne({
const user = await this.ENTITY_SERVICE.FIND_ONE_FUNCTION({
where: { username },
});
if (!user) {
4 changes: 2 additions & 2 deletions plugins/auth-jwt/src/templates/jwt.strategy.template.spec.ts
Original file line number Diff line number Diff line change
@@ -8,11 +8,11 @@ describe("Testing the jwtStrategyBase.validate()", () => {
const userService = mock<ENTITY_SERVICE>();
const jwtStrategy = new JwtStrategyBase("Secrete", userService);
beforeEach(() => {
userService.findOne.mockClear();
userService.FIND_ONE_FUNCTION.mockClear();
});
it("should throw UnauthorizedException where there is no user", async () => {
//ARRANGE
userService.findOne
userService.FIND_ONE_FUNCTION
.calledWith({ where: { username: TEST_USER.username } })
.mockReturnValue(Promise.resolve(null));
//ACT

Unchanged files with check annotations Beta

/* eslint-disable import/no-unresolved */

Check failure on line 1 in plugins/auth-jwt/src/static/auth/base/token.service.base.ts

GitHub Actions / Continuous Integration

Definition for rule 'import/no-unresolved' was not found
import { Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { INVALID_PASSWORD_ERROR, INVALID_USERNAME_ERROR } from "../constants";
canActivate(
context: ExecutionContext
): boolean | Promise<boolean> | Observable<any> {

Check failure on line 15 in plugins/auth-jwt/src/static/auth/defaultAuth.guard.ts

GitHub Actions / Continuous Integration

Unexpected any. Specify a different type
const isPublic = this.reflector.get<boolean>(
IS_PUBLIC_KEY,
context.getHandler()
it("should reject when username missing", () => {
const result = tokenServiceBase.createToken({
id: VALID_ID,
//@ts-ignore

Check failure on line 31 in plugins/auth-jwt/src/static/tests/auth/token.service.spec.ts

GitHub Actions / Continuous Integration

Use "@ts-expect-error" instead of "@ts-ignore", as "@ts-ignore" will do nothing if the following line is error-free
username: null,
password: VALID_CREDENTIALS.password,
});
const result = tokenServiceBase.createToken({
id: VALID_ID,
username: VALID_CREDENTIALS.username,
//@ts-ignore

Check failure on line 41 in plugins/auth-jwt/src/static/tests/auth/token.service.spec.ts

GitHub Actions / Continuous Integration

Use "@ts-expect-error" instead of "@ts-ignore", as "@ts-ignore" will do nothing if the following line is error-free
password: null,
});
return expect(result).rejects.toBe(INVALID_PASSWORD_ERROR);
return recast.visit(ast, {
visitIdentifier(path) {
const { name } = path.node;
if (mapping.hasOwnProperty(name)) {

Check failure on line 145 in plugins/auth-jwt/src/util/ast.ts

GitHub Actions / Continuous Integration

Do not access Object.prototype method 'hasOwnProperty' from target object
const replacement = mapping[name];
path.replace(replacement);
}
const contained: namedTypes.Identifier[] = [];
recast.visit(node, {
visitIdentifier(path) {
if (nameToIdentifier.hasOwnProperty(path.node.name)) {

Check failure on line 460 in plugins/auth-jwt/src/util/ast.ts

GitHub Actions / Continuous Integration

Do not access Object.prototype method 'hasOwnProperty' from target object
contained.push(path.node);
}
this.traverse(path);
namedTypes.ExpressionStatement
);
export function typedExpression<T>(type: { check(v: any): v is T }) {

Check failure on line 644 in plugins/auth-jwt/src/util/ast.ts

GitHub Actions / Continuous Integration

Unexpected any. Specify a different type
return (
strings: TemplateStringsArray,
...values: Array<namedTypes.ASTNode | namedTypes.ASTNode[] | string>
};
}
export function typedStatement<T>(type: { check(v: any): v is T }) {

Check failure on line 657 in plugins/auth-jwt/src/util/ast.ts

GitHub Actions / Continuous Integration

Unexpected any. Specify a different type
return (
strings: TemplateStringsArray,
...values: Array<namedTypes.ASTNode | namedTypes.ASTNode[] | string>
);
}
return decorator as any;

Check failure on line 810 in plugins/auth-jwt/src/util/ast.ts

GitHub Actions / Continuous Integration

Unexpected any. Specify a different type
}
export function addDecoratorsToClassDeclaration(