From 12a982a6bf0030571f8581ff4d1ed88f152e1554 Mon Sep 17 00:00:00 2001 From: "amplication[bot]" Date: Sat, 4 Nov 2023 16:32:16 +0000 Subject: [PATCH] Amplication build # clok9hyzk0hcekj01umajol2g Congratulations on your first commit with Amplication! We encourage you to continue exploring the many ways Amplication can supercharge your development. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If you find Amplication useful, please show your support and give our GitHub repo a star ⭐️ This simple action helps our open-source project grow and reach more developers like you. Thank you and happy coding! Build URL: [https://app.amplication.com/clok9exal0ecomi01bhkctmhv/clok9exka0ecrmi014g34bn4o/clok9hy1s0haskj01jpbldjwk/builds/clok9hyzk0hcekj01umajol2g](https://app.amplication.com/clok9exal0ecomi01bhkctmhv/clok9exka0ecrmi014g34bn4o/clok9hy1s0haskj01jpbldjwk/builds/clok9hyzk0hcekj01umajol2g) --- admin-ui/.dockerignore | 7 + admin-ui/.env | 2 + admin-ui/.gitignore | 23 ++ admin-ui/Dockerfile | 51 +++ admin-ui/README.md | 47 +++ admin-ui/configuration/nginx.conf | 11 + admin-ui/package.json | 60 ++++ admin-ui/public/favicon.ico | Bin 0 -> 6548 bytes admin-ui/public/index.html | 40 +++ admin-ui/public/logo192.png | Bin 0 -> 9721 bytes admin-ui/public/logo512.png | Bin 0 -> 17361 bytes admin-ui/public/manifest.json | 25 ++ admin-ui/public/robots.txt | 3 + admin-ui/src/App.scss | 59 ++++ admin-ui/src/App.tsx | 50 +++ admin-ui/src/Components/Pagination.tsx | 10 + admin-ui/src/Login.tsx | 117 +++++++ admin-ui/src/api/user/CreateUserArgs.ts | 5 + admin-ui/src/api/user/DeleteUserArgs.ts | 5 + admin-ui/src/api/user/UpdateUserArgs.ts | 7 + admin-ui/src/api/user/User.ts | 11 + admin-ui/src/api/user/UserCountArgs.ts | 5 + admin-ui/src/api/user/UserCreateInput.ts | 9 + admin-ui/src/api/user/UserFindManyArgs.ts | 9 + admin-ui/src/api/user/UserFindUniqueArgs.ts | 5 + .../src/api/user/UserListRelationFilter.ts | 7 + admin-ui/src/api/user/UserOrderByInput.ts | 12 + admin-ui/src/api/user/UserUpdateInput.ts | 9 + admin-ui/src/api/user/UserWhereInput.ts | 9 + admin-ui/src/api/user/UserWhereUniqueInput.ts | 3 + admin-ui/src/auth-provider/ra-auth-http.ts | 78 +++++ admin-ui/src/auth-provider/ra-auth-jwt.ts | 72 ++++ admin-ui/src/auth.ts | 34 ++ admin-ui/src/constants.ts | 2 + .../src/data-provider/graphqlDataProvider.ts | 28 ++ admin-ui/src/index.css | 26 ++ admin-ui/src/index.tsx | 19 ++ admin-ui/src/login.scss | 119 +++++++ admin-ui/src/pages/Dashboard.tsx | 12 + admin-ui/src/reportWebVitals.ts | 17 + admin-ui/src/setupTests.ts | 5 + admin-ui/src/theme/theme.ts | 33 ++ admin-ui/src/types.ts | 13 + admin-ui/src/user/EnumRoles.ts | 3 + admin-ui/src/user/RolesOptions.ts | 12 + admin-ui/src/user/UserCreate.tsx | 31 ++ admin-ui/src/user/UserEdit.tsx | 29 ++ admin-ui/src/user/UserList.tsx | 25 ++ admin-ui/src/user/UserShow.tsx | 24 ++ admin-ui/src/user/UserTitle.ts | 7 + admin-ui/src/user/roles.ts | 6 + admin-ui/src/util/BooleanFilter.ts | 4 + admin-ui/src/util/BooleanNullableFilter.ts | 4 + admin-ui/src/util/DateTimeFilter.ts | 10 + admin-ui/src/util/DateTimeNullableFilter.ts | 10 + admin-ui/src/util/FloatFilter.ts | 10 + admin-ui/src/util/FloatNullableFilter.ts | 10 + admin-ui/src/util/IntFilter.ts | 10 + admin-ui/src/util/IntNullableFilter.ts | 10 + admin-ui/src/util/JsonFilter.ts | 5 + admin-ui/src/util/JsonNullableFilter.ts | 5 + admin-ui/src/util/MetaQueryPayload.ts | 3 + admin-ui/src/util/QueryMode.ts | 4 + admin-ui/src/util/SortOrder.ts | 4 + admin-ui/src/util/StringFilter.ts | 16 + admin-ui/src/util/StringNullableFilter.ts | 15 + admin-ui/tsconfig.json | 21 ++ server/.dockerignore | 8 + server/.env | 10 + server/.gitignore | 5 + server/.prettierignore | 5 + server/Dockerfile | 68 ++++ server/README.md | 64 ++++ server/docker-compose.dev.yml | 29 ++ server/docker-compose.yml | 57 ++++ server/nest-cli.json | 6 + server/package.json | 75 ++++ server/prisma/schema.prisma | 19 ++ server/scripts/customSeed.ts | 17 + server/scripts/seed.ts | 49 +++ server/src/app.module.ts | 46 +++ server/src/auth/Credentials.ts | 21 ++ server/src/auth/IAuthStrategy.ts | 5 + server/src/auth/ITokenService.ts | 9 + server/src/auth/LoginArgs.ts | 12 + server/src/auth/UserInfo.ts | 14 + server/src/auth/abac.util.ts | 19 ++ server/src/auth/acl.module.ts | 7 + server/src/auth/auth.controller.ts | 15 + server/src/auth/auth.module.ts | 54 +++ server/src/auth/auth.resolver.ts | 23 ++ server/src/auth/auth.service.spec.ts | 114 +++++++ server/src/auth/auth.service.ts | 49 +++ server/src/auth/base/token.service.base.ts | 25 ++ server/src/auth/constants.ts | 2 + server/src/auth/defaultAuth.guard.ts | 27 ++ server/src/auth/gqlAC.guard.ts | 11 + server/src/auth/gqlDefaultAuth.guard.ts | 14 + server/src/auth/gqlUserRoles.decorator.ts | 19 ++ server/src/auth/jwt/base/jwt.strategy.base.ts | 40 +++ server/src/auth/jwt/jwt.strategy.ts | 14 + server/src/auth/jwt/jwtAuth.guard.ts | 3 + server/src/auth/jwt/jwtSecretFactory.ts | 16 + server/src/auth/password.service.spec.ts | 69 ++++ server/src/auth/password.service.ts | 64 ++++ server/src/auth/token.service.ts | 7 + server/src/auth/userData.decorator.ts | 30 ++ server/src/connectMicroservices.ts | 6 + server/src/constants.ts | 2 + .../decorators/api-nested-query.decorator.ts | 80 +++++ server/src/decorators/public.decorator.ts | 10 + server/src/errors.ts | 16 + server/src/filters/HttpExceptions.filter.ts | 89 +++++ server/src/grants.json | 32 ++ .../src/health/base/health.controller.base.ts | 19 ++ server/src/health/base/health.service.base.ts | 15 + server/src/health/health.controller.ts | 10 + server/src/health/health.module.ts | 10 + server/src/health/health.service.ts | 10 + .../aclFilterResponse.interceptor.ts | 42 +++ .../aclValidateRequest.interceptor.ts | 53 +++ server/src/main.ts | 53 +++ server/src/prisma.util.spec.ts | 23 ++ server/src/prisma.util.ts | 29 ++ server/src/prisma/prisma.module.ts | 9 + server/src/prisma/prisma.service.ts | 9 + .../base/secretsManager.service.base.spec.ts | 39 +++ .../base/secretsManager.service.base.ts | 19 ++ .../secrets/secretsManager.module.ts | 8 + .../secrets/secretsManager.service.ts | 10 + server/src/serveStaticOptions.service.ts | 39 +++ server/src/swagger.ts | 20 ++ server/src/swagger/favicon.png | Bin 0 -> 2498 bytes server/src/swagger/logo-amplication-white.svg | 15 + server/src/swagger/swagger.css | 321 ++++++++++++++++++ server/src/tests/auth/constants.ts | 19 ++ .../src/tests/auth/jwt/jwt.strategy.spec.ts | 26 ++ server/src/tests/auth/token.service.spec.ts | 47 +++ .../src/tests/health/health.service.spec.ts | 36 ++ server/src/types.ts | 3 + server/src/user/base/CreateUserArgs.ts | 30 ++ server/src/user/base/DeleteUserArgs.ts | 30 ++ server/src/user/base/UpdateUserArgs.ts | 40 +++ server/src/user/base/User.ts | 84 +++++ server/src/user/base/UserCountArgs.ts | 28 ++ server/src/user/base/UserCreateInput.ts | 67 ++++ server/src/user/base/UserFindManyArgs.ts | 62 ++++ server/src/user/base/UserFindUniqueArgs.ts | 30 ++ .../src/user/base/UserListRelationFilter.ts | 56 +++ server/src/user/base/UserOrderByInput.ts | 111 ++++++ server/src/user/base/UserUpdateInput.ts | 76 +++++ server/src/user/base/UserWhereInput.ts | 66 ++++ server/src/user/base/UserWhereUniqueInput.ts | 27 ++ .../user/base/user.controller.base.spec.ts | 206 +++++++++++ server/src/user/base/user.controller.base.ts | 203 +++++++++++ server/src/user/base/user.module.base.ts | 18 + server/src/user/base/user.resolver.base.ts | 134 ++++++++ server/src/user/base/user.service.base.ts | 74 ++++ server/src/user/user.controller.ts | 17 + server/src/user/user.module.ts | 14 + server/src/user/user.resolver.ts | 20 ++ server/src/user/user.service.ts | 14 + server/src/util/BooleanFilter.ts | 32 ++ server/src/util/BooleanNullableFilter.ts | 31 ++ server/src/util/DateTimeFilter.ts | 97 ++++++ server/src/util/DateTimeNullableFilter.ts | 97 ++++++ server/src/util/FloatFilter.ts | 98 ++++++ server/src/util/FloatNullableFilter.ts | 98 ++++++ server/src/util/IntFilter.ts | 98 ++++++ server/src/util/IntNullableFilter.ts | 98 ++++++ server/src/util/JsonFilter.ts | 31 ++ server/src/util/JsonNullableFilter.ts | 31 ++ server/src/util/MetaQueryPayload.ts | 13 + server/src/util/QueryMode.ts | 10 + server/src/util/SortOrder.ts | 10 + server/src/util/StringFilter.ts | 141 ++++++++ server/src/util/StringNullableFilter.ts | 141 ++++++++ server/src/validators/index.ts | 1 + .../is-json-value-validator.spec.ts | 44 +++ .../src/validators/is-json-value-validator.ts | 29 ++ server/tsconfig.build.json | 4 + server/tsconfig.json | 24 ++ 182 files changed, 6132 insertions(+) create mode 100644 admin-ui/.dockerignore create mode 100644 admin-ui/.env create mode 100644 admin-ui/.gitignore create mode 100644 admin-ui/Dockerfile create mode 100644 admin-ui/README.md create mode 100644 admin-ui/configuration/nginx.conf create mode 100644 admin-ui/package.json create mode 100644 admin-ui/public/favicon.ico create mode 100644 admin-ui/public/index.html create mode 100644 admin-ui/public/logo192.png create mode 100644 admin-ui/public/logo512.png create mode 100644 admin-ui/public/manifest.json create mode 100644 admin-ui/public/robots.txt create mode 100644 admin-ui/src/App.scss create mode 100644 admin-ui/src/App.tsx create mode 100644 admin-ui/src/Components/Pagination.tsx create mode 100644 admin-ui/src/Login.tsx create mode 100644 admin-ui/src/api/user/CreateUserArgs.ts create mode 100644 admin-ui/src/api/user/DeleteUserArgs.ts create mode 100644 admin-ui/src/api/user/UpdateUserArgs.ts create mode 100644 admin-ui/src/api/user/User.ts create mode 100644 admin-ui/src/api/user/UserCountArgs.ts create mode 100644 admin-ui/src/api/user/UserCreateInput.ts create mode 100644 admin-ui/src/api/user/UserFindManyArgs.ts create mode 100644 admin-ui/src/api/user/UserFindUniqueArgs.ts create mode 100644 admin-ui/src/api/user/UserListRelationFilter.ts create mode 100644 admin-ui/src/api/user/UserOrderByInput.ts create mode 100644 admin-ui/src/api/user/UserUpdateInput.ts create mode 100644 admin-ui/src/api/user/UserWhereInput.ts create mode 100644 admin-ui/src/api/user/UserWhereUniqueInput.ts create mode 100644 admin-ui/src/auth-provider/ra-auth-http.ts create mode 100644 admin-ui/src/auth-provider/ra-auth-jwt.ts create mode 100644 admin-ui/src/auth.ts create mode 100644 admin-ui/src/constants.ts create mode 100644 admin-ui/src/data-provider/graphqlDataProvider.ts create mode 100644 admin-ui/src/index.css create mode 100644 admin-ui/src/index.tsx create mode 100644 admin-ui/src/login.scss create mode 100644 admin-ui/src/pages/Dashboard.tsx create mode 100644 admin-ui/src/reportWebVitals.ts create mode 100644 admin-ui/src/setupTests.ts create mode 100644 admin-ui/src/theme/theme.ts create mode 100644 admin-ui/src/types.ts create mode 100644 admin-ui/src/user/EnumRoles.ts create mode 100644 admin-ui/src/user/RolesOptions.ts create mode 100644 admin-ui/src/user/UserCreate.tsx create mode 100644 admin-ui/src/user/UserEdit.tsx create mode 100644 admin-ui/src/user/UserList.tsx create mode 100644 admin-ui/src/user/UserShow.tsx create mode 100644 admin-ui/src/user/UserTitle.ts create mode 100644 admin-ui/src/user/roles.ts create mode 100644 admin-ui/src/util/BooleanFilter.ts create mode 100644 admin-ui/src/util/BooleanNullableFilter.ts create mode 100644 admin-ui/src/util/DateTimeFilter.ts create mode 100644 admin-ui/src/util/DateTimeNullableFilter.ts create mode 100644 admin-ui/src/util/FloatFilter.ts create mode 100644 admin-ui/src/util/FloatNullableFilter.ts create mode 100644 admin-ui/src/util/IntFilter.ts create mode 100644 admin-ui/src/util/IntNullableFilter.ts create mode 100644 admin-ui/src/util/JsonFilter.ts create mode 100644 admin-ui/src/util/JsonNullableFilter.ts create mode 100644 admin-ui/src/util/MetaQueryPayload.ts create mode 100644 admin-ui/src/util/QueryMode.ts create mode 100644 admin-ui/src/util/SortOrder.ts create mode 100644 admin-ui/src/util/StringFilter.ts create mode 100644 admin-ui/src/util/StringNullableFilter.ts create mode 100644 admin-ui/tsconfig.json create mode 100644 server/.dockerignore create mode 100644 server/.env create mode 100644 server/.gitignore create mode 100644 server/.prettierignore create mode 100644 server/Dockerfile create mode 100644 server/README.md create mode 100644 server/docker-compose.dev.yml create mode 100644 server/docker-compose.yml create mode 100644 server/nest-cli.json create mode 100644 server/package.json create mode 100644 server/prisma/schema.prisma create mode 100644 server/scripts/customSeed.ts create mode 100644 server/scripts/seed.ts create mode 100644 server/src/app.module.ts create mode 100644 server/src/auth/Credentials.ts create mode 100644 server/src/auth/IAuthStrategy.ts create mode 100644 server/src/auth/ITokenService.ts create mode 100644 server/src/auth/LoginArgs.ts create mode 100644 server/src/auth/UserInfo.ts create mode 100644 server/src/auth/abac.util.ts create mode 100644 server/src/auth/acl.module.ts create mode 100644 server/src/auth/auth.controller.ts create mode 100644 server/src/auth/auth.module.ts create mode 100644 server/src/auth/auth.resolver.ts create mode 100644 server/src/auth/auth.service.spec.ts create mode 100644 server/src/auth/auth.service.ts create mode 100644 server/src/auth/base/token.service.base.ts create mode 100644 server/src/auth/constants.ts create mode 100644 server/src/auth/defaultAuth.guard.ts create mode 100644 server/src/auth/gqlAC.guard.ts create mode 100644 server/src/auth/gqlDefaultAuth.guard.ts create mode 100644 server/src/auth/gqlUserRoles.decorator.ts create mode 100644 server/src/auth/jwt/base/jwt.strategy.base.ts create mode 100644 server/src/auth/jwt/jwt.strategy.ts create mode 100644 server/src/auth/jwt/jwtAuth.guard.ts create mode 100644 server/src/auth/jwt/jwtSecretFactory.ts create mode 100644 server/src/auth/password.service.spec.ts create mode 100644 server/src/auth/password.service.ts create mode 100644 server/src/auth/token.service.ts create mode 100644 server/src/auth/userData.decorator.ts create mode 100644 server/src/connectMicroservices.ts create mode 100644 server/src/constants.ts create mode 100644 server/src/decorators/api-nested-query.decorator.ts create mode 100644 server/src/decorators/public.decorator.ts create mode 100644 server/src/errors.ts create mode 100644 server/src/filters/HttpExceptions.filter.ts create mode 100644 server/src/grants.json create mode 100644 server/src/health/base/health.controller.base.ts create mode 100644 server/src/health/base/health.service.base.ts create mode 100644 server/src/health/health.controller.ts create mode 100644 server/src/health/health.module.ts create mode 100644 server/src/health/health.service.ts create mode 100644 server/src/interceptors/aclFilterResponse.interceptor.ts create mode 100644 server/src/interceptors/aclValidateRequest.interceptor.ts create mode 100644 server/src/main.ts create mode 100644 server/src/prisma.util.spec.ts create mode 100644 server/src/prisma.util.ts create mode 100644 server/src/prisma/prisma.module.ts create mode 100644 server/src/prisma/prisma.service.ts create mode 100644 server/src/providers/secrets/base/secretsManager.service.base.spec.ts create mode 100644 server/src/providers/secrets/base/secretsManager.service.base.ts create mode 100644 server/src/providers/secrets/secretsManager.module.ts create mode 100644 server/src/providers/secrets/secretsManager.service.ts create mode 100644 server/src/serveStaticOptions.service.ts create mode 100644 server/src/swagger.ts create mode 100644 server/src/swagger/favicon.png create mode 100644 server/src/swagger/logo-amplication-white.svg create mode 100644 server/src/swagger/swagger.css create mode 100644 server/src/tests/auth/constants.ts create mode 100644 server/src/tests/auth/jwt/jwt.strategy.spec.ts create mode 100644 server/src/tests/auth/token.service.spec.ts create mode 100644 server/src/tests/health/health.service.spec.ts create mode 100644 server/src/types.ts create mode 100644 server/src/user/base/CreateUserArgs.ts create mode 100644 server/src/user/base/DeleteUserArgs.ts create mode 100644 server/src/user/base/UpdateUserArgs.ts create mode 100644 server/src/user/base/User.ts create mode 100644 server/src/user/base/UserCountArgs.ts create mode 100644 server/src/user/base/UserCreateInput.ts create mode 100644 server/src/user/base/UserFindManyArgs.ts create mode 100644 server/src/user/base/UserFindUniqueArgs.ts create mode 100644 server/src/user/base/UserListRelationFilter.ts create mode 100644 server/src/user/base/UserOrderByInput.ts create mode 100644 server/src/user/base/UserUpdateInput.ts create mode 100644 server/src/user/base/UserWhereInput.ts create mode 100644 server/src/user/base/UserWhereUniqueInput.ts create mode 100644 server/src/user/base/user.controller.base.spec.ts create mode 100644 server/src/user/base/user.controller.base.ts create mode 100644 server/src/user/base/user.module.base.ts create mode 100644 server/src/user/base/user.resolver.base.ts create mode 100644 server/src/user/base/user.service.base.ts create mode 100644 server/src/user/user.controller.ts create mode 100644 server/src/user/user.module.ts create mode 100644 server/src/user/user.resolver.ts create mode 100644 server/src/user/user.service.ts create mode 100644 server/src/util/BooleanFilter.ts create mode 100644 server/src/util/BooleanNullableFilter.ts create mode 100644 server/src/util/DateTimeFilter.ts create mode 100644 server/src/util/DateTimeNullableFilter.ts create mode 100644 server/src/util/FloatFilter.ts create mode 100644 server/src/util/FloatNullableFilter.ts create mode 100644 server/src/util/IntFilter.ts create mode 100644 server/src/util/IntNullableFilter.ts create mode 100644 server/src/util/JsonFilter.ts create mode 100644 server/src/util/JsonNullableFilter.ts create mode 100644 server/src/util/MetaQueryPayload.ts create mode 100644 server/src/util/QueryMode.ts create mode 100644 server/src/util/SortOrder.ts create mode 100644 server/src/util/StringFilter.ts create mode 100644 server/src/util/StringNullableFilter.ts create mode 100644 server/src/validators/index.ts create mode 100644 server/src/validators/is-json-value-validator.spec.ts create mode 100644 server/src/validators/is-json-value-validator.ts create mode 100644 server/tsconfig.build.json create mode 100644 server/tsconfig.json diff --git a/admin-ui/.dockerignore b/admin-ui/.dockerignore new file mode 100644 index 0000000..1194b4f --- /dev/null +++ b/admin-ui/.dockerignore @@ -0,0 +1,7 @@ +.dockerignore +docker-compose.yml +Dockerfile +build/ +node_modules +.env +.gitignore diff --git a/admin-ui/.env b/admin-ui/.env new file mode 100644 index 0000000..4eef91c --- /dev/null +++ b/admin-ui/.env @@ -0,0 +1,2 @@ +PORT=3001 +REACT_APP_SERVER_URL=http://localhost:3000 \ No newline at end of file diff --git a/admin-ui/.gitignore b/admin-ui/.gitignore new file mode 100644 index 0000000..590b2e0 --- /dev/null +++ b/admin-ui/.gitignore @@ -0,0 +1,23 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/admin-ui/Dockerfile b/admin-ui/Dockerfile new file mode 100644 index 0000000..9c43e40 --- /dev/null +++ b/admin-ui/Dockerfile @@ -0,0 +1,51 @@ +# multi-stage: base (build) +FROM node:18.13.0-slim AS base + +# instantiate environment variable +ARG REACT_APP_SERVER_URL=http://localhost:3000 + +# set the environment variable that points to the server +ENV REACT_APP_SERVER_URL=$REACT_APP_SERVER_URL + +# create directory where the application will be built +WORKDIR /app + +# copy over the dependency manifests, both the package.json +# and the package-lock.json are copied over +COPY package*.json ./ + +# installs packages and their dependencies +RUN npm install + +# copy over the code base +COPY . . + +# create the bundle of the application +RUN npm run build + +# multi-stage: production (runtime) +FROM nginx:1.22-alpine AS production + +# copy over the bundled code from the build stage +COPY --from=base /app/build /usr/share/nginx/html +COPY --from=base /app/configuration/nginx.conf /etc/nginx/conf.d/default.conf + +# create a new process indication file +RUN touch /var/run/nginx.pid + +# change ownership of nginx related directories and files +RUN chown -R nginx:nginx /var/run/nginx.pid \ + /usr/share/nginx/html \ + /var/cache/nginx \ + /var/log/nginx \ + /etc/nginx/conf.d + +# set user to the created non-privileged user +USER nginx + +# expose a specific port on the docker container +ENV PORT=80 +EXPOSE ${PORT} + +# start the server using the previously build application +ENTRYPOINT [ "nginx", "-g", "daemon off;" ] diff --git a/admin-ui/README.md b/admin-ui/README.md new file mode 100644 index 0000000..03abb2a --- /dev/null +++ b/admin-ui/README.md @@ -0,0 +1,47 @@ +

+ + amplication-logo + +

+ +# Introduction + +This service was generated with Amplication. It serves as the client-side for the generated server component. The client-side consist of a React application with ready-made forms for creating and editing the different data models of the application. It is pre-conffigured to work with the server and comes with the boilerplate and foundation for the client - i.e., routing, navigation, authentication, permissions, menu, breadcrumbs, error handling and much more. Additional information about the admin component and the architecture around it, can be found on the [documentation](https://docs.amplication.com/guides/getting-started) site. This side of the generated project was bootstrapped with [create-react-app](https://github.com/facebook/create-react-app) and built with [react-admin](https://marmelab.com/react-admin/). + + +

+ +

+ +# Getting started + +## Step 1: Configuration + +Configuration for the client component can be provided through the use of environment variables. These can be passed to the application via the use of the `.env` file in the base directory of the generated service. Below a table can be found which show the different variables that can be passed. These values are provided default values after generation, change them to the desired values. + +| Variable | Description | Value | +| -------------------- | ------------------------------------------------ | ------------------------------ | +| PORT | the port on which to run the client | 3001 | +| REACT_APP_SERVER_URL | the url on which the server component is running | http://localhost:[server-port] | + +> **Note** +> Amplication generates default values and stores them under the .env file. It is advised to use some form of secrets manager/vault solution when using in production. + + +## Step 2: Scripts + +After configuration of the client the next step would be to run the application. Before running the client side of the component, make sure that the different pre-requisites are met - i.e., npm, docker. Make sure that the server-side of the application is running. + +```sh +# installation of the dependencies +$ npm install + +# starts the application in development mode - available by default under http://localhost:3001 with a pre-configured user with the username "admin" and password "admin" +$ npm run start + +# builds the application in production mode - available under 'build' +$ npm run build + +# removes the single build dependency from the project +$ npm run eject +``` diff --git a/admin-ui/configuration/nginx.conf b/admin-ui/configuration/nginx.conf new file mode 100644 index 0000000..88dad6e --- /dev/null +++ b/admin-ui/configuration/nginx.conf @@ -0,0 +1,11 @@ +server_tokens off; + +server { + listen 8080; + server_name localhost; + location / { + root /usr/share/nginx/html; + index index.html index.htm; + try_files $uri /index.html; + } +} \ No newline at end of file diff --git a/admin-ui/package.json b/admin-ui/package.json new file mode 100644 index 0000000..576a781 --- /dev/null +++ b/admin-ui/package.json @@ -0,0 +1,60 @@ +{ + "name": "@record/admin", + "private": true, + "dependencies": { + "@apollo/client": "3.6.9", + "@material-ui/core": "4.12.4", + "graphql": "15.6.1", + "lodash": "4.17.21", + "pluralize": "8.0.0", + "ra-data-graphql-amplication": "0.0.14", + "react": "16.14.0", + "react-admin": "3.19.12", + "react-dom": "16.14.0", + "react-scripts": "5.0.0", + "sass": "^1.39.0", + "web-vitals": "1.1.2" + }, + "overrides": { + "react-scripts": { + "@svgr/webpack": "6.5.1" + } + }, + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test", + "eject": "react-scripts eject", + "package:container": "docker build ." + }, + "eslintConfig": { + "extends": [ + "react-app", + "react-app/jest" + ] + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + }, + "devDependencies": { + "@testing-library/jest-dom": "5.14.1", + "@testing-library/react": "11.2.7", + "@testing-library/user-event": "13.2.0", + "@types/jest": "26.0.16", + "@types/lodash": "4.14.178", + "@types/node": "12.20.16", + "@types/react": "16.14.11", + "@types/react-dom": "17.0.0", + "type-fest": "0.13.1", + "typescript": "4.3.5" + } +} \ No newline at end of file diff --git a/admin-ui/public/favicon.ico b/admin-ui/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..fcbdcf2d26233c47420d1e8d0f47f0aede4c1130 GIT binary patch literal 6548 zcma)A`EOj+6@K2G#EugH`3D$$Xw$;Z~QgJFxm{m$jTB+N}OR7#~Ma%uGBrK*CZH*-*0`9Xc%kB z2EQHXYfn9V>M%Y}?d)hBg2cE+dNRH-9A#<45bV`663V~puX14A_aIt}>%1imO&!oc zWx@84X!Y~!HRE%&lMCHaS5eVB>RH;X8lLJDbHmbBk-N&ji`tl2MnnYmq9*?i^xCP# zJCn3@>eo7#)9bIBjnvJaZ%d$I5EBnWtjR9RmL1AI5bg-AY zbOD@){=hjTYz_4dtC_1=&>~0F*%}zR5~CALgaRpO1%3YFAyMqQa;c4sEJJCRN~s8N zUmRE_%09{}$|B_&c>u+R(v-(OODLcYm7%Yn`sd4gv4;}Bd{r8RUr3+7*Q$4|AG7o- zXg&GrQp*Zu5QVdVZoGDSkrQ)uH4#tj$q#-GjYpYNz8Z{$1YK6)ZB2#dECk~@9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(bcRm&&cmw-si?BuaAD$vLr~U?PADKlx*lXf{Ui)ps8|0TJKP6o%*?snGE% z`lS)KyV`uih1r+^s250`;8-G1CMjDPY==zCxP7Cc3)UY&?XN_TFH8T=+Qzk-=> zQNO=%Tj!n?;}pbE6iQc`*qmHXoHr*UCNGhIm69%Ya63wF7gx!pzxiYlN1NtYUKI8# d$}i+n)((Y_4MNTsC&AAV=X77V%?~`&{|DHLP-*}G literal 0 HcmV?d00001 diff --git a/admin-ui/public/index.html b/admin-ui/public/index.html new file mode 100644 index 0000000..2bbf9af --- /dev/null +++ b/admin-ui/public/index.html @@ -0,0 +1,40 @@ + + + + + + + + + + + + + Record + + + +
+ + + diff --git a/admin-ui/public/logo192.png b/admin-ui/public/logo192.png new file mode 100644 index 0000000000000000000000000000000000000000..1918ff2edeedb1a1cfb429c71deb46b3cb71427e GIT binary patch literal 9721 zcmc&)`EOj;bskbAhx;N9N92%0QWCcriu*p?H*qKq$>ApM`ywvlPKu<&AtS@JQAdsA z*!3dEjuXRjyeo+lwT%n|w&h5cEm?IWtG1+|DT20gPyjd(Ni1Ab*p;PNxg1x7V~nfBXJ>!oItp$35Za$$-<*UJGjsBf#+g zs~Y+!I|E<6en?1j?l!ol@5mF?>?*bB7;$qY^Rj6RwkU0eny0x|^=ln<8k^%5VZ|7=5g3IK z?pi|@tY-0&p;(zfiKw9UP%#)`o{xv-q7@Dh5N_cMx1ad({JsJi5l*;$N{kFq^-wbq ztGM8H$lBGP@O6IvFvK&oireFeO4K&&ZoUhoLjvO?RLa9VGvVj8**${f@n+zyw_)*n z-s6R($3|9R_2tP!lPFlTs=%bB(uKM=Q*cJY~idg^(ZpRe-| zu5RN-bAneH-bMRpzS@)}1%4c4Hv|ZQ@SK2yN76(1ChJgeK!x_&!(aZ0rM7S!#9V&y zqD)}10mkkY@J5eHK(*~RKN$97>D8D)7k&-eg!DmTcYzuqEj(wgcfNjv!D=qz5Tpwt z;7)T^e6J1(DQ=2TK)H9&xZYR(kYH-Gk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ogZ;f~A-b&-;vO?!_lz?k}DJN6Vn9<9I8ty}*H{c{Uc1 zC<@GVfrt#zbIs6!K4mT9g1eVN`#s1#;J6?HI4|TYRoG$}B+c@J6=r?=8 zo;LAlLii^EAoI6Ri(wVD(^Tq55=H`;wuABrta8Hlxm}+@UVGoZaTc5%qt3CK8Ok;R z7-t?Em}4dmnZ+@P;-`4Ks447jpsYq|s3r)%bNd{Znr5(p65e`1z*jGdF_gdw?*?|@Lczze9S}KV&0YA4i$pSf2~b2i}i1>Jf;oh+KjMS!Mqew zAxkC@!{dSgy90S$PBU*jCOgA-MP-^(HCTE40dbjNLALXf^wbUPCR7w{maBPc#(_bfkI+79aR0clvs6w}3y0X8c^{!=U$ zfRzKp@)9`=>9uytNN$_c7ZzK!AHu3))B)=X_t9Lq&K5I6^nswti@)FrnTOhB5Kji| z{OwlF+@WyRKhV>~;&4I?wIHwQu?Z-JH$=!Jq^e8_lmgU$?o2Uz0~Zhdd(Z@;)xRcrDPT*1LI zh>rJu`L&akQ|@ZO2=`sS%7U!i3IH!dfR!Om_aA0C@tdk7iW$t3B9Mlo{;Qm%lYy9$ z=|pZ}|Kzu?{2esw@DP{M5L#8gZ|y{QSe1+{LGggAkl{6U0aqVnHU)K>)pUYIs?N>% z8!@1--dU*$TWB;Mfo*HuV&=JKT(t{)FN#u`fsfv}@iVAuNDG8Dw`l17-grkC~z#_~6BKBv}8t?Oci za|3|K*2ZqAfE97Opm>Lua7#H`6Sz2l|jlpaZ_W>SYPy~z-i?}SkYP7fT zi)Y8%tPF5*F30T2)BL~(JUH;>bG&}{igPdb1ymd1|NiAuVE@xawq$tLna$Ec0xM}72@ zm-<@GJaqXn5Wt!TRN1R-)CZ{pM&S`>11UM>E~qAhxNRRiDF(x4X=cH&bY~zcudENA TglphG9_i|9n`&TI@kIX#FLjTn literal 0 HcmV?d00001 diff --git a/admin-ui/public/logo512.png b/admin-ui/public/logo512.png new file mode 100644 index 0000000000000000000000000000000000000000..7e7dc74f2a9aa690a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T10r*isY1F zBLi|vbnCAtB1U9j*z{zOfiR!9Ut^f_9Ld9d^Y~6PC}M0M9LNVHF$`_ze_LA3=|$EK z5P9zPl8v-6UPjO}0e2*?$>2H*E8v$4<{D7v&Y%J2RImbi3~=^jB?H!fTc-}m zq|Te>QRlo@=z>UQ3*#6FV%O5JcvLyCr~nzEUi^-%xN#4I0dQ|W5c|nWZY)0(8r+P& zqTlvUJYm=qW9)8~wvw+FOnU?sLre4x(@dh6=6PT?osFtkenKZqyzd++0^~UpykOg_ z+=($j2MX-c_k0*yCKkYK_jKsxKETmVOh~^Ov9U7>3>jI4AO0v}f(|O88|}!JWHOr$ z74#Sx=^19s|33EYqlGO{dJT3m>5&v$PX_@EF~F*ys$tld+uB(0BQ9V-V>*~BA3wG- zYvml+@UZ$iyGWI=d_9ZaxnQCJLJ+5EV~lZ95Dn*_F$J>mEYkw=(rGD2 zBO=rjaxxpNC7qu}AX|B~e*5af|M9PH?9knepPfpm^g0aa8lczVgL`>^FMjg?BcCVM z74=uaX6&CFg&!9oX$v?TE2DB{Y^fJ#aftFtygl#ME3XGK6Pnu9m?`PG%3KdXz)b zQ?m@+SHTypveit2-g*2>3+i{5YWP2Jpof4telKqOA37*?!DjGFg#l}&6U6)cMX E3vX#zv;Y7A literal 0 HcmV?d00001 diff --git a/admin-ui/public/manifest.json b/admin-ui/public/manifest.json new file mode 100644 index 0000000..a9acc14 --- /dev/null +++ b/admin-ui/public/manifest.json @@ -0,0 +1,25 @@ +{ + "short_name": "Record", + "name": "Record", + "icons": [ + { + "src": "favicon.ico", + "sizes": "64x64 32x32 24x24 16x16", + "type": "image/x-icon" + }, + { + "src": "logo192.png", + "type": "image/png", + "sizes": "192x192" + }, + { + "src": "logo512.png", + "type": "image/png", + "sizes": "512x512" + } + ], + "start_url": ".", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} \ No newline at end of file diff --git a/admin-ui/public/robots.txt b/admin-ui/public/robots.txt new file mode 100644 index 0000000..e9e57dc --- /dev/null +++ b/admin-ui/public/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/admin-ui/src/App.scss b/admin-ui/src/App.scss new file mode 100644 index 0000000..4c1cbb0 --- /dev/null +++ b/admin-ui/src/App.scss @@ -0,0 +1,59 @@ +// .App { +// .MuiAppBar-colorSecondary { +// background-color: black; + +// .RaAppBar-menuButton-13 { +// background-color: yellow; +// } +// } + +// .MuiDrawer-paper { +// background-color: red; + +// .MuiListItemIcon-root { +// color: white; +// } +// } + +// .MuiButton-textPrimary { +// background-color: purple; +// margin: 0 0.5rem; +// color: white; +// padding: 0.5rem 1rem; + +// &:hover { +// background-color: blue; +// } +// } + +// .MuiTableRow-head { +// .MuiTableCell-head { +// background-color: black; +// color: white; +// } + +// .MuiTableSortLabel-root { +// &:hover { +// color: red; + +// .MuiTableSortLabel-icon { +// color: red !important; +// } +// } +// .MuiTableSortLabel-icon { +// color: white !important; +// } +// } +// .MuiTableSortLabel-active { +// color: green; + +// .MuiTableSortLabel-icon { +// color: green !important; +// } +// } +// } + +// .MuiFormLabel-root { +// color: magenta; +// } +// } diff --git a/admin-ui/src/App.tsx b/admin-ui/src/App.tsx new file mode 100644 index 0000000..9267aa2 --- /dev/null +++ b/admin-ui/src/App.tsx @@ -0,0 +1,50 @@ +import React, { useEffect, useState } from "react"; +import { Admin, DataProvider, Resource } from "react-admin"; +import buildGraphQLProvider from "./data-provider/graphqlDataProvider"; +import { theme } from "./theme/theme"; +import Login from "./Login"; +import "./App.scss"; +import Dashboard from "./pages/Dashboard"; +import { UserList } from "./user/UserList"; +import { UserCreate } from "./user/UserCreate"; +import { UserEdit } from "./user/UserEdit"; +import { UserShow } from "./user/UserShow"; +import { jwtAuthProvider } from "./auth-provider/ra-auth-jwt"; + +const App = (): React.ReactElement => { + const [dataProvider, setDataProvider] = useState(null); + useEffect(() => { + buildGraphQLProvider + .then((provider: any) => { + setDataProvider(() => provider); + }) + .catch((error: any) => { + console.log(error); + }); + }, []); + if (!dataProvider) { + return
Loading
; + } + return ( +
+ + + +
+ ); +}; + +export default App; diff --git a/admin-ui/src/Components/Pagination.tsx b/admin-ui/src/Components/Pagination.tsx new file mode 100644 index 0000000..2de2ebf --- /dev/null +++ b/admin-ui/src/Components/Pagination.tsx @@ -0,0 +1,10 @@ +import React from "react"; +import { Pagination as RAPagination, PaginationProps } from "react-admin"; + +const PAGINATION_OPTIONS = [10, 25, 50, 100, 200]; + +const Pagination = (props: PaginationProps) => ( + +); + +export default Pagination; diff --git a/admin-ui/src/Login.tsx b/admin-ui/src/Login.tsx new file mode 100644 index 0000000..f7ec8ed --- /dev/null +++ b/admin-ui/src/Login.tsx @@ -0,0 +1,117 @@ +import * as React from "react"; +import { useState } from "react"; +import { useLogin, useNotify, Notification, defaultTheme } from "react-admin"; +import { ThemeProvider } from "@material-ui/styles"; +import { createTheme } from "@material-ui/core/styles"; +import { Button } from "@material-ui/core"; +import "./login.scss"; + +const CLASS_NAME = "login-page"; + +const Login = ({ theme }: any) => { + const [username, setUsername] = useState(""); + const [password, setPassword] = useState(""); + const login = useLogin(); + const notify = useNotify(); + const BASE_URI = process.env.REACT_APP_SERVER_URL; + const submit = (e: any) => { + e.preventDefault(); + login({ username, password }).catch(() => + notify("Invalid username or password") + ); + }; + + return ( + +
+
+
+ GraphQL API +

Connect via GraphQL

+
+ Connect to the server using GraphQL API with a complete and + understandable description of the data in your API +
+ +
+
+ React-Admin +

Admin UI

+
+ Sign in to a React-Admin client with ready-made forms for creating + and editing all the data models of your application +
+
+ + + +
+
+
+ REST API +

Connect via REST API

+
+ Connect to the server using REST API with a built-in Swagger + documentation +
+ +
+ + +
+
+ Read + + Amplication docs + + to learn more +
+
+
+ ); +}; + +export default Login; diff --git a/admin-ui/src/api/user/CreateUserArgs.ts b/admin-ui/src/api/user/CreateUserArgs.ts new file mode 100644 index 0000000..2a56f0c --- /dev/null +++ b/admin-ui/src/api/user/CreateUserArgs.ts @@ -0,0 +1,5 @@ +import { UserCreateInput } from "./UserCreateInput"; + +export type CreateUserArgs = { + data: UserCreateInput; +}; diff --git a/admin-ui/src/api/user/DeleteUserArgs.ts b/admin-ui/src/api/user/DeleteUserArgs.ts new file mode 100644 index 0000000..5f655b8 --- /dev/null +++ b/admin-ui/src/api/user/DeleteUserArgs.ts @@ -0,0 +1,5 @@ +import { UserWhereUniqueInput } from "./UserWhereUniqueInput"; + +export type DeleteUserArgs = { + where: UserWhereUniqueInput; +}; diff --git a/admin-ui/src/api/user/UpdateUserArgs.ts b/admin-ui/src/api/user/UpdateUserArgs.ts new file mode 100644 index 0000000..30e635e --- /dev/null +++ b/admin-ui/src/api/user/UpdateUserArgs.ts @@ -0,0 +1,7 @@ +import { UserWhereUniqueInput } from "./UserWhereUniqueInput"; +import { UserUpdateInput } from "./UserUpdateInput"; + +export type UpdateUserArgs = { + where: UserWhereUniqueInput; + data: UserUpdateInput; +}; diff --git a/admin-ui/src/api/user/User.ts b/admin-ui/src/api/user/User.ts new file mode 100644 index 0000000..9c53564 --- /dev/null +++ b/admin-ui/src/api/user/User.ts @@ -0,0 +1,11 @@ +import { JsonValue } from "type-fest"; + +export type User = { + createdAt: Date; + firstName: string | null; + id: string; + lastName: string | null; + roles: JsonValue; + updatedAt: Date; + username: string; +}; diff --git a/admin-ui/src/api/user/UserCountArgs.ts b/admin-ui/src/api/user/UserCountArgs.ts new file mode 100644 index 0000000..b300ec3 --- /dev/null +++ b/admin-ui/src/api/user/UserCountArgs.ts @@ -0,0 +1,5 @@ +import { UserWhereInput } from "./UserWhereInput"; + +export type UserCountArgs = { + where?: UserWhereInput; +}; diff --git a/admin-ui/src/api/user/UserCreateInput.ts b/admin-ui/src/api/user/UserCreateInput.ts new file mode 100644 index 0000000..e53c277 --- /dev/null +++ b/admin-ui/src/api/user/UserCreateInput.ts @@ -0,0 +1,9 @@ +import { InputJsonValue } from "../../types"; + +export type UserCreateInput = { + firstName?: string | null; + lastName?: string | null; + password: string; + roles: InputJsonValue; + username: string; +}; diff --git a/admin-ui/src/api/user/UserFindManyArgs.ts b/admin-ui/src/api/user/UserFindManyArgs.ts new file mode 100644 index 0000000..b453f3e --- /dev/null +++ b/admin-ui/src/api/user/UserFindManyArgs.ts @@ -0,0 +1,9 @@ +import { UserWhereInput } from "./UserWhereInput"; +import { UserOrderByInput } from "./UserOrderByInput"; + +export type UserFindManyArgs = { + where?: UserWhereInput; + orderBy?: Array; + skip?: number; + take?: number; +}; diff --git a/admin-ui/src/api/user/UserFindUniqueArgs.ts b/admin-ui/src/api/user/UserFindUniqueArgs.ts new file mode 100644 index 0000000..97d18e8 --- /dev/null +++ b/admin-ui/src/api/user/UserFindUniqueArgs.ts @@ -0,0 +1,5 @@ +import { UserWhereUniqueInput } from "./UserWhereUniqueInput"; + +export type UserFindUniqueArgs = { + where: UserWhereUniqueInput; +}; diff --git a/admin-ui/src/api/user/UserListRelationFilter.ts b/admin-ui/src/api/user/UserListRelationFilter.ts new file mode 100644 index 0000000..4c4d06e --- /dev/null +++ b/admin-ui/src/api/user/UserListRelationFilter.ts @@ -0,0 +1,7 @@ +import { UserWhereInput } from "./UserWhereInput"; + +export type UserListRelationFilter = { + every?: UserWhereInput; + some?: UserWhereInput; + none?: UserWhereInput; +}; diff --git a/admin-ui/src/api/user/UserOrderByInput.ts b/admin-ui/src/api/user/UserOrderByInput.ts new file mode 100644 index 0000000..36cee1e --- /dev/null +++ b/admin-ui/src/api/user/UserOrderByInput.ts @@ -0,0 +1,12 @@ +import { SortOrder } from "../../util/SortOrder"; + +export type UserOrderByInput = { + createdAt?: SortOrder; + firstName?: SortOrder; + id?: SortOrder; + lastName?: SortOrder; + password?: SortOrder; + roles?: SortOrder; + updatedAt?: SortOrder; + username?: SortOrder; +}; diff --git a/admin-ui/src/api/user/UserUpdateInput.ts b/admin-ui/src/api/user/UserUpdateInput.ts new file mode 100644 index 0000000..f5ee977 --- /dev/null +++ b/admin-ui/src/api/user/UserUpdateInput.ts @@ -0,0 +1,9 @@ +import { InputJsonValue } from "../../types"; + +export type UserUpdateInput = { + firstName?: string | null; + lastName?: string | null; + password?: string; + roles?: InputJsonValue; + username?: string; +}; diff --git a/admin-ui/src/api/user/UserWhereInput.ts b/admin-ui/src/api/user/UserWhereInput.ts new file mode 100644 index 0000000..22c10cb --- /dev/null +++ b/admin-ui/src/api/user/UserWhereInput.ts @@ -0,0 +1,9 @@ +import { StringNullableFilter } from "../../util/StringNullableFilter"; +import { StringFilter } from "../../util/StringFilter"; + +export type UserWhereInput = { + firstName?: StringNullableFilter; + id?: StringFilter; + lastName?: StringNullableFilter; + username?: StringFilter; +}; diff --git a/admin-ui/src/api/user/UserWhereUniqueInput.ts b/admin-ui/src/api/user/UserWhereUniqueInput.ts new file mode 100644 index 0000000..309d343 --- /dev/null +++ b/admin-ui/src/api/user/UserWhereUniqueInput.ts @@ -0,0 +1,3 @@ +export type UserWhereUniqueInput = { + id: string; +}; diff --git a/admin-ui/src/auth-provider/ra-auth-http.ts b/admin-ui/src/auth-provider/ra-auth-http.ts new file mode 100644 index 0000000..c6eeba8 --- /dev/null +++ b/admin-ui/src/auth-provider/ra-auth-http.ts @@ -0,0 +1,78 @@ +import { gql } from "@apollo/client/core"; +import { AuthProvider } from "react-admin"; +import { + CREDENTIALS_LOCAL_STORAGE_ITEM, + USER_DATA_LOCAL_STORAGE_ITEM, +} from "../constants"; +import { Credentials, LoginMutateResult } from "../types"; +import { apolloClient } from "../data-provider/graphqlDataProvider"; + +const LOGIN = gql` + mutation login($username: String!, $password: String!) { + login(credentials: { username: $username, password: $password }) { + username + roles + } + } +`; + +export const httpAuthProvider: AuthProvider = { + login: async (credentials: Credentials) => { + const userData = await apolloClient.mutate({ + mutation: LOGIN, + variables: { + ...credentials, + }, + }); + + if (userData && userData.data?.login.username) { + localStorage.setItem( + CREDENTIALS_LOCAL_STORAGE_ITEM, + createBasicAuthorizationHeader( + credentials.username, + credentials.password + ) + ); + localStorage.setItem( + USER_DATA_LOCAL_STORAGE_ITEM, + JSON.stringify(userData.data) + ); + return Promise.resolve(); + } + return Promise.reject(); + }, + logout: () => { + localStorage.removeItem(CREDENTIALS_LOCAL_STORAGE_ITEM); + return Promise.resolve(); + }, + checkError: ({ status }: any) => { + if (status === 401 || status === 403) { + localStorage.removeItem(CREDENTIALS_LOCAL_STORAGE_ITEM); + return Promise.reject(); + } + return Promise.resolve(); + }, + checkAuth: () => { + return localStorage.getItem(CREDENTIALS_LOCAL_STORAGE_ITEM) + ? Promise.resolve() + : Promise.reject(); + }, + getPermissions: () => Promise.reject("Unknown method"), + getIdentity: () => { + const str = localStorage.getItem(USER_DATA_LOCAL_STORAGE_ITEM); + const userData: LoginMutateResult = JSON.parse(str || ""); + + return Promise.resolve({ + id: userData.login.username, + fullName: userData.login.username, + avatar: undefined, + }); + }, +}; + +function createBasicAuthorizationHeader( + username: string, + password: string +): string { + return `Basic ${btoa(`${username}:${password}`)}`; +} diff --git a/admin-ui/src/auth-provider/ra-auth-jwt.ts b/admin-ui/src/auth-provider/ra-auth-jwt.ts new file mode 100644 index 0000000..c8bcafc --- /dev/null +++ b/admin-ui/src/auth-provider/ra-auth-jwt.ts @@ -0,0 +1,72 @@ +import { gql } from "@apollo/client/core"; +import { AuthProvider } from "react-admin"; +import { + CREDENTIALS_LOCAL_STORAGE_ITEM, + USER_DATA_LOCAL_STORAGE_ITEM, +} from "../constants"; +import { Credentials, LoginMutateResult } from "../types"; +import { apolloClient } from "../data-provider/graphqlDataProvider"; + +const LOGIN = gql` + mutation login($username: String!, $password: String!) { + login(credentials: { username: $username, password: $password }) { + username + accessToken + } + } +`; + +export const jwtAuthProvider: AuthProvider = { + login: async (credentials: Credentials) => { + const userData = await apolloClient.mutate({ + mutation: LOGIN, + variables: { + ...credentials, + }, + }); + + if (userData && userData.data?.login.username) { + localStorage.setItem( + CREDENTIALS_LOCAL_STORAGE_ITEM, + createBearerAuthorizationHeader(userData.data.login?.accessToken) + ); + localStorage.setItem( + USER_DATA_LOCAL_STORAGE_ITEM, + JSON.stringify(userData.data) + ); + return Promise.resolve(); + } + return Promise.reject(); + }, + logout: () => { + localStorage.removeItem(CREDENTIALS_LOCAL_STORAGE_ITEM); + return Promise.resolve(); + }, + checkError: ({ status }: any) => { + if (status === 401 || status === 403) { + localStorage.removeItem(CREDENTIALS_LOCAL_STORAGE_ITEM); + return Promise.reject(); + } + return Promise.resolve(); + }, + checkAuth: () => { + return localStorage.getItem(CREDENTIALS_LOCAL_STORAGE_ITEM) + ? Promise.resolve() + : Promise.reject(); + }, + getPermissions: () => Promise.reject("Unknown method"), + getIdentity: () => { + const str = localStorage.getItem(USER_DATA_LOCAL_STORAGE_ITEM); + const userData: LoginMutateResult = JSON.parse(str || ""); + + return Promise.resolve({ + id: userData.login.username, + fullName: userData.login.username, + avatar: undefined, + }); + }, +}; + +export function createBearerAuthorizationHeader(accessToken: string) { + return `Bearer ${accessToken}`; +} diff --git a/admin-ui/src/auth.ts b/admin-ui/src/auth.ts new file mode 100644 index 0000000..498b026 --- /dev/null +++ b/admin-ui/src/auth.ts @@ -0,0 +1,34 @@ +import { EventEmitter } from "events"; +import { CREDENTIALS_LOCAL_STORAGE_ITEM } from "./constants"; +import { Credentials } from "./types"; + +const eventEmitter = new EventEmitter(); + +export function isAuthenticated(): boolean { + return Boolean(getCredentials()); +} + +export function listen(listener: (authenticated: boolean) => void): void { + eventEmitter.on("change", () => { + listener(isAuthenticated()); + }); +} + +export function setCredentials(credentials: Credentials) { + localStorage.setItem( + CREDENTIALS_LOCAL_STORAGE_ITEM, + JSON.stringify(credentials) + ); +} + +export function getCredentials(): Credentials | null { + const raw = localStorage.getItem(CREDENTIALS_LOCAL_STORAGE_ITEM); + if (raw === null) { + return null; + } + return JSON.parse(raw); +} + +export function removeCredentials(): void { + localStorage.removeItem(CREDENTIALS_LOCAL_STORAGE_ITEM); +} diff --git a/admin-ui/src/constants.ts b/admin-ui/src/constants.ts new file mode 100644 index 0000000..4b3ca4b --- /dev/null +++ b/admin-ui/src/constants.ts @@ -0,0 +1,2 @@ +export const CREDENTIALS_LOCAL_STORAGE_ITEM = "credentials"; +export const USER_DATA_LOCAL_STORAGE_ITEM = "userData"; diff --git a/admin-ui/src/data-provider/graphqlDataProvider.ts b/admin-ui/src/data-provider/graphqlDataProvider.ts new file mode 100644 index 0000000..3ec4466 --- /dev/null +++ b/admin-ui/src/data-provider/graphqlDataProvider.ts @@ -0,0 +1,28 @@ +import buildGraphQLProvider from "ra-data-graphql-amplication"; +import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client"; +import { setContext } from "@apollo/client/link/context"; +import { CREDENTIALS_LOCAL_STORAGE_ITEM } from "../constants"; + +const httpLink = createHttpLink({ + uri: `${process.env.REACT_APP_SERVER_URL}/graphql`, +}); + +// eslint-disable-next-line @typescript-eslint/naming-convention +const authLink = setContext((_, { headers }) => { + const token = localStorage.getItem(CREDENTIALS_LOCAL_STORAGE_ITEM); + return { + headers: { + ...headers, + authorization: token ? token : "", + }, + }; +}); + +export const apolloClient = new ApolloClient({ + cache: new InMemoryCache(), + link: authLink.concat(httpLink), +}); + +export default buildGraphQLProvider({ + client: apolloClient, +}); diff --git a/admin-ui/src/index.css b/admin-ui/src/index.css new file mode 100644 index 0000000..8686848 --- /dev/null +++ b/admin-ui/src/index.css @@ -0,0 +1,26 @@ +body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", + "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +#root { + height: 100vh; +} + +code { + font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", + monospace; +} + +.amp-breadcrumbs { + padding: var(--default-spacing); +} + +.entity-id { + color: var(--primary); + text-decoration: underline; +} diff --git a/admin-ui/src/index.tsx b/admin-ui/src/index.tsx new file mode 100644 index 0000000..5e2de69 --- /dev/null +++ b/admin-ui/src/index.tsx @@ -0,0 +1,19 @@ +import React from "react"; +import ReactDOM from "react-dom"; +import "./index.css"; +// @ts-ignore +// eslint-disable-next-line import/no-unresolved +import App from "./App"; +import reportWebVitals from "./reportWebVitals"; + +ReactDOM.render( + + + , + document.getElementById("root") +); + +// If you want to start measuring performance in your app, pass a function +// to log results (for example: reportWebVitals(console.log)) +// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals +reportWebVitals(); diff --git a/admin-ui/src/login.scss b/admin-ui/src/login.scss new file mode 100644 index 0000000..667d8d2 --- /dev/null +++ b/admin-ui/src/login.scss @@ -0,0 +1,119 @@ +:root { + --surface: #15192c; /*dark: black100 */ + --white: #15192c; /*dark: black100 */ + + --black100: #ffffff; /*dark: white */ + --black90: #b7bac7; /*dark: black10 */ + --black80: #a3a8b8; /*dark: black20 */ + --black60: #80869d; /*dark: black30 */ + --black40: #686f8c; /*dark: black40 */ + --black30: #515873; /*dark: black50 */ + --black20: #444b66; /*dark: black60 */ + --black10: #373d57; /*dark: black70 */ + --black5: #2c3249; /*dark: black80 */ + --black2: #22273c; /*dark: black90 */ + + --primary: #7950ed; +} + +.login-page { + height: 100vh; + width: 100%; + background-color: var(--surface); + color: var(--black100); + display: flex; + justify-content: center; + align-items: center; + flex-direction: column; + + &__wrapper { + display: flex; + align-items: stretch; + justify-content: center; + flex-direction: row; + } + + &__box { + text-align: center; + width: 340px; + background-color: var(--black2); + border-radius: var(--small-border-radius); + margin: 1rem; + padding: 1rem; + border: 1px solid var(--black10); + display: flex; + flex-direction: column; + align-items: center; + justify-content: stretch; + + h2 { + font-size: 18px; + } + img { + width: 48px; + } + + &__message { + color: var(--black80); + font-size: 14px; + line-height: 22px; + } + + button, + .MuiButton-contained { + box-sizing: border-box; + background-color: var(--primary); + width: 300px; + margin-top: 0.5rem; + margin-bottom: 1rem; + margin-top: auto; + &:hover, + &:active, + &:focus { + background-color: var(--primary); + } + } + } + + form { + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: center; + margin-top: 2rem; + + label { + span { + display: block; + text-align: left; + font-size: 12px; + color: var(--black60); + } + } + + input { + box-sizing: border-box; + background-color: var(--white); + border: 1px solid var(--black10); + padding: 0.5rem; + margin-bottom: 1rem; + outline: none; + border-radius: var(--small-border-radius); + width: 300px; + color: var(--black100); + &:hover, + &:active, + &:focus { + border: 1px solid var(--black100); + } + } + } + + &__read-more { + color: var(--black80); + a { + color: var(--black100); + text-decoration: none; + } + } +} diff --git a/admin-ui/src/pages/Dashboard.tsx b/admin-ui/src/pages/Dashboard.tsx new file mode 100644 index 0000000..39c4d18 --- /dev/null +++ b/admin-ui/src/pages/Dashboard.tsx @@ -0,0 +1,12 @@ +import * as React from "react"; +import Card from "@material-ui/core/Card"; +import CardContent from "@material-ui/core/CardContent"; +import { Title } from "react-admin"; +const Dashboard = () => ( + + + <CardContent>Welcome</CardContent> + </Card> +); + +export default Dashboard; diff --git a/admin-ui/src/reportWebVitals.ts b/admin-ui/src/reportWebVitals.ts new file mode 100644 index 0000000..821a6cd --- /dev/null +++ b/admin-ui/src/reportWebVitals.ts @@ -0,0 +1,17 @@ +import { ReportHandler } from "web-vitals"; + +const reportWebVitals = (onPerfEntry?: ReportHandler): void => { + if (onPerfEntry && onPerfEntry instanceof Function) { + void import("web-vitals").then( + ({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { + getCLS(onPerfEntry); + getFID(onPerfEntry); + getFCP(onPerfEntry); + getLCP(onPerfEntry); + getTTFB(onPerfEntry); + } + ); + } +}; + +export default reportWebVitals; diff --git a/admin-ui/src/setupTests.ts b/admin-ui/src/setupTests.ts new file mode 100644 index 0000000..1dd407a --- /dev/null +++ b/admin-ui/src/setupTests.ts @@ -0,0 +1,5 @@ +// jest-dom adds custom jest matchers for asserting on DOM nodes. +// allows you to do things like: +// expect(element).toHaveTextContent(/react/i) +// learn more: https://github.com/testing-library/jest-dom +import "@testing-library/jest-dom"; diff --git a/admin-ui/src/theme/theme.ts b/admin-ui/src/theme/theme.ts new file mode 100644 index 0000000..56a1153 --- /dev/null +++ b/admin-ui/src/theme/theme.ts @@ -0,0 +1,33 @@ +import { defaultTheme } from "react-admin"; +import { createTheme, ThemeOptions } from "@material-ui/core/styles"; +import { merge } from "lodash"; +import createPalette from "@material-ui/core/styles/createPalette"; + +const palette = createPalette( + merge({}, defaultTheme.palette, { + primary: { + main: "#20a4f3", + }, + secondary: { + main: "#7950ed", + }, + error: { + main: "#e93c51", + }, + warning: { + main: "#f6aa50", + }, + info: { + main: "#144bc1", + }, + success: { + main: "#31c587", + }, + }) +); + +const themeOptions: ThemeOptions = { + palette, +}; + +export const theme = createTheme(merge({}, defaultTheme, themeOptions)); diff --git a/admin-ui/src/types.ts b/admin-ui/src/types.ts new file mode 100644 index 0000000..45a457d --- /dev/null +++ b/admin-ui/src/types.ts @@ -0,0 +1,13 @@ +import { JsonValue } from "type-fest"; + +export type Credentials = { + username: string; + password: string; +}; +export type LoginMutateResult = { + login: { + username: string; + accessToken: string; + }; +}; +export type InputJsonValue = Omit<JsonValue, "null">; diff --git a/admin-ui/src/user/EnumRoles.ts b/admin-ui/src/user/EnumRoles.ts new file mode 100644 index 0000000..3df7048 --- /dev/null +++ b/admin-ui/src/user/EnumRoles.ts @@ -0,0 +1,3 @@ +export enum EnumRoles { + User = "user", +} diff --git a/admin-ui/src/user/RolesOptions.ts b/admin-ui/src/user/RolesOptions.ts new file mode 100644 index 0000000..2f12fcf --- /dev/null +++ b/admin-ui/src/user/RolesOptions.ts @@ -0,0 +1,12 @@ +//@ts-ignore +import { ROLES } from "./roles"; + +declare interface Role { + name: string; + displayName: string; +} + +export const ROLES_OPTIONS = ROLES.map((role: Role) => ({ + value: role.name, + label: role.displayName, +})); diff --git a/admin-ui/src/user/UserCreate.tsx b/admin-ui/src/user/UserCreate.tsx new file mode 100644 index 0000000..def7787 --- /dev/null +++ b/admin-ui/src/user/UserCreate.tsx @@ -0,0 +1,31 @@ +import * as React from "react"; + +import { + Create, + SimpleForm, + CreateProps, + TextInput, + PasswordInput, + SelectArrayInput, +} from "react-admin"; + +import { ROLES_OPTIONS } from "../user/RolesOptions"; + +export const UserCreate = (props: CreateProps): React.ReactElement => { + return ( + <Create {...props}> + <SimpleForm> + <TextInput label="First Name" source="firstName" /> + <TextInput label="Last Name" source="lastName" /> + <PasswordInput label="Password" source="password" /> + <SelectArrayInput + source="roles" + choices={ROLES_OPTIONS} + optionText="label" + optionValue="value" + /> + <TextInput label="Username" source="username" /> + </SimpleForm> + </Create> + ); +}; diff --git a/admin-ui/src/user/UserEdit.tsx b/admin-ui/src/user/UserEdit.tsx new file mode 100644 index 0000000..8565bf9 --- /dev/null +++ b/admin-ui/src/user/UserEdit.tsx @@ -0,0 +1,29 @@ +import * as React from "react"; +import { + Edit, + SimpleForm, + EditProps, + TextInput, + PasswordInput, + SelectArrayInput, +} from "react-admin"; +import { ROLES_OPTIONS } from "../user/RolesOptions"; + +export const UserEdit = (props: EditProps): React.ReactElement => { + return ( + <Edit {...props}> + <SimpleForm> + <TextInput label="First Name" source="firstName" /> + <TextInput label="Last Name" source="lastName" /> + <PasswordInput label="Password" source="password" /> + <SelectArrayInput + source="roles" + choices={ROLES_OPTIONS} + optionText="label" + optionValue="value" + /> + <TextInput label="Username" source="username" /> + </SimpleForm> + </Edit> + ); +}; diff --git a/admin-ui/src/user/UserList.tsx b/admin-ui/src/user/UserList.tsx new file mode 100644 index 0000000..aa820f4 --- /dev/null +++ b/admin-ui/src/user/UserList.tsx @@ -0,0 +1,25 @@ +import * as React from "react"; +import { List, Datagrid, ListProps, DateField, TextField } from "react-admin"; +import Pagination from "../Components/Pagination"; + +export const UserList = (props: ListProps): React.ReactElement => { + return ( + <List + {...props} + bulkActionButtons={false} + title={"Users"} + perPage={50} + pagination={<Pagination />} + > + <Datagrid rowClick="show"> + <DateField source="createdAt" label="Created At" /> + <TextField label="First Name" source="firstName" /> + <TextField label="ID" source="id" /> + <TextField label="Last Name" source="lastName" /> + <TextField label="Roles" source="roles" /> + <DateField source="updatedAt" label="Updated At" /> + <TextField label="Username" source="username" /> + </Datagrid> + </List> + ); +}; diff --git a/admin-ui/src/user/UserShow.tsx b/admin-ui/src/user/UserShow.tsx new file mode 100644 index 0000000..dc33a5b --- /dev/null +++ b/admin-ui/src/user/UserShow.tsx @@ -0,0 +1,24 @@ +import * as React from "react"; +import { + Show, + SimpleShowLayout, + ShowProps, + DateField, + TextField, +} from "react-admin"; + +export const UserShow = (props: ShowProps): React.ReactElement => { + return ( + <Show {...props}> + <SimpleShowLayout> + <DateField source="createdAt" label="Created At" /> + <TextField label="First Name" source="firstName" /> + <TextField label="ID" source="id" /> + <TextField label="Last Name" source="lastName" /> + <TextField label="Roles" source="roles" /> + <DateField source="updatedAt" label="Updated At" /> + <TextField label="Username" source="username" /> + </SimpleShowLayout> + </Show> + ); +}; diff --git a/admin-ui/src/user/UserTitle.ts b/admin-ui/src/user/UserTitle.ts new file mode 100644 index 0000000..336f609 --- /dev/null +++ b/admin-ui/src/user/UserTitle.ts @@ -0,0 +1,7 @@ +import { User as TUser } from "../api/user/User"; + +export const USER_TITLE_FIELD = "firstName"; + +export const UserTitle = (record: TUser): string => { + return record.firstName?.toString() || String(record.id); +}; diff --git a/admin-ui/src/user/roles.ts b/admin-ui/src/user/roles.ts new file mode 100644 index 0000000..732870a --- /dev/null +++ b/admin-ui/src/user/roles.ts @@ -0,0 +1,6 @@ +export const ROLES = [ + { + name: "user", + displayName: "User", + }, +]; diff --git a/admin-ui/src/util/BooleanFilter.ts b/admin-ui/src/util/BooleanFilter.ts new file mode 100644 index 0000000..a142d58 --- /dev/null +++ b/admin-ui/src/util/BooleanFilter.ts @@ -0,0 +1,4 @@ +export class BooleanFilter { + equals?: boolean; + not?: boolean; +} diff --git a/admin-ui/src/util/BooleanNullableFilter.ts b/admin-ui/src/util/BooleanNullableFilter.ts new file mode 100644 index 0000000..b94aefc --- /dev/null +++ b/admin-ui/src/util/BooleanNullableFilter.ts @@ -0,0 +1,4 @@ +export class BooleanNullableFilter { + equals?: boolean | null; + not?: boolean | null; +} diff --git a/admin-ui/src/util/DateTimeFilter.ts b/admin-ui/src/util/DateTimeFilter.ts new file mode 100644 index 0000000..cd8d213 --- /dev/null +++ b/admin-ui/src/util/DateTimeFilter.ts @@ -0,0 +1,10 @@ +export class DateTimeFilter { + equals?: Date; + not?: Date; + in?: Date[]; + notIn?: Date[]; + lt?: Date; + lte?: Date; + gt?: Date; + gte?: Date; +} diff --git a/admin-ui/src/util/DateTimeNullableFilter.ts b/admin-ui/src/util/DateTimeNullableFilter.ts new file mode 100644 index 0000000..2f9c7b3 --- /dev/null +++ b/admin-ui/src/util/DateTimeNullableFilter.ts @@ -0,0 +1,10 @@ +export class DateTimeNullableFilter { + equals?: Date | null; + in?: Date[] | null; + notIn?: Date[] | null; + lt?: Date; + lte?: Date; + gt?: Date; + gte?: Date; + not?: Date; +} diff --git a/admin-ui/src/util/FloatFilter.ts b/admin-ui/src/util/FloatFilter.ts new file mode 100644 index 0000000..62aeb14 --- /dev/null +++ b/admin-ui/src/util/FloatFilter.ts @@ -0,0 +1,10 @@ +export class FloatFilter { + equals?: number; + in?: number[]; + notIn?: number[]; + lt?: number; + lte?: number; + gt?: number; + gte?: number; + not?: number; +} diff --git a/admin-ui/src/util/FloatNullableFilter.ts b/admin-ui/src/util/FloatNullableFilter.ts new file mode 100644 index 0000000..d7bb163 --- /dev/null +++ b/admin-ui/src/util/FloatNullableFilter.ts @@ -0,0 +1,10 @@ +export class FloatNullableFilter { + equals?: number | null; + in?: number[] | null; + notIn?: number[] | null; + lt?: number; + lte?: number; + gt?: number; + gte?: number; + not?: number; +} diff --git a/admin-ui/src/util/IntFilter.ts b/admin-ui/src/util/IntFilter.ts new file mode 100644 index 0000000..3dc0221 --- /dev/null +++ b/admin-ui/src/util/IntFilter.ts @@ -0,0 +1,10 @@ +export class IntFilter { + equals?: number; + in?: number[]; + notIn?: number[]; + lt?: number; + lte?: number; + gt?: number; + gte?: number; + not?: number; +} diff --git a/admin-ui/src/util/IntNullableFilter.ts b/admin-ui/src/util/IntNullableFilter.ts new file mode 100644 index 0000000..2107cae --- /dev/null +++ b/admin-ui/src/util/IntNullableFilter.ts @@ -0,0 +1,10 @@ +export class IntNullableFilter { + equals?: number | null; + in?: number[] | null; + notIn?: number[] | null; + lt?: number; + lte?: number; + gt?: number; + gte?: number; + not?: number; +} diff --git a/admin-ui/src/util/JsonFilter.ts b/admin-ui/src/util/JsonFilter.ts new file mode 100644 index 0000000..cc44763 --- /dev/null +++ b/admin-ui/src/util/JsonFilter.ts @@ -0,0 +1,5 @@ +import { InputJsonValue } from "../types"; +export class JsonFilter { + equals?: InputJsonValue; + not?: InputJsonValue; +} diff --git a/admin-ui/src/util/JsonNullableFilter.ts b/admin-ui/src/util/JsonNullableFilter.ts new file mode 100644 index 0000000..e6d1506 --- /dev/null +++ b/admin-ui/src/util/JsonNullableFilter.ts @@ -0,0 +1,5 @@ +import { JsonValue } from "type-fest"; +export class JsonNullableFilter { + equals?: JsonValue | null; + not?: JsonValue | null; +} diff --git a/admin-ui/src/util/MetaQueryPayload.ts b/admin-ui/src/util/MetaQueryPayload.ts new file mode 100644 index 0000000..bc3175b --- /dev/null +++ b/admin-ui/src/util/MetaQueryPayload.ts @@ -0,0 +1,3 @@ +export class MetaQueryPayload { + count!: number; +} diff --git a/admin-ui/src/util/QueryMode.ts b/admin-ui/src/util/QueryMode.ts new file mode 100644 index 0000000..8a2164e --- /dev/null +++ b/admin-ui/src/util/QueryMode.ts @@ -0,0 +1,4 @@ +export enum QueryMode { + Default = "default", + Insensitive = "insensitive", +} diff --git a/admin-ui/src/util/SortOrder.ts b/admin-ui/src/util/SortOrder.ts new file mode 100644 index 0000000..a5bcdb6 --- /dev/null +++ b/admin-ui/src/util/SortOrder.ts @@ -0,0 +1,4 @@ +export enum SortOrder { + Asc = "asc", + Desc = "desc", +} diff --git a/admin-ui/src/util/StringFilter.ts b/admin-ui/src/util/StringFilter.ts new file mode 100644 index 0000000..c2e26c5 --- /dev/null +++ b/admin-ui/src/util/StringFilter.ts @@ -0,0 +1,16 @@ +import { QueryMode } from "./QueryMode"; + +export class StringFilter { + equals?: string; + in?: string[]; + notIn?: string[]; + lt?: string; + lte?: string; + gt?: string; + gte?: string; + contains?: string; + startsWith?: string; + endsWith?: string; + mode?: QueryMode; + not?: string; +} diff --git a/admin-ui/src/util/StringNullableFilter.ts b/admin-ui/src/util/StringNullableFilter.ts new file mode 100644 index 0000000..e1e37ec --- /dev/null +++ b/admin-ui/src/util/StringNullableFilter.ts @@ -0,0 +1,15 @@ +import { QueryMode } from "./QueryMode"; +export class StringNullableFilter { + equals?: string | null; + in?: string[] | null; + notIn?: string[] | null; + lt?: string; + lte?: string; + gt?: string; + gte?: string; + contains?: string; + startsWith?: string; + endsWith?: string; + mode?: QueryMode; + not?: string; +} diff --git a/admin-ui/tsconfig.json b/admin-ui/tsconfig.json new file mode 100644 index 0000000..31cc780 --- /dev/null +++ b/admin-ui/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es5", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true + }, + "include": ["src"], + "exclude": ["./node_modules"] +} diff --git a/server/.dockerignore b/server/.dockerignore new file mode 100644 index 0000000..cb5c30b --- /dev/null +++ b/server/.dockerignore @@ -0,0 +1,8 @@ +.dockerignore +docker-compose.yml +Dockerfile +dist/ +node_modules +.env +.gitignore +.prettierignore \ No newline at end of file diff --git a/server/.env b/server/.env new file mode 100644 index 0000000..714edfe --- /dev/null +++ b/server/.env @@ -0,0 +1,10 @@ +BCRYPT_SALT=10 +COMPOSE_PROJECT_NAME=amp_clok9hy1s0haskj01jpbldjwk +PORT=3000 +DB_USER=root +DB_PASSWORD=admin +DB_PORT=3306 +DB_NAME=my-db +DB_URL=mysql://root:admin@localhost:3306/my-db +JWT_SECRET_KEY=Change_ME!!! +JWT_EXPIRATION=2d \ No newline at end of file diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..08c9980 --- /dev/null +++ b/server/.gitignore @@ -0,0 +1,5 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +/node_modules +/dist +.DS_Store diff --git a/server/.prettierignore b/server/.prettierignore new file mode 100644 index 0000000..e48f355 --- /dev/null +++ b/server/.prettierignore @@ -0,0 +1,5 @@ +node_modules/ +dist/ +prisma/migrations/ +package-lock.json +coverage/ \ No newline at end of file diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 0000000..80dd8d3 --- /dev/null +++ b/server/Dockerfile @@ -0,0 +1,68 @@ +# multi-stage: base (build) +FROM node:18.13.0 AS base + +# create directory where the application will be built +WORKDIR /app + +# copy over the dependency manifests, both the package.json +# and the package-lock.json are copied over +COPY package*.json ./ + +# installs packages and their dependencies +RUN npm install + +# copy over the prisma schema +COPY prisma/schema.prisma ./prisma/ + +# generate the prisma client based on the schema +RUN npm run prisma:generate + +# copy over the code base +COPY . . + +# create the bundle of the application +RUN npm run build + +# multi-stage: production (runtime) +FROM node:18.13.0-slim AS production + +# create arguments of builds time variables +ARG user=amplication +ARG group=${user} +ARG uid=1001 +ARG gid=$uid + +# [temporary] work around to be able to run prisma +RUN apt-get update -y && apt-get install -y openssl + +# create directory where the application will be executed from +WORKDIR /app + +# add the user and group +RUN groupadd --gid ${gid} ${user} +RUN useradd --uid ${uid} --gid ${gid} -m ${user} + +# copy over the bundled code from the build stage +COPY --from=base /app/node_modules/ ./node_modules +COPY --from=base /app/package.json ./package.json +COPY --from=base /app/dist ./dist +COPY --from=base /app/prisma ./prisma +COPY --from=base /app/scripts ./scripts +COPY --from=base /app/src ./src +COPY --from=base /app/tsconfig* ./ + +# change ownership of the workspace directory +RUN chown -R ${uid}:${gid} /app/ + +# get rid of the development dependencies +RUN npm install --production + +# set user to the created non-privileged user +USER ${user} + +# expose a specific port on the docker container +ENV PORT=3000 +EXPOSE ${PORT} + +# start the server using the previously build application +CMD [ "node", "./dist/main.js" ] diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..6db8e75 --- /dev/null +++ b/server/README.md @@ -0,0 +1,64 @@ +<p align="right"> + <a href="https://amplication.com" target="_blank"> + <img alt="amplication-logo" height="70" alt="Amplication Logo" src="https://amplication.com/images/amplication-logo-purple.svg"/> + </a> +</p> + +# Introduction + +This service was generated with Amplication. The server-side of the generated project. This component provides the different backend services - i.e., REST API, GraphQL API, authentication, authorization, logging, data validation and the connection to the database. Additional information about the server component and the architecture around it, can be found on the [documentation](https://docs.amplication.com/guides/getting-started) site. + +# Getting started + +## Step 1: Configuration + +Configuration for the server component can be provided through the use of environment variables. These can be passed to the application via the use of the `.env` file in the base directory of the generated service. Below a table can be found which show the different variables that can be passed - these are the variables which exist by default, through the use of plugins additional integrations could require additional values. These values are provided default values after generation, change them to the desired values. + +| Variable | Description | Value | +| -------------------- | -------------------------------------------- | ------------------------------------------------------------------- | +| BCRYPT_SALT | the string used for hashing | [random-string] | +| COMPOSE_PROJECT_NAME | the identifier of the service plus prefix | amp_[service-identifier] | +| PORT | the port on which to run the server | 3000 | +| DB_URL | the connection url for the database | [db-provider]://[username]:[password]@localhost:[db-port]/[db-name] | +| DB_PORT | the port used by the database instance | [db-provider-port] | +| DB_USER | the username used to connect to the database | [username] | +| DB_PASSWORD | the password used to connect to the database | [password] | +| DB_NAME | the name of the database | [service-name] / [project-name] | +| JWT_SECRET_KEY | the secret used to sign the json-web token | [secret] | +| JWT_EXPIRATION | the expiration time for the json-web token | 2d | + +> **Note** +> Amplication generates default values and stores them under the .env file. It is advised to use some form of secrets manager/vault solution when using in production. + +## Step 2.1: Scripts - pre-requisites + +After configuration of the server the next step would be to run the application. Before running the server side of the component, make sure that the different pre-requisites are met - i.e., node.js [^16.x], npm, docker. After the setup of the pre-requisites the server component can be started. + +```sh +# installation of the dependencies +$ npm install + +# generate the prisma client +$ npm run prisma:generate +``` + +## Step 2.2: Scripts - local development + +```sh +# start the database where the server component will connect to +$ npm run docker:dev + +# initialize the database +$ npm run db:init + +# start the server component +$ npm run start +``` +By default, your app comes with one user with the username "admin" and password "admin". + +## Step 2.2: Scripts - container based development + +```shell +# start the server component as a docker container +$ npm run compose:up +``` diff --git a/server/docker-compose.dev.yml b/server/docker-compose.dev.yml new file mode 100644 index 0000000..e2c7ce0 --- /dev/null +++ b/server/docker-compose.dev.yml @@ -0,0 +1,29 @@ +version: "3" +services: + db: + image: mysql + command: --default-authentication-plugin=mysql_native_password + restart: always + ports: + - ${DB_PORT}:3306 + environment: + MYSQL_ROOT_PASSWORD: ${DB_PASSWORD} + healthcheck: + test: + - CMD + - mysqladmin + - ping + - -h + - localhost + - -u + - ${DB_USER} + timeout: 45s + interval: 10s + retries: 10 + adminer: + image: adminer + restart: always + ports: + - 1234:8080 +volumes: + mysql: ~ diff --git a/server/docker-compose.yml b/server/docker-compose.yml new file mode 100644 index 0000000..3eddc28 --- /dev/null +++ b/server/docker-compose.yml @@ -0,0 +1,57 @@ +version: "3" +services: + server: + build: + context: . + args: + NPM_LOG_LEVEL: notice + ports: + - ${PORT}:3000 + environment: + BCRYPT_SALT: ${BCRYPT_SALT} + JWT_SECRET_KEY: ${JWT_SECRET_KEY} + JWT_EXPIRATION: ${JWT_EXPIRATION} + DB_URL: mysql://${DB_USER}:${DB_PASSWORD}@db:3306/${DB_NAME} + depends_on: + - migrate + restart: on-failure + migrate: + build: + context: . + args: + NPM_LOG_LEVEL: notice + command: npm run db:init + working_dir: /app/server + environment: + BCRYPT_SALT: ${BCRYPT_SALT} + DB_URL: mysql://${DB_USER}:${DB_PASSWORD}@db:3306/${DB_NAME} + depends_on: + db: + condition: service_healthy + adminer: + image: adminer + restart: always + ports: + - 1234:8080 + db: + image: mysql + command: --default-authentication-plugin=mysql_native_password + restart: always + ports: + - ${DB_PORT}:3306 + environment: + MYSQL_ROOT_PASSWORD: ${DB_PASSWORD} + healthcheck: + test: + - CMD + - mysqladmin + - ping + - -h + - localhost + - -u + - ${DB_USER} + timeout: 45s + interval: 10s + retries: 10 +volumes: + mysql: ~ diff --git a/server/nest-cli.json b/server/nest-cli.json new file mode 100644 index 0000000..fe51713 --- /dev/null +++ b/server/nest-cli.json @@ -0,0 +1,6 @@ +{ + "sourceRoot": "src", + "compilerOptions": { + "assets": ["swagger"] + } +} diff --git a/server/package.json b/server/package.json new file mode 100644 index 0000000..6d19d1d --- /dev/null +++ b/server/package.json @@ -0,0 +1,75 @@ +{ + "name": "@record/server", + "private": true, + "scripts": { + "start": "nest start", + "start:watch": "nest start --watch", + "start:debug": "nest start --debug --watch", + "build": "nest build", + "test": "jest", + "seed": "ts-node scripts/seed.ts", + "db:migrate-save": "prisma migrate dev", + "db:migrate-up": "prisma migrate deploy", + "db:clean": "prisma migrate reset", + "db:init": "run-s \"db:migrate-save -- --name 'initial version'\" db:migrate-up seed", + "prisma:generate": "prisma generate", + "docker:dev": "docker-compose -f docker-compose.dev.yml up -d", + "package:container": "docker build .", + "compose:up": "docker-compose up -d", + "compose:down": "docker-compose down --volumes" + }, + "dependencies": { + "@amplication/nest-access-control": "2.2.1", + "@apollo/server": "^4.9.4", + "@nestjs/apollo": "12.0.9", + "@nestjs/common": "10.2.7", + "@nestjs/config": "3.1.1", + "@nestjs/core": "10.2.7", + "@nestjs/graphql": "12.0.9", + "@nestjs/jwt": "^10.1.1", + "@nestjs/passport": "^10.0.2", + "@nestjs/platform-express": "10.2.7", + "@nestjs/serve-static": "4.0.0", + "@nestjs/swagger": "7.1.13", + "@prisma/client": "^5.4.2", + "@types/bcrypt": "5.0.0", + "bcrypt": "5.1.1", + "class-transformer": "0.5.1", + "class-validator": "0.14.0", + "dotenv": "16.3.1", + "graphql": "^16.8.1", + "graphql-type-json": "0.3.2", + "nest-access-control": "^3.1.0", + "npm-run-all": "4.1.5", + "passport": "0.6.0", + "passport-http": "0.3.0", + "passport-jwt": "4.0.1", + "reflect-metadata": "0.1.13", + "ts-node": "10.9.1", + "type-fest": "2.19.0", + "validator": "13.11.0" + }, + "devDependencies": { + "@nestjs/cli": "^10.1.18", + "@nestjs/testing": "^10.2.7", + "@types/express": "^4.17.19", + "@types/graphql-type-json": "0.3.3", + "@types/jest": "^29.5.5", + "@types/normalize-path": "3.0.0", + "@types/passport-http": "0.3.9", + "@types/passport-jwt": "3.0.10", + "@types/supertest": "^2.0.14", + "@types/validator": "^13.11.2", + "jest": "^29.7.0", + "jest-mock-extended": "^3.0.5", + "prisma": "^5.4.2", + "supertest": "^6.3.3", + "ts-jest": "^29.1.1", + "typescript": "^5.2.2" + }, + "jest": { + "preset": "ts-jest", + "testEnvironment": "node", + "modulePathIgnorePatterns": ["<rootDir>/dist/"] + } +} diff --git a/server/prisma/schema.prisma b/server/prisma/schema.prisma new file mode 100644 index 0000000..1379699 --- /dev/null +++ b/server/prisma/schema.prisma @@ -0,0 +1,19 @@ +datasource db { + provider = "mysql" + url = env("DB_URL") +} + +generator client { + provider = "prisma-client-js" +} + +model User { + createdAt DateTime @default(now()) + firstName String? + id String @id @default(cuid()) + lastName String? + password String + roles Json + updatedAt DateTime @updatedAt + username String @unique +} diff --git a/server/scripts/customSeed.ts b/server/scripts/customSeed.ts new file mode 100644 index 0000000..6baf5f6 --- /dev/null +++ b/server/scripts/customSeed.ts @@ -0,0 +1,17 @@ +import { PrismaClient } from "@prisma/client"; + +export async function customSeed() { + const client = new PrismaClient(); + const username = "admin"; + + //replace this sample code to populate your database + //with data that is required for your service to start + await client.user.update({ + where: { username: username }, + data: { + username, + }, + }); + + client.$disconnect(); +} diff --git a/server/scripts/seed.ts b/server/scripts/seed.ts new file mode 100644 index 0000000..272dddd --- /dev/null +++ b/server/scripts/seed.ts @@ -0,0 +1,49 @@ +import * as dotenv from "dotenv"; +import { PrismaClient } from "@prisma/client"; +import { customSeed } from "./customSeed"; +import { Salt, parseSalt } from "../src/auth/password.service"; +import { hash } from "bcrypt"; + +if (require.main === module) { + dotenv.config(); + + const { BCRYPT_SALT } = process.env; + + if (!BCRYPT_SALT) { + throw new Error("BCRYPT_SALT environment variable must be defined"); + } + const salt = parseSalt(BCRYPT_SALT); + + seed(salt).catch((error) => { + console.error(error); + process.exit(1); + }); +} + +async function seed(bcryptSalt: Salt) { + console.info("Seeding database..."); + + const client = new PrismaClient(); + + const data = { + username: "admin", + password: await hash("admin", bcryptSalt), + roles: ["user"], + }; + + await client.user.upsert({ + where: { + username: data.username, + }, + + update: {}, + create: data, + }); + + void client.$disconnect(); + + console.info("Seeding database with custom seed..."); + customSeed(); + + console.info("Seeded database successfully"); +} diff --git a/server/src/app.module.ts b/server/src/app.module.ts new file mode 100644 index 0000000..2fcb3b5 --- /dev/null +++ b/server/src/app.module.ts @@ -0,0 +1,46 @@ +import { Module } from "@nestjs/common"; +import { UserModule } from "./user/user.module"; +import { HealthModule } from "./health/health.module"; +import { PrismaModule } from "./prisma/prisma.module"; +import { SecretsManagerModule } from "./providers/secrets/secretsManager.module"; +import { ServeStaticModule } from "@nestjs/serve-static"; +import { ServeStaticOptionsService } from "./serveStaticOptions.service"; +import { ConfigModule, ConfigService } from "@nestjs/config"; +import { GraphQLModule } from "@nestjs/graphql"; +import { ApolloDriver, ApolloDriverConfig } from "@nestjs/apollo"; + +import { ACLModule } from "./auth/acl.module"; +import { AuthModule } from "./auth/auth.module"; + +@Module({ + controllers: [], + imports: [ + ACLModule, + AuthModule, + UserModule, + HealthModule, + PrismaModule, + SecretsManagerModule, + ConfigModule.forRoot({ isGlobal: true }), + ServeStaticModule.forRootAsync({ + useClass: ServeStaticOptionsService, + }), + GraphQLModule.forRootAsync<ApolloDriverConfig>({ + driver: ApolloDriver, + useFactory: (configService: ConfigService) => { + const playground = configService.get("GRAPHQL_PLAYGROUND"); + const introspection = configService.get("GRAPHQL_INTROSPECTION"); + return { + autoSchemaFile: "schema.graphql", + sortSchema: true, + playground, + introspection: playground || introspection, + }; + }, + inject: [ConfigService], + imports: [ConfigModule], + }), + ], + providers: [], +}) +export class AppModule {} diff --git a/server/src/auth/Credentials.ts b/server/src/auth/Credentials.ts new file mode 100644 index 0000000..9ac6798 --- /dev/null +++ b/server/src/auth/Credentials.ts @@ -0,0 +1,21 @@ +import { ApiProperty } from "@nestjs/swagger"; +import { InputType, Field } from "@nestjs/graphql"; +import { IsString } from "class-validator"; + +@InputType() +export class Credentials { + @ApiProperty({ + required: true, + type: String, + }) + @IsString() + @Field(() => String, { nullable: false }) + username!: string; + @ApiProperty({ + required: true, + type: String, + }) + @IsString() + @Field(() => String, { nullable: false }) + password!: string; +} diff --git a/server/src/auth/IAuthStrategy.ts b/server/src/auth/IAuthStrategy.ts new file mode 100644 index 0000000..5db10cf --- /dev/null +++ b/server/src/auth/IAuthStrategy.ts @@ -0,0 +1,5 @@ +import { UserInfo } from "./UserInfo"; + +export interface IAuthStrategy { + validate: (...any: any) => Promise<UserInfo>; +} diff --git a/server/src/auth/ITokenService.ts b/server/src/auth/ITokenService.ts new file mode 100644 index 0000000..7983189 --- /dev/null +++ b/server/src/auth/ITokenService.ts @@ -0,0 +1,9 @@ +export interface ITokenPayload { + id: string; + username: string; + password: string; +} + +export interface ITokenService { + createToken: ({ id, username, password }: ITokenPayload) => Promise<string>; +} diff --git a/server/src/auth/LoginArgs.ts b/server/src/auth/LoginArgs.ts new file mode 100644 index 0000000..66a0b2f --- /dev/null +++ b/server/src/auth/LoginArgs.ts @@ -0,0 +1,12 @@ +import { ArgsType, Field } from "@nestjs/graphql"; +import { ValidateNested } from "class-validator"; +import { Type } from "class-transformer"; +import { Credentials } from "./Credentials"; + +@ArgsType() +export class LoginArgs { + @Field(() => Credentials, { nullable: false }) + @Type(() => Credentials) + @ValidateNested() + credentials!: Credentials; +} diff --git a/server/src/auth/UserInfo.ts b/server/src/auth/UserInfo.ts new file mode 100644 index 0000000..ef61dc4 --- /dev/null +++ b/server/src/auth/UserInfo.ts @@ -0,0 +1,14 @@ +import { Field, ObjectType } from "@nestjs/graphql"; +import { User } from "../user/base/User"; + +@ObjectType() +export class UserInfo implements Partial<User> { + @Field(() => String) + id!: string; + @Field(() => String) + username!: string; + @Field(() => [String]) + roles!: string[]; + @Field(() => String, { nullable: true }) + accessToken?: string; +} diff --git a/server/src/auth/abac.util.ts b/server/src/auth/abac.util.ts new file mode 100644 index 0000000..2f0dcab --- /dev/null +++ b/server/src/auth/abac.util.ts @@ -0,0 +1,19 @@ +import { Permission } from "accesscontrol"; + +/** + * @returns attributes not allowed to appear on given data according to given + * attributeMatchers + */ +export function getInvalidAttributes( + permission: Permission, + // eslint-disable-next-line @typescript-eslint/ban-types + data: Object +): string[] { + // The structuredClone call is necessary because the + // `Permission.filter` function doesn't consider objects + // with null prototypes. And in graphql requests, the + // object passed here by the request interceptor is an object + // with a null prototype. + const filteredData = permission.filter(structuredClone(data)); + return Object.keys(data).filter((key) => !(key in filteredData)); +} diff --git a/server/src/auth/acl.module.ts b/server/src/auth/acl.module.ts new file mode 100644 index 0000000..eb90005 --- /dev/null +++ b/server/src/auth/acl.module.ts @@ -0,0 +1,7 @@ +import { AccessControlModule, RolesBuilder } from "nest-access-control"; +// @ts-ignore +// eslint-disable-next-line import/no-unresolved +import grants from "../grants.json"; + +// eslint-disable-next-line @typescript-eslint/naming-convention +export const ACLModule = AccessControlModule.forRoles(new RolesBuilder(grants)); diff --git a/server/src/auth/auth.controller.ts b/server/src/auth/auth.controller.ts new file mode 100644 index 0000000..7ae732f --- /dev/null +++ b/server/src/auth/auth.controller.ts @@ -0,0 +1,15 @@ +import { Body, Controller, Post } from "@nestjs/common"; +import { ApiTags } from "@nestjs/swagger"; +import { AuthService } from "./auth.service"; +import { Credentials } from "../auth/Credentials"; +import { UserInfo } from "./UserInfo"; + +@ApiTags("auth") +@Controller() +export class AuthController { + constructor(private readonly authService: AuthService) {} + @Post("login") + async login(@Body() body: Credentials): Promise<UserInfo> { + return this.authService.login(body); + } +} diff --git a/server/src/auth/auth.module.ts b/server/src/auth/auth.module.ts new file mode 100644 index 0000000..73c8725 --- /dev/null +++ b/server/src/auth/auth.module.ts @@ -0,0 +1,54 @@ +import { forwardRef, Module } from "@nestjs/common"; +import { ConfigService } from "@nestjs/config"; +import { JwtModule } from "@nestjs/jwt"; +import { PassportModule } from "@nestjs/passport"; +import { JWT_EXPIRATION, JWT_SECRET_KEY } from "../constants"; +import { SecretsManagerModule } from "../providers/secrets/secretsManager.module"; +import { SecretsManagerService } from "../providers/secrets/secretsManager.service"; +import { AuthController } from "./auth.controller"; +import { AuthResolver } from "./auth.resolver"; +import { AuthService } from "./auth.service"; +import { JwtStrategy } from "./jwt/jwt.strategy"; +import { jwtSecretFactory } from "./jwt/jwtSecretFactory"; +import { PasswordService } from "./password.service"; +import { TokenService } from "./token.service"; +import { UserModule } from "../user/user.module"; +@Module({ + imports: [ + forwardRef(() => UserModule), + PassportModule, + SecretsManagerModule, + JwtModule.registerAsync({ + imports: [SecretsManagerModule], + inject: [SecretsManagerService, ConfigService], + useFactory: async ( + secretsService: SecretsManagerService, + configService: ConfigService + ) => { + const secret = await secretsService.getSecret<string>(JWT_SECRET_KEY); + const expiresIn = configService.get(JWT_EXPIRATION); + if (!secret) { + throw new Error("Didn't get a valid jwt secret"); + } + if (!expiresIn) { + throw new Error("Jwt expire in value is not valid"); + } + return { + secret: secret, + signOptions: { expiresIn }, + }; + }, + }), + ], + providers: [ + AuthService, + PasswordService, + AuthResolver, + JwtStrategy, + jwtSecretFactory, + TokenService, + ], + controllers: [AuthController], + exports: [AuthService, PasswordService], +}) +export class AuthModule {} diff --git a/server/src/auth/auth.resolver.ts b/server/src/auth/auth.resolver.ts new file mode 100644 index 0000000..c186f41 --- /dev/null +++ b/server/src/auth/auth.resolver.ts @@ -0,0 +1,23 @@ +import * as common from "@nestjs/common"; +import { Args, Mutation, Query, Resolver } from "@nestjs/graphql"; +import * as gqlACGuard from "../auth/gqlAC.guard"; +import { AuthService } from "./auth.service"; +import { GqlDefaultAuthGuard } from "./gqlDefaultAuth.guard"; +import { UserData } from "./userData.decorator"; +import { LoginArgs } from "./LoginArgs"; +import { UserInfo } from "./UserInfo"; + +@Resolver(UserInfo) +export class AuthResolver { + constructor(private readonly authService: AuthService) {} + @Mutation(() => UserInfo) + async login(@Args() args: LoginArgs): Promise<UserInfo> { + return this.authService.login(args.credentials); + } + + @Query(() => UserInfo) + @common.UseGuards(GqlDefaultAuthGuard, gqlACGuard.GqlACGuard) + async userInfo(@UserData() entityInfo: UserInfo): Promise<UserInfo> { + return entityInfo; + } +} diff --git a/server/src/auth/auth.service.spec.ts b/server/src/auth/auth.service.spec.ts new file mode 100644 index 0000000..72fd2d3 --- /dev/null +++ b/server/src/auth/auth.service.spec.ts @@ -0,0 +1,114 @@ +import { Test, TestingModule } from "@nestjs/testing"; +import { AuthService } from "./auth.service"; +import { Credentials } from "./Credentials"; +import { PasswordService } from "./password.service"; +import { TokenService } from "./token.service"; +import { VALID_ID } from "../tests/auth/constants"; +import { UserService } from "../user/user.service"; + +const VALID_CREDENTIALS: Credentials = { + username: "Valid User", + password: "Valid User Password", +}; +const INVALID_CREDENTIALS: Credentials = { + username: "Invalid User", + password: "Invalid User Password", +}; +const USER: any = { + ...VALID_CREDENTIALS, + createdAt: new Date(), + firstName: "ofek", + id: VALID_ID, + lastName: "gabay", + roles: ["admin"], + updatedAt: new Date(), +}; + +const SIGN_TOKEN = "SIGN_TOKEN"; + +const authEntityService = { + findOne(args: { where: { username: string } }): any | null { + if (args.where.username === VALID_CREDENTIALS.username) { + return USER; + } + return null; + }, +}; + +const passwordService = { + compare(password: string, encrypted: string) { + return true; + }, +}; + +const tokenService = { + createToken(username: string, password: string) { + return SIGN_TOKEN; + }, +}; + +describe("AuthService", () => { + //ARRANGE + let service: AuthService; + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [ + { + provide: UserService, + useValue: authEntityService, + }, + { + provide: PasswordService, + useValue: passwordService, + }, + { + provide: TokenService, + useValue: tokenService, + }, + AuthService, + ], + }).compile(); + + service = module.get<AuthService>(AuthService); + }); + + it("should be defined", () => { + expect(service).toBeDefined(); + }); + + describe("Testing the authService.validateUser()", () => { + it("should validate a valid user", async () => { + await expect( + service.validateUser( + VALID_CREDENTIALS.username, + VALID_CREDENTIALS.password + ) + ).resolves.toEqual({ + username: USER.username, + roles: USER.roles, + id: USER.id, + }); + }); + + it("should not validate a invalid user", async () => { + await expect( + service.validateUser( + INVALID_CREDENTIALS.username, + INVALID_CREDENTIALS.password + ) + ).resolves.toBe(null); + }); + }); + + describe("Testing the authService.login()", () => { + it("should return userInfo object for correct username and password", async () => { + const loginResult = await service.login(VALID_CREDENTIALS); + expect(loginResult).toEqual({ + username: USER.username, + roles: USER.roles, + accessToken: SIGN_TOKEN, + id: USER.id, + }); + }); + }); +}); diff --git a/server/src/auth/auth.service.ts b/server/src/auth/auth.service.ts new file mode 100644 index 0000000..f5a74ba --- /dev/null +++ b/server/src/auth/auth.service.ts @@ -0,0 +1,49 @@ +import { Injectable, UnauthorizedException } from "@nestjs/common"; +import { Credentials } from "./Credentials"; +import { PasswordService } from "./password.service"; +import { TokenService } from "./token.service"; +import { UserInfo } from "./UserInfo"; +import { UserService } from "../user/user.service"; + +@Injectable() +export class AuthService { + constructor( + private readonly passwordService: PasswordService, + private readonly tokenService: TokenService, + private readonly userService: UserService + ) {} + + async validateUser( + username: string, + password: string + ): Promise<UserInfo | null> { + const user = await this.userService.findOne({ + where: { username }, + }); + if (user && (await this.passwordService.compare(password, user.password))) { + const { id, roles } = user; + const roleList = roles as string[]; + return { id, username, roles: roleList }; + } + return null; + } + async login(credentials: Credentials): Promise<UserInfo> { + const { username, password } = credentials; + const user = await this.validateUser( + credentials.username, + credentials.password + ); + if (!user) { + throw new UnauthorizedException("The passed credentials are incorrect"); + } + const accessToken = await this.tokenService.createToken({ + id: user.id, + username, + password, + }); + return { + accessToken, + ...user, + }; + } +} diff --git a/server/src/auth/base/token.service.base.ts b/server/src/auth/base/token.service.base.ts new file mode 100644 index 0000000..f25fdb5 --- /dev/null +++ b/server/src/auth/base/token.service.base.ts @@ -0,0 +1,25 @@ +/* eslint-disable import/no-unresolved */ +import { Injectable } from "@nestjs/common"; +import { JwtService } from "@nestjs/jwt"; +import { INVALID_PASSWORD_ERROR, INVALID_USERNAME_ERROR } from "../constants"; +import { ITokenService, ITokenPayload } from "../ITokenService"; +/** + * TokenServiceBase is a jwt bearer implementation of ITokenService + */ +@Injectable() +export class TokenServiceBase implements ITokenService { + constructor(protected readonly jwtService: JwtService) {} + /** + * + * @object { id: String, username: String, password: String} + * @returns a jwt token sign with the username and user id + */ + createToken({ id, username, password }: ITokenPayload): Promise<string> { + if (!username) return Promise.reject(INVALID_USERNAME_ERROR); + if (!password) return Promise.reject(INVALID_PASSWORD_ERROR); + return this.jwtService.signAsync({ + sub: id, + username, + }); + } +} diff --git a/server/src/auth/constants.ts b/server/src/auth/constants.ts new file mode 100644 index 0000000..59f9f7d --- /dev/null +++ b/server/src/auth/constants.ts @@ -0,0 +1,2 @@ +export const INVALID_USERNAME_ERROR = "Invalid username"; +export const INVALID_PASSWORD_ERROR = "Invalid password"; diff --git a/server/src/auth/defaultAuth.guard.ts b/server/src/auth/defaultAuth.guard.ts new file mode 100644 index 0000000..33a530c --- /dev/null +++ b/server/src/auth/defaultAuth.guard.ts @@ -0,0 +1,27 @@ +import { Observable } from "rxjs"; +import { ExecutionContext, Injectable } from "@nestjs/common"; +import { Reflector } from "@nestjs/core"; +import { IS_PUBLIC_KEY } from "../decorators/public.decorator"; +import { JwtAuthGuard } from "./jwt/jwtAuth.guard"; + +@Injectable() +export class DefaultAuthGuard extends JwtAuthGuard { + constructor(private readonly reflector: Reflector) { + super(); + } + + canActivate( + context: ExecutionContext + ): boolean | Promise<boolean> | Observable<any> { + const isPublic = this.reflector.get<boolean>( + IS_PUBLIC_KEY, + context.getHandler() + ); + + if (isPublic) { + return true; + } + + return super.canActivate(context); + } +} diff --git a/server/src/auth/gqlAC.guard.ts b/server/src/auth/gqlAC.guard.ts new file mode 100644 index 0000000..dacac55 --- /dev/null +++ b/server/src/auth/gqlAC.guard.ts @@ -0,0 +1,11 @@ +import { ExecutionContext } from "@nestjs/common"; +import { GqlExecutionContext } from "@nestjs/graphql"; +import { ACGuard } from "nest-access-control"; + +export class GqlACGuard<User extends any = any> extends ACGuard<User> { + async getUser(context: ExecutionContext): Promise<User> { + const ctx = GqlExecutionContext.create(context); + const request = ctx.getContext<{ req: { user: User } }>().req; + return request.user; + } +} diff --git a/server/src/auth/gqlDefaultAuth.guard.ts b/server/src/auth/gqlDefaultAuth.guard.ts new file mode 100644 index 0000000..0455177 --- /dev/null +++ b/server/src/auth/gqlDefaultAuth.guard.ts @@ -0,0 +1,14 @@ +import { ExecutionContext } from "@nestjs/common"; +import { GqlExecutionContext } from "@nestjs/graphql"; +import type { Request } from "express"; +// @ts-ignore +// eslint-disable-next-line +import { DefaultAuthGuard } from "./defaultAuth.guard"; + +export class GqlDefaultAuthGuard extends DefaultAuthGuard { + // This method is required for the interface - do not delete it. + getRequest<Request>(context: ExecutionContext): Request { + const ctx = GqlExecutionContext.create(context); + return ctx.getContext<{ req: Request }>().req; + } +} diff --git a/server/src/auth/gqlUserRoles.decorator.ts b/server/src/auth/gqlUserRoles.decorator.ts new file mode 100644 index 0000000..5ea256b --- /dev/null +++ b/server/src/auth/gqlUserRoles.decorator.ts @@ -0,0 +1,19 @@ +import { createParamDecorator, ExecutionContext } from "@nestjs/common"; +import { GqlExecutionContext } from "@nestjs/graphql"; + +/** + * Access the user roles from the request object i.e `req.user.roles`. + * + * You can pass an optional property key to the decorator to get it from the user object + * e.g `@UserRoles('permissions')` will return the `req.user.permissions` instead. + */ +export const UserRoles = createParamDecorator( + (data: string, context: ExecutionContext) => { + const ctx = GqlExecutionContext.create(context); + const request = ctx.getContext<{ req: { user: any } }>().req; + if (!request.user) { + return null; + } + return data ? request.user[data] : request.user.roles; + } +); diff --git a/server/src/auth/jwt/base/jwt.strategy.base.ts b/server/src/auth/jwt/base/jwt.strategy.base.ts new file mode 100644 index 0000000..3bbc919 --- /dev/null +++ b/server/src/auth/jwt/base/jwt.strategy.base.ts @@ -0,0 +1,40 @@ +import { UnauthorizedException } from "@nestjs/common"; +import { PassportStrategy } from "@nestjs/passport"; +import { ExtractJwt, Strategy } from "passport-jwt"; +import { IAuthStrategy } from "../../IAuthStrategy"; +import { UserInfo } from "../../UserInfo"; +import { UserService } from "../../../user/user.service"; + +export class JwtStrategyBase + extends PassportStrategy(Strategy) + implements IAuthStrategy +{ + constructor( + protected readonly secretOrKey: string, + protected readonly userService: UserService + ) { + super({ + jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), + ignoreExpiration: false, + secretOrKey, + }); + } + + async validate(payload: UserInfo): Promise<UserInfo> { + const { username } = payload; + const user = await this.userService.findOne({ + where: { username }, + }); + if (!user) { + throw new UnauthorizedException(); + } + if ( + !Array.isArray(user.roles) || + typeof user.roles !== "object" || + user.roles === null + ) { + throw new Error("User roles is not a valid value"); + } + return { ...user, roles: user.roles as string[] }; + } +} diff --git a/server/src/auth/jwt/jwt.strategy.ts b/server/src/auth/jwt/jwt.strategy.ts new file mode 100644 index 0000000..9e75f4c --- /dev/null +++ b/server/src/auth/jwt/jwt.strategy.ts @@ -0,0 +1,14 @@ +import { Inject, Injectable } from "@nestjs/common"; +import { JWT_SECRET_KEY } from "../../constants"; +import { JwtStrategyBase } from "./base/jwt.strategy.base"; +import { UserService } from "../../user/user.service"; + +@Injectable() +export class JwtStrategy extends JwtStrategyBase { + constructor( + @Inject(JWT_SECRET_KEY) secretOrKey: string, + protected readonly userService: UserService + ) { + super(secretOrKey, userService); + } +} diff --git a/server/src/auth/jwt/jwtAuth.guard.ts b/server/src/auth/jwt/jwtAuth.guard.ts new file mode 100644 index 0000000..f0c5570 --- /dev/null +++ b/server/src/auth/jwt/jwtAuth.guard.ts @@ -0,0 +1,3 @@ +import { AuthGuard } from "@nestjs/passport"; + +export class JwtAuthGuard extends AuthGuard("jwt") {} diff --git a/server/src/auth/jwt/jwtSecretFactory.ts b/server/src/auth/jwt/jwtSecretFactory.ts new file mode 100644 index 0000000..151e793 --- /dev/null +++ b/server/src/auth/jwt/jwtSecretFactory.ts @@ -0,0 +1,16 @@ +import { JWT_SECRET_KEY } from "../../constants"; +import { SecretsManagerService } from "../../providers/secrets/secretsManager.service"; + +export const jwtSecretFactory = { + provide: JWT_SECRET_KEY, + useFactory: async ( + secretsService: SecretsManagerService + ): Promise<string> => { + const secret = await secretsService.getSecret<string>(JWT_SECRET_KEY); + if (secret) { + return secret; + } + throw new Error("jwtSecretFactory missing secret"); + }, + inject: [SecretsManagerService], +}; diff --git a/server/src/auth/password.service.spec.ts b/server/src/auth/password.service.spec.ts new file mode 100644 index 0000000..309c8c0 --- /dev/null +++ b/server/src/auth/password.service.spec.ts @@ -0,0 +1,69 @@ +import { ConfigService } from "@nestjs/config"; +import { Test, TestingModule } from "@nestjs/testing"; +import { PasswordService } from "./password.service"; + +const EXAMPLE_PASSWORD = "examplePassword"; +const EXAMPLE_HASHED_PASSWORD = "exampleHashedPassword"; + +const EXAMPLE_SALT_OR_ROUNDS = 1; + +const configServiceGetMock = jest.fn(() => { + return EXAMPLE_SALT_OR_ROUNDS; +}); + +jest.mock("bcrypt", () => ({ + hash: jest.fn(), + compare: jest.fn(), +})); + +const { hash, compare } = jest.requireMock("bcrypt"); + +hash.mockImplementation(async () => EXAMPLE_HASHED_PASSWORD); + +compare.mockImplementation(async () => true); + +describe("PasswordService", () => { + let service: PasswordService; + + beforeEach(async () => { + jest.clearAllMocks(); + const module: TestingModule = await Test.createTestingModule({ + providers: [ + PasswordService, + { + provide: ConfigService, + useClass: jest.fn(() => ({ + get: configServiceGetMock, + })), + }, + ], + imports: [], + }).compile(); + + service = module.get<PasswordService>(PasswordService); + }); + + it("should be defined", () => { + expect(service).toBeDefined(); + }); + + it("should have salt defined", () => { + expect(service.salt).toEqual(EXAMPLE_SALT_OR_ROUNDS); + }); + + it("should compare a password", async () => { + const args = { + password: EXAMPLE_PASSWORD, + hashedPassword: EXAMPLE_HASHED_PASSWORD, + }; + await expect( + service.compare(args.password, args.hashedPassword) + ).resolves.toEqual(true); + }); + + it("should hash a password", async () => { + await expect(service.hash(EXAMPLE_PASSWORD)).resolves.toEqual( + EXAMPLE_HASHED_PASSWORD + ); + }); +}); diff --git a/server/src/auth/password.service.ts b/server/src/auth/password.service.ts new file mode 100644 index 0000000..377b64b --- /dev/null +++ b/server/src/auth/password.service.ts @@ -0,0 +1,64 @@ +import { Injectable } from "@nestjs/common"; +import { hash, compare } from "bcrypt"; +import { ConfigService } from "@nestjs/config"; + +/** Salt or number of rounds to generate a salt */ +export type Salt = string | number; + +const BCRYPT_SALT_VAR = "BCRYPT_SALT"; +const UNDEFINED_SALT_OR_ROUNDS_ERROR = `${BCRYPT_SALT_VAR} is not defined`; +const SALT_OR_ROUNDS_TYPE_ERROR = `${BCRYPT_SALT_VAR} must be a positive integer or text`; + +@Injectable() +export class PasswordService { + /** + * the salt to be used to hash the password. if specified as a number then a + * salt will be generated with the specified number of rounds and used + */ + salt: Salt; + + constructor(private configService: ConfigService) { + const saltOrRounds = this.configService.get(BCRYPT_SALT_VAR); + this.salt = parseSalt(saltOrRounds); + } + + /** + * + * @param password the password to be encrypted. + * @param encrypted the encrypted password to be compared against. + * @returns whether the password match the encrypted password + */ + compare(password: string, encrypted: string): Promise<boolean> { + return compare(password, encrypted); + } + + /** + * @param password the password to be encrypted + * @return encrypted password + */ + hash(password: string): Promise<string> { + return hash(password, this.salt); + } +} + +/** + * Parses a salt environment variable value. + * If a number string value is given tries to parse it as a number of rounds to generate a salt + * @param value salt environment variable value + * @returns salt or number of rounds to generate a salt + */ +export function parseSalt(value: string | undefined): Salt { + if (value === undefined) { + throw new Error(UNDEFINED_SALT_OR_ROUNDS_ERROR); + } + + const rounds = Number(value); + + if (Number.isNaN(rounds)) { + return value; + } + if (!Number.isInteger(rounds) || rounds < 0) { + throw new Error(SALT_OR_ROUNDS_TYPE_ERROR); + } + return rounds; +} diff --git a/server/src/auth/token.service.ts b/server/src/auth/token.service.ts new file mode 100644 index 0000000..b102b72 --- /dev/null +++ b/server/src/auth/token.service.ts @@ -0,0 +1,7 @@ +//@ts-ignore +import { ITokenService } from "./ITokenService"; +// eslint-disable-next-line import/no-unresolved +//@ts-ignore +import { TokenServiceBase } from "./base/token.service.base"; + +export class TokenService extends TokenServiceBase implements ITokenService {} diff --git a/server/src/auth/userData.decorator.ts b/server/src/auth/userData.decorator.ts new file mode 100644 index 0000000..6a40ad1 --- /dev/null +++ b/server/src/auth/userData.decorator.ts @@ -0,0 +1,30 @@ +import { createParamDecorator, ExecutionContext } from "@nestjs/common"; +import { GqlContextType, GqlExecutionContext } from "@nestjs/graphql"; +import { User } from "@prisma/client"; + +/** + * Access the user data from the request object i.e `req.user`. + */ +function userFactory(ctx: ExecutionContext): User { + const contextType = ctx.getType(); + if (contextType === "http") { + // do something that is only important in the context of regular HTTP requests (REST) + const { user } = ctx.switchToHttp().getRequest(); + return user; + } else if (contextType === "rpc") { + // do something that is only important in the context of Microservice requests + throw new Error("Rpc context is not implemented yet"); + } else if (contextType === "ws") { + // do something that is only important in the context of Websockets requests + throw new Error("Websockets context is not implemented yet"); + } else if (ctx.getType<GqlContextType>() === "graphql") { + // do something that is only important in the context of GraphQL requests + const gqlExecutionContext = GqlExecutionContext.create(ctx); + return gqlExecutionContext.getContext().req.user; + } + throw new Error("Invalid context"); +} + +export const UserData = createParamDecorator<undefined, ExecutionContext, User>( + (data, ctx: ExecutionContext) => userFactory(ctx) +); diff --git a/server/src/connectMicroservices.ts b/server/src/connectMicroservices.ts new file mode 100644 index 0000000..068fa5f --- /dev/null +++ b/server/src/connectMicroservices.ts @@ -0,0 +1,6 @@ +import { INestApplication } from "@nestjs/common"; +import { ConfigService } from "@nestjs/config"; + +export async function connectMicroservices(app: INestApplication) { + const configService = app.get(ConfigService); +} diff --git a/server/src/constants.ts b/server/src/constants.ts new file mode 100644 index 0000000..08f98bf --- /dev/null +++ b/server/src/constants.ts @@ -0,0 +1,2 @@ +export const JWT_SECRET_KEY = "JWT_SECRET_KEY"; +export const JWT_EXPIRATION = "JWT_EXPIRATION"; diff --git a/server/src/decorators/api-nested-query.decorator.ts b/server/src/decorators/api-nested-query.decorator.ts new file mode 100644 index 0000000..9fd5ba3 --- /dev/null +++ b/server/src/decorators/api-nested-query.decorator.ts @@ -0,0 +1,80 @@ +import { applyDecorators } from "@nestjs/common"; +import { + ApiExtraModels, + ApiQuery, + ApiQueryOptions, + getSchemaPath, +} from "@nestjs/swagger"; +import "reflect-metadata"; + +const generateApiQueryObject = ( + prop: any, + propType: any, + required: boolean, + isArray: boolean +): ApiQueryOptions => { + if (propType === Number) { + return { + required, + name: prop, + style: "deepObject", + explode: true, + type: "number", + isArray, + }; + } else if (propType === String) { + return { + required, + name: prop, + style: "deepObject", + explode: true, + type: "string", + isArray, + }; + } else { + return { + required, + name: prop, + style: "deepObject", + explode: true, + type: "object", + isArray, + schema: { + $ref: getSchemaPath(propType), + }, + }; + } +}; + +// eslint-disable-next-line @typescript-eslint/ban-types,@typescript-eslint/explicit-module-boundary-types,@typescript-eslint/naming-convention +export function ApiNestedQuery(query: Function) { + const constructor = query.prototype; + const properties = Reflect.getMetadata( + "swagger/apiModelPropertiesArray", + constructor + ).map((prop: any) => prop.slice(1)); + + const decorators = properties + .map((property: any) => { + const { required, isArray } = Reflect.getMetadata( + "swagger/apiModelProperties", + constructor, + property + ); + const propertyType = Reflect.getMetadata( + "design:type", + constructor, + property + ); + const typedQuery = generateApiQueryObject( + property, + propertyType, + required, + isArray + ); + return [ApiExtraModels(propertyType), ApiQuery(typedQuery)]; + }) + .flat(); + + return applyDecorators(...decorators); +} diff --git a/server/src/decorators/public.decorator.ts b/server/src/decorators/public.decorator.ts new file mode 100644 index 0000000..9eab4e0 --- /dev/null +++ b/server/src/decorators/public.decorator.ts @@ -0,0 +1,10 @@ +import { applyDecorators, SetMetadata } from "@nestjs/common"; + +export const IS_PUBLIC_KEY = "isPublic"; + +const PublicAuthMiddleware = SetMetadata(IS_PUBLIC_KEY, true); +const PublicAuthSwagger = SetMetadata("swagger/apiSecurity", ["isPublic"]); + +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export const Public = () => + applyDecorators(PublicAuthMiddleware, PublicAuthSwagger); diff --git a/server/src/errors.ts b/server/src/errors.ts new file mode 100644 index 0000000..bd1aa6d --- /dev/null +++ b/server/src/errors.ts @@ -0,0 +1,16 @@ +import * as common from "@nestjs/common"; +import { ApiProperty } from "@nestjs/swagger"; + +export class ForbiddenException extends common.ForbiddenException { + @ApiProperty() + statusCode!: number; + @ApiProperty() + message!: string; +} + +export class NotFoundException extends common.NotFoundException { + @ApiProperty() + statusCode!: number; + @ApiProperty() + message!: string; +} diff --git a/server/src/filters/HttpExceptions.filter.ts b/server/src/filters/HttpExceptions.filter.ts new file mode 100644 index 0000000..f5eda8e --- /dev/null +++ b/server/src/filters/HttpExceptions.filter.ts @@ -0,0 +1,89 @@ +import { + ArgumentsHost, + Catch, + HttpException, + HttpServer, + HttpStatus, +} from "@nestjs/common"; +import { BaseExceptionFilter } from "@nestjs/core"; +import { Prisma } from "@prisma/client"; +import { Response } from "express"; + +export type ErrorCodesStatusMapping = { + [key: string]: number; +}; + +/** + * {@link PrismaClientExceptionFilter} handling {@link Prisma.PrismaClientKnownRequestError} exceptions. + */ +@Catch(Prisma?.PrismaClientKnownRequestError) +export class HttpExceptionFilter extends BaseExceptionFilter { + /** + * default error codes mapping + * + * Error codes definition for Prisma Client (Query Engine) + * @see https://www.prisma.io/docs/reference/api-reference/error-reference#prisma-client-query-engine + */ + private errorCodesStatusMapping: ErrorCodesStatusMapping = { + P2000: HttpStatus.BAD_REQUEST, + P2002: HttpStatus.CONFLICT, + P2025: HttpStatus.NOT_FOUND, + }; + + /** + * @param applicationRef + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(applicationRef?: HttpServer) { + super(applicationRef); + } + + /** + * @param exception + * @param host + * @returns + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + catch(exception: Prisma.PrismaClientKnownRequestError, host: ArgumentsHost) { + const statusCode = this.errorCodesStatusMapping[exception.code]; + let message; + if (host.getType() === "http") { + // for http requests (REST) + // Todo : Add all other exception types and also add mapping + const ctx = host.switchToHttp(); + const response = ctx.getResponse<Response>(); + if (exception.code === "P2002") { + // Handling Unique Key Constraint Violation Error + const fields = (exception.meta as { target: string[] }).target; + message = `Another record with the requested (${fields.join( + ", " + )}) already exists`; + } else { + message = + `[${exception.code}]: ` + + this.exceptionShortMessage(exception.message); + } + if (!Object.keys(this.errorCodesStatusMapping).includes(exception.code)) { + return super.catch(exception, host); + } + const errorResponse = { + message: message, + statusCode: statusCode, + }; + response.status(statusCode).send(errorResponse); + } + return new HttpException({ statusCode, message }, statusCode); + } + + /** + * @param exception + * @returns short message for the exception + */ + exceptionShortMessage(message: string): string { + const shortMessage = message.substring(message.indexOf("→")); + return shortMessage + .substring(shortMessage.indexOf("\n")) + .replace(/\n/g, "") + .trim(); + } +} diff --git a/server/src/grants.json b/server/src/grants.json new file mode 100644 index 0000000..51ae229 --- /dev/null +++ b/server/src/grants.json @@ -0,0 +1,32 @@ +[ + { + "role": "user", + "resource": "User", + "action": "read:own", + "attributes": "*" + }, + { + "role": "user", + "resource": "User", + "action": "create:any", + "attributes": "*" + }, + { + "role": "user", + "resource": "User", + "action": "update:any", + "attributes": "*" + }, + { + "role": "user", + "resource": "User", + "action": "delete:any", + "attributes": "*" + }, + { + "role": "user", + "resource": "User", + "action": "read:any", + "attributes": "*" + } +] diff --git a/server/src/health/base/health.controller.base.ts b/server/src/health/base/health.controller.base.ts new file mode 100644 index 0000000..afd9e0d --- /dev/null +++ b/server/src/health/base/health.controller.base.ts @@ -0,0 +1,19 @@ +import { Get, HttpStatus, Res } from "@nestjs/common"; +import { Response } from "express"; +import { HealthService } from "../health.service"; + +export class HealthControllerBase { + constructor(protected readonly healthService: HealthService) {} + @Get("live") + healthLive(@Res() response: Response): Response<void> { + return response.status(HttpStatus.NO_CONTENT).send(); + } + @Get("ready") + async healthReady(@Res() response: Response): Promise<Response<void>> { + const dbConnection = await this.healthService.isDbReady(); + if (!dbConnection) { + return response.status(HttpStatus.NOT_FOUND).send(); + } + return response.status(HttpStatus.NO_CONTENT).send(); + } +} diff --git a/server/src/health/base/health.service.base.ts b/server/src/health/base/health.service.base.ts new file mode 100644 index 0000000..49a93a5 --- /dev/null +++ b/server/src/health/base/health.service.base.ts @@ -0,0 +1,15 @@ +import { Injectable } from "@nestjs/common"; +import { PrismaService } from "../../prisma/prisma.service"; + +@Injectable() +export class HealthServiceBase { + constructor(protected readonly prisma: PrismaService) {} + async isDbReady(): Promise<boolean> { + try { + await this.prisma.$queryRaw`SELECT 1`; + return true; + } catch (error) { + return false; + } + } +} diff --git a/server/src/health/health.controller.ts b/server/src/health/health.controller.ts new file mode 100644 index 0000000..ff484e7 --- /dev/null +++ b/server/src/health/health.controller.ts @@ -0,0 +1,10 @@ +import { Controller } from "@nestjs/common"; +import { HealthControllerBase } from "./base/health.controller.base"; +import { HealthService } from "./health.service"; + +@Controller("_health") +export class HealthController extends HealthControllerBase { + constructor(protected readonly healthService: HealthService) { + super(healthService); + } +} diff --git a/server/src/health/health.module.ts b/server/src/health/health.module.ts new file mode 100644 index 0000000..39eff7f --- /dev/null +++ b/server/src/health/health.module.ts @@ -0,0 +1,10 @@ +import { Module } from "@nestjs/common"; +import { HealthController } from "./health.controller"; +import { HealthService } from "./health.service"; + +@Module({ + controllers: [HealthController], + providers: [HealthService], + exports: [HealthService], +}) +export class HealthModule {} diff --git a/server/src/health/health.service.ts b/server/src/health/health.service.ts new file mode 100644 index 0000000..44d9343 --- /dev/null +++ b/server/src/health/health.service.ts @@ -0,0 +1,10 @@ +import { Injectable } from "@nestjs/common"; +import { PrismaService } from "../prisma/prisma.service"; +import { HealthServiceBase } from "./base/health.service.base"; + +@Injectable() +export class HealthService extends HealthServiceBase { + constructor(protected readonly prisma: PrismaService) { + super(prisma); + } +} diff --git a/server/src/interceptors/aclFilterResponse.interceptor.ts b/server/src/interceptors/aclFilterResponse.interceptor.ts new file mode 100644 index 0000000..5eeba18 --- /dev/null +++ b/server/src/interceptors/aclFilterResponse.interceptor.ts @@ -0,0 +1,42 @@ +import { + CallHandler, + ExecutionContext, + Injectable, + NestInterceptor, +} from "@nestjs/common"; +import { Observable } from "rxjs"; +import { map } from "rxjs/operators"; +import { InjectRolesBuilder, RolesBuilder } from "nest-access-control"; +import { Reflector } from "@nestjs/core"; + +@Injectable() +export class AclFilterResponseInterceptor implements NestInterceptor { + constructor( + @InjectRolesBuilder() private readonly rolesBuilder: RolesBuilder, + private readonly reflector: Reflector + ) {} + + intercept(context: ExecutionContext, next: CallHandler): Observable<any> { + const [permissionsRoles]: any = this.reflector.getAllAndMerge<string[]>( + "roles", + [context.getHandler(), context.getClass()] + ); + + const permission = this.rolesBuilder.permission({ + role: permissionsRoles.role, + action: permissionsRoles.action, + possession: permissionsRoles.possession, + resource: permissionsRoles.resource, + }); + + return next.handle().pipe( + map((data) => { + if (Array.isArray(data)) { + return data.map((results: any) => permission.filter(results)); + } else { + return permission.filter(data); + } + }) + ); + } +} diff --git a/server/src/interceptors/aclValidateRequest.interceptor.ts b/server/src/interceptors/aclValidateRequest.interceptor.ts new file mode 100644 index 0000000..6d30246 --- /dev/null +++ b/server/src/interceptors/aclValidateRequest.interceptor.ts @@ -0,0 +1,53 @@ +import { + CallHandler, + ExecutionContext, + Injectable, + NestInterceptor, +} from "@nestjs/common"; +import { Observable } from "rxjs"; +import { InjectRolesBuilder, RolesBuilder } from "nest-access-control"; +import { Reflector } from "@nestjs/core"; +import * as abacUtil from "../auth/abac.util"; +import { ForbiddenException } from "../errors"; + +@Injectable() +export class AclValidateRequestInterceptor implements NestInterceptor { + constructor( + @InjectRolesBuilder() private readonly rolesBuilder: RolesBuilder, + private readonly reflector: Reflector + ) {} + + intercept(context: ExecutionContext, next: CallHandler): Observable<any> { + const [permissionsRoles]: any = this.reflector.getAllAndMerge<string[]>( + "roles", + [context.getHandler(), context.getClass()] + ); + + const type = context.getType(); + + const inputDataToValidate = + type === "http" + ? context.switchToHttp().getRequest().body + : context.getArgByIndex(1).data; + + const permission = this.rolesBuilder.permission({ + role: permissionsRoles.role, + action: permissionsRoles.action, + possession: permissionsRoles.possession, + resource: permissionsRoles.resource, + }); + + const invalidAttributes = abacUtil.getInvalidAttributes( + permission, + inputDataToValidate + ); + + if (invalidAttributes.length) { + throw new ForbiddenException( + "Insufficient privileges to complete the operation" + ); + } + + return next.handle(); + } +} diff --git a/server/src/main.ts b/server/src/main.ts new file mode 100644 index 0000000..474eead --- /dev/null +++ b/server/src/main.ts @@ -0,0 +1,53 @@ +import { ValidationPipe } from "@nestjs/common"; +import { HttpAdapterHost, NestFactory } from "@nestjs/core"; +import { OpenAPIObject, SwaggerModule } from "@nestjs/swagger"; +import { HttpExceptionFilter } from "./filters/HttpExceptions.filter"; +import { AppModule } from "./app.module"; +import { connectMicroservices } from "./connectMicroservices"; +import { + swaggerPath, + swaggerDocumentOptions, + swaggerSetupOptions, +} from "./swagger"; + +const { PORT = 3000 } = process.env; + +async function main() { + const app = await NestFactory.create(AppModule, { cors: true }); + + app.setGlobalPrefix("api"); + app.useGlobalPipes( + new ValidationPipe({ + transform: true, + forbidUnknownValues: false, + }) + ); + + const document = SwaggerModule.createDocument(app, swaggerDocumentOptions); + + /** check if there is Public decorator for each path (action) and its method (findMany / findOne) on each controller */ + Object.values((document as OpenAPIObject).paths).forEach((path: any) => { + Object.values(path).forEach((method: any) => { + if ( + Array.isArray(method.security) && + method.security.includes("isPublic") + ) { + method.security = []; + } + }); + }); + + await connectMicroservices(app); + await app.startAllMicroservices(); + + SwaggerModule.setup(swaggerPath, app, document, swaggerSetupOptions); + + const { httpAdapter } = app.get(HttpAdapterHost); + app.useGlobalFilters(new HttpExceptionFilter(httpAdapter)); + + void app.listen(PORT); + + return app; +} + +module.exports = main(); diff --git a/server/src/prisma.util.spec.ts b/server/src/prisma.util.spec.ts new file mode 100644 index 0000000..0aa308e --- /dev/null +++ b/server/src/prisma.util.spec.ts @@ -0,0 +1,23 @@ +import { + isRecordNotFoundError, + PRISMA_QUERY_INTERPRETATION_ERROR, +} from "./prisma.util"; + +describe("isRecordNotFoundError", () => { + test("returns true for record not found error", () => { + expect( + isRecordNotFoundError( + Object.assign( + new Error(`Error occurred during query execution: + InterpretationError("Error for binding '0': RecordNotFound("Record to update not found.")")`), + { + code: PRISMA_QUERY_INTERPRETATION_ERROR, + } + ) + ) + ).toBe(true); + }); + test("returns false for any other error", () => { + expect(isRecordNotFoundError(new Error())).toBe(false); + }); +}); diff --git a/server/src/prisma.util.ts b/server/src/prisma.util.ts new file mode 100644 index 0000000..029b98a --- /dev/null +++ b/server/src/prisma.util.ts @@ -0,0 +1,29 @@ +export const PRISMA_QUERY_INTERPRETATION_ERROR = "P2016"; +export const PRISMA_RECORD_NOT_FOUND = "RecordNotFound"; + +export function isRecordNotFoundError(error: any): boolean { + return ( + error instanceof Error && + "code" in error && + error.code === PRISMA_QUERY_INTERPRETATION_ERROR && + error.message.includes(PRISMA_RECORD_NOT_FOUND) + ); +} + +export async function transformStringFieldUpdateInput< + T extends undefined | string | { set?: string } +>(input: T, transform: (input: string) => Promise<string>): Promise<T> { + if (typeof input === "object" && typeof input?.set === "string") { + return { set: await transform(input.set) } as T; + } + if (typeof input === "object") { + if (typeof input.set === "string") { + return { set: await transform(input.set) } as T; + } + return input; + } + if (typeof input === "string") { + return (await transform(input)) as T; + } + return input; +} diff --git a/server/src/prisma/prisma.module.ts b/server/src/prisma/prisma.module.ts new file mode 100644 index 0000000..1edbf95 --- /dev/null +++ b/server/src/prisma/prisma.module.ts @@ -0,0 +1,9 @@ +import { Global, Module } from "@nestjs/common"; +import { PrismaService } from "./prisma.service"; + +@Global() +@Module({ + providers: [PrismaService], + exports: [PrismaService], +}) +export class PrismaModule {} diff --git a/server/src/prisma/prisma.service.ts b/server/src/prisma/prisma.service.ts new file mode 100644 index 0000000..79ea4fa --- /dev/null +++ b/server/src/prisma/prisma.service.ts @@ -0,0 +1,9 @@ +import { Injectable, OnModuleInit, INestApplication } from "@nestjs/common"; +import { PrismaClient } from "@prisma/client"; + +@Injectable() +export class PrismaService extends PrismaClient implements OnModuleInit { + async onModuleInit() { + await this.$connect(); + } +} diff --git a/server/src/providers/secrets/base/secretsManager.service.base.spec.ts b/server/src/providers/secrets/base/secretsManager.service.base.spec.ts new file mode 100644 index 0000000..beb2607 --- /dev/null +++ b/server/src/providers/secrets/base/secretsManager.service.base.spec.ts @@ -0,0 +1,39 @@ +import { ConfigService } from "@nestjs/config"; +import { mock } from "jest-mock-extended"; +import { SecretsManagerServiceBase } from "./secretsManager.service.base"; + +describe("Testing the secrets manager base class", () => { + const SECRET_KEY = "SECRET_KEY"; + const SECRET_VALUE = "SECRET_VALUE"; + const configService = mock<ConfigService>(); + const secretsManagerServiceBase = new SecretsManagerServiceBase( + configService + ); + beforeEach(() => { + configService.get.mockClear(); + }); + it("should return value from env", async () => { + //ARRANGE + configService.get.mockReturnValue(SECRET_VALUE); + //ACT + const result = await secretsManagerServiceBase.getSecret(SECRET_KEY); + //ASSERT + expect(result).toBe(SECRET_VALUE); + }); + it("should return null for unknown keys", async () => { + //ARRANGE + configService.get.mockReturnValue(undefined); + //ACT + const result = await secretsManagerServiceBase.getSecret(SECRET_KEY); + //ASSERT + expect(result).toBeNull(); + }); + it("should throw error if dont get key", () => { + return expect(secretsManagerServiceBase.getSecret("")).rejects.toThrow(); + }); + it("should throw an exception if getting null key", () => { + return expect( + secretsManagerServiceBase.getSecret(null as unknown as string) + ).rejects.toThrow(); + }); +}); diff --git a/server/src/providers/secrets/base/secretsManager.service.base.ts b/server/src/providers/secrets/base/secretsManager.service.base.ts new file mode 100644 index 0000000..18a340b --- /dev/null +++ b/server/src/providers/secrets/base/secretsManager.service.base.ts @@ -0,0 +1,19 @@ +import { ConfigService } from "@nestjs/config"; + +export interface ISecretsManager { + getSecret: (key: string) => Promise<any | null>; +} + +export class SecretsManagerServiceBase implements ISecretsManager { + constructor(protected readonly configService: ConfigService) {} + async getSecret<T>(key: string): Promise<T | null> { + if (!key) { + throw new Error("Didn't got the key"); + } + const value = this.configService.get(key); + if (value) { + return value; + } + return null; + } +} diff --git a/server/src/providers/secrets/secretsManager.module.ts b/server/src/providers/secrets/secretsManager.module.ts new file mode 100644 index 0000000..3a621e4 --- /dev/null +++ b/server/src/providers/secrets/secretsManager.module.ts @@ -0,0 +1,8 @@ +import { Module } from "@nestjs/common"; +import { SecretsManagerService } from "./secretsManager.service"; + +@Module({ + providers: [SecretsManagerService], + exports: [SecretsManagerService], +}) +export class SecretsManagerModule {} diff --git a/server/src/providers/secrets/secretsManager.service.ts b/server/src/providers/secrets/secretsManager.service.ts new file mode 100644 index 0000000..89907c3 --- /dev/null +++ b/server/src/providers/secrets/secretsManager.service.ts @@ -0,0 +1,10 @@ +import { Injectable } from "@nestjs/common"; +import { ConfigService } from "@nestjs/config"; +import { SecretsManagerServiceBase } from "./base/secretsManager.service.base"; + +@Injectable() +export class SecretsManagerService extends SecretsManagerServiceBase { + constructor(protected readonly configService: ConfigService) { + super(configService); + } +} diff --git a/server/src/serveStaticOptions.service.ts b/server/src/serveStaticOptions.service.ts new file mode 100644 index 0000000..390248b --- /dev/null +++ b/server/src/serveStaticOptions.service.ts @@ -0,0 +1,39 @@ +import * as path from "path"; +import { Injectable, Logger } from "@nestjs/common"; +import { ConfigService } from "@nestjs/config"; +import { + ServeStaticModuleOptions, + ServeStaticModuleOptionsFactory, +} from "@nestjs/serve-static"; + +const SERVE_STATIC_ROOT_PATH_VAR = "SERVE_STATIC_ROOT_PATH"; +const DEFAULT_STATIC_MODULE_OPTIONS_LIST: ServeStaticModuleOptions[] = [ + { + serveRoot: "/swagger", + rootPath: path.join(__dirname, "swagger"), + }, +]; + +@Injectable() +export class ServeStaticOptionsService + implements ServeStaticModuleOptionsFactory +{ + private readonly logger = new Logger(ServeStaticOptionsService.name); + + constructor(private readonly configService: ConfigService) {} + + createLoggerOptions(): ServeStaticModuleOptions[] { + const serveStaticRootPath = this.configService.get( + SERVE_STATIC_ROOT_PATH_VAR + ); + if (serveStaticRootPath) { + const resolvedPath = path.resolve(serveStaticRootPath); + this.logger.log(`Serving static files from ${resolvedPath}`); + return [ + ...DEFAULT_STATIC_MODULE_OPTIONS_LIST, + { rootPath: resolvedPath, exclude: ["/api*", "/graphql"] }, + ]; + } + return DEFAULT_STATIC_MODULE_OPTIONS_LIST; + } +} diff --git a/server/src/swagger.ts b/server/src/swagger.ts new file mode 100644 index 0000000..cadb474 --- /dev/null +++ b/server/src/swagger.ts @@ -0,0 +1,20 @@ +import { DocumentBuilder, SwaggerCustomOptions } from "@nestjs/swagger"; + +export const swaggerPath = "api"; + +export const swaggerDocumentOptions = new DocumentBuilder() + .setTitle("Record") + .setDescription( + '\n\n## Congratulations! Your service resource is ready.\n \nPlease note that all endpoints are secured with JWT Bearer authentication.\nBy default, your service resource comes with one user with the username "admin" and password "admin".\nLearn more in [our docs](https://docs.amplication.com)' + ) + .addBearerAuth() + .build(); + +export const swaggerSetupOptions: SwaggerCustomOptions = { + swaggerOptions: { + persistAuthorization: true, + }, + customCssUrl: "../swagger/swagger.css", + customfavIcon: "../swagger/favicon.png", + customSiteTitle: "Record", +}; diff --git a/server/src/swagger/favicon.png b/server/src/swagger/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..a79882d55bdcd1d04939ed7a42257c20ac32f17c GIT binary patch literal 2498 zcmZ`*>rdNd6#kVvl#bgdw{@jJ2c2M{$hfWC29(Qyav88OF5?my1-7meXrU!j6F<&G z-ABd5FD8azVwPxROPCY=pqU9IVsw7-<C6UgK9A>3sY^_r^PK0L_t)QhIp_Dnt0#Nz zUY8*$H%ZepLuW_p0DL|zAr9;d1YSMa)3n&PI$N8EMqLPi?xpdO9FbuTLR}6=B34ZB zy#t_5cb?U4GfMi3xYNne*$y3abW!UWxa^9V{q33d1Q|_*bMr~9z|sXrD};qn7-fYX zJ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4naq&s{_)J!rSoX@%Hz7{Sa{#phy%P z-DCaL4}wi=2u5KAjxO$6bvYEEU%8~ScX`xo4Si1Jh6hi+S)M(>>kx1SKnXpd5bWTC z`X(#<zgIdxVnLw}-UvJT_IOu)Vu&g$If(%VT;<L)+-aHW@<8<LJrKLw1QT#pF5Fw& zcl24zBvchE#ZpwmM%Ai9>^Yv^;X_dI6bMM&fAqrxc-3ApTslzP0rD-r_&kecO5$Gw z)fhF90)A5MFm65xcD&1q@Gry-n6-b6S5E#+4flMxno9we)N5k?ddS}oaJLCE1m<PM t<*K%ZYUNV^ClYWAo*T1?*DFfZWvA{M8D=Njui(Ejt+TDS6+sJk`VZG>JHG$` literal 0 HcmV?d00001 diff --git a/server/src/swagger/logo-amplication-white.svg b/server/src/swagger/logo-amplication-white.svg new file mode 100644 index 0000000..0054cd4 --- /dev/null +++ b/server/src/swagger/logo-amplication-white.svg @@ -0,0 +1,15 @@ +<svg width="206" height="45" viewBox="0 0 206 45" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path d="M0 22.472C0 34.0994 8.90877 43.6025 20.3874 44.9441V0C8.90877 1.34161 0 10.9006 0 22.472Z" fill="white"/> +<path d="M46.2574 22.472C46.2574 10.8447 37.2344 1.22981 25.6987 0V45H46.2574V23.1429C46.2574 22.9193 46.2574 22.6957 46.2574 22.472Z" fill="white"/> +<path d="M70.8698 26.2732V38.8508H67.6718V37.1738C66.8152 38.5154 64.9877 39.1303 63.3887 39.1303C60.0194 39.1303 57.0498 36.5589 57.0498 32.534C57.0498 28.5092 59.9623 25.9937 63.3887 25.9937C64.9877 25.9937 66.8152 26.6086 67.6718 27.9502V26.2732H70.8698ZM67.6147 32.534C67.6147 30.298 65.7301 28.9005 63.9027 28.9005C61.9039 28.9005 60.3049 30.4098 60.3049 32.534C60.3049 34.6583 61.9039 36.2235 63.9027 36.2235C65.8444 36.2235 67.6147 34.7701 67.6147 32.534Z" fill="white"/> +<path d="M95.14 31.8074V38.8509H91.942V32.031C91.942 30.0186 90.857 29.0124 89.3722 29.0124C87.5447 29.0124 86.3455 30.354 86.5168 32.6459V32.5341V38.8509H83.3188V32.031C83.3188 30.0186 82.2337 29.0124 80.8632 29.0124C79.3784 29.0124 77.8936 29.795 77.8936 32.1987V38.8509H74.6956V26.2733H77.8936V28.4534C78.3504 26.8882 80.1208 26.0497 81.7198 26.0497C83.6043 26.0497 85.1462 26.8882 85.8886 28.5093C86.9166 26.4969 88.9153 26.0497 90.2288 26.0497C93.4268 25.9938 95.14 28.118 95.14 31.8074Z" fill="white"/> +<path d="M112.614 32.534C112.614 36.5589 109.702 39.0744 106.276 39.0744C104.677 39.0744 102.849 38.4595 101.992 37.1179V44.944H98.7944V26.2732H101.992V27.9502C102.849 26.6086 104.734 25.9937 106.276 25.9937C109.645 25.9937 112.614 28.5651 112.614 32.534ZM109.416 32.5899C109.416 30.4657 107.76 28.9005 105.762 28.9005C103.82 28.9005 102.05 30.3539 102.05 32.5899C102.05 34.8259 103.934 36.2235 105.762 36.2235C107.76 36.2235 109.416 34.7141 109.416 32.5899Z" fill="white"/> +<path d="M115.642 19.5092H118.84V38.8508H115.642V19.5092Z" fill="white"/> +<path d="M122.152 21.8006C122.152 20.6826 123.123 19.9 124.265 19.9C125.407 19.9 126.321 20.6826 126.321 21.8006C126.321 22.8628 125.407 23.7013 124.265 23.7013C123.123 23.7572 122.152 22.9187 122.152 21.8006ZM122.609 26.2727H125.807V38.8503H122.609V26.2727Z" fill="white"/> +<path d="M128.834 32.534C128.834 28.5651 132.09 25.9937 135.859 25.9937C138.086 25.9937 139.913 26.944 141.113 28.3974L138.828 30.1303C138.143 29.3477 137.058 28.8446 135.916 28.8446C133.689 28.8446 132.09 30.3539 132.09 32.4781C132.09 34.6024 133.689 36.1117 135.916 36.1117C137.058 36.1117 138.143 35.6086 138.828 34.826L141.113 36.5589C139.913 38.0123 138.086 38.9626 135.859 38.9626C132.09 39.1303 128.834 36.5589 128.834 32.534Z" fill="white"/> +<path d="M156.589 26.2732V38.8508H153.391V37.1738C152.534 38.5154 150.707 39.1303 149.107 39.1303C145.738 39.1303 142.769 36.5589 142.769 32.534C142.769 28.5092 145.681 25.9937 149.107 25.9937C150.707 25.9937 152.534 26.6086 153.391 27.9502V26.2732H156.589ZM153.333 32.534C153.333 30.298 151.449 28.9005 149.621 28.9005C147.623 28.9005 146.024 30.4098 146.024 32.534C146.024 34.6583 147.623 36.2235 149.621 36.2235C151.563 36.2235 153.333 34.7701 153.333 32.534Z" fill="white"/> +<path d="M167.496 28.7891H164.755V38.9071H161.556V28.7891H159.215V26.2735H161.556V21.6338H164.755V26.2735H167.496V28.7891Z" fill="white"/> +<path d="M169.438 21.8006C169.438 20.6826 170.409 19.9 171.551 19.9C172.693 19.9 173.607 20.6826 173.607 21.8006C173.607 22.8628 172.693 23.7013 171.551 23.7013C170.409 23.7572 169.438 22.9187 169.438 21.8006ZM169.952 26.2727H173.15V38.8503H169.952V26.2727Z" fill="white"/> +<path d="M176.12 32.534C176.12 28.5651 179.318 25.9937 182.973 25.9937C186.627 25.9937 189.825 28.5092 189.825 32.534C189.825 36.503 186.627 39.1303 182.973 39.1303C179.318 39.1303 176.12 36.503 176.12 32.534ZM186.627 32.534C186.627 30.3539 184.971 28.9005 182.973 28.9005C180.974 28.9005 179.375 30.3539 179.375 32.534C179.375 34.7701 180.974 36.2235 182.973 36.2235C184.971 36.2235 186.627 34.7701 186.627 32.534Z" fill="white"/> +<path d="M205.187 31.8073V38.8508H201.989V32.0868C201.989 30.0744 200.733 29.0682 199.305 29.0682C197.82 29.0682 196.05 29.8508 196.05 32.2545V38.8508H192.852V26.2732H196.05V28.2856C196.735 26.7204 198.734 25.9937 200.047 25.9937C203.36 25.9937 205.187 28.1179 205.187 31.8073Z" fill="white"/> +</svg> diff --git a/server/src/swagger/swagger.css b/server/src/swagger/swagger.css new file mode 100644 index 0000000..b7c4037 --- /dev/null +++ b/server/src/swagger/swagger.css @@ -0,0 +1,321 @@ +html, +body { + background-color: #f4f4f7; +} + +body { + margin: auto; + line-height: 1.6; + font-family: "Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", + "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", + "Helvetica Neue", sans-serif; + color: #121242; +} + +.swagger-ui { + font-family: "Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", + "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", + "Helvetica Neue", sans-serif; +} + +.swagger-ui button, +.swagger-ui input, +.swagger-ui optgroup, +.swagger-ui select, +.swagger-ui textarea, +.swagger-ui .parameter__name, +.swagger-ui .parameters-col_name > *, +.swagger-ui label { + font-family: "Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", + "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", + "Helvetica Neue", sans-serif; + font-weight: normal; + font-size: 12px; + outline: none; +} + +.swagger-ui textarea { + border: 1px solid #d0d0d9; + min-height: 100px; +} + +.swagger-ui input[type="email"], +.swagger-ui input[type="file"], +.swagger-ui input[type="password"], +.swagger-ui input[type="search"], +.swagger-ui input[type="text"], +.swagger-ui textarea { + border-radius: 3px; +} + +.swagger-ui input[disabled], +.swagger-ui select[disabled], +.swagger-ui textarea[disabled] { + background: #f4f4f7; + color: #b8b8c6; +} + +.swagger-ui .btn { + font-family: "Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", + "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", + "Helvetica Neue", sans-serif; + font-weight: 500; + box-shadow: none; + border: 1px solid #d0d0d9; + height: 28px; + border-radius: 14px; + background-color: #fff; + color: #7950ed; +} + +.swagger-ui .btn:hover { + box-shadow: none; +} + +/* topbar */ + +.swagger-ui .topbar { + background-color: #7950ed; + height: 80px; + padding: 0; + display: flex; + flex-direction: row; + align-items: center; + justify-content: flex-start; +} + +.swagger-ui .topbar-wrapper a { + display: block; + width: 206px; + height: 35px; + background-image: url("logo-amplication-white.svg"); + background-repeat: no-repeat; + background-size: contain; +} + +.swagger-ui .topbar-wrapper svg, +.swagger-ui .topbar-wrapper img { + display: none; +} + +/* title */ +.swagger-ui .info { + margin: 0; +} + +.swagger-ui .info .title { + font-family: "Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", + "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", + "Helvetica Neue", sans-serif; + font-size: 32px; + font-weight: 600; +} + +.swagger-ui .information-container { + padding-top: 50px; + padding-bottom: 20px; + position: relative; +} + +.swagger-ui .info .title small.version-stamp { + display: none; +} + +.swagger-ui .info .title small { + background-color: #a787ff; +} + +.swagger-ui .info .description p { + max-width: 1000px; + margin: 0; +} + +.swagger-ui .info .description p, +.swagger-ui .info .description a { + font-size: 1rem; +} + +.swagger-ui .information-container section { + position: relative; +} + +.swagger-ui .scheme-container { + box-shadow: none; + background-color: transparent; + position: relative; + margin: 0; + margin-top: 20px; + margin-bottom: 20px; + padding: 0; +} + +.swagger-ui .scheme-container .auth-wrapper { + justify-content: flex-start; +} + +.swagger-ui .btn.authorize { + box-shadow: none; + border: 1px solid #d0d0d9; + height: 40px; + border-radius: 20px; + background-color: #fff; + color: #7950ed; +} + +.swagger-ui .btn.authorize svg { + fill: #7950ed; +} + +/* content */ + +.swagger-ui .opblock-tag { + font-family: "Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", + "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", + "Helvetica Neue", sans-serif; + font-size: 28px; + font-weight: 600; +} + +.swagger-ui .opblock.is-open .opblock-summary { + border-color: #e7e7ec !important; + border-bottom: none; +} + +.swagger-ui .opblock .opblock-section-header { + background-color: #fff; + border: none; + border-top: 1px solid #e7e7ec; + border-bottom: 1px solid #e7e7ec; + box-shadow: none; +} + +.swagger-ui .opblock .tab-header .tab-item.active h4 span:after { + display: none; +} + +.swagger-ui .opblock.opblock-post { + border: 1px solid #e7e7ec; + background: #f9f9fa; + box-shadow: none; + color: #fff; +} + +.swagger-ui .opblock.opblock-post:hover, +.swagger-ui .opblock.opblock-post.is-open { + border-color: #31c587; +} + +.swagger-ui .opblock.opblock-post .opblock-summary-method { + background-color: #31c587; +} + +.swagger-ui .opblock.opblock-get { + border: 1px solid #e7e7ec; + background: #f9f9fa; + box-shadow: none; +} +.swagger-ui .opblock.opblock-get:hover, +.swagger-ui .opblock.opblock-get.is-open { + border-color: #20a4f3; +} +.swagger-ui .opblock.opblock-get .opblock-summary-method { + background-color: #20a4f3; +} + +.swagger-ui .opblock.opblock-delete { + border: 1px solid #e7e7ec; + background: #f9f9fa; + box-shadow: none; +} +.swagger-ui .opblock.opblock-delete:hover, +.swagger-ui .opblock.opblock-delete.is-open { + border-color: #e93c51; +} +.swagger-ui .opblock.opblock-delete .opblock-summary-method { + background-color: #e93c51; +} + +.swagger-ui .opblock.opblock-patch { + border: 1px solid #e7e7ec; + background: #f9f9fa; + box-shadow: none; +} +.swagger-ui .opblock.opblock-patch:hover, +.swagger-ui .opblock.opblock-patch.is-open { + border-color: #41cadd; +} +.swagger-ui .opblock.opblock-patch .opblock-summary-method { + background-color: #41cadd; +} + +.swagger-ui .opblock-body pre { + background-color: #121242 !important; +} + +.swagger-ui select, +.swagger-ui .response-control-media-type--accept-controller select { + border: 1px solid #d0d0d9; + box-shadow: none; + outline: none; +} + +/* models */ + +.swagger-ui section.models { + background-color: #fff; + border: 1px solid #e7e7ec; +} + +.swagger-ui section.models.is-open h4 { + border-bottom: 1px solid #e7e7ec; +} + +.swagger-ui section.models .model-container, +.swagger-ui section.models .model-container:hover { + background-color: #f4f4f7; + color: #121242; +} + +.swagger-ui .model-title { + font-family: "Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", + "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", + "Helvetica Neue", sans-serif; + font-weight: normal; + font-size: 15px; + color: #121242; +} + +/* modal */ + +.swagger-ui .dialog-ux .modal-ux-header h3, +.swagger-ui .dialog-ux .modal-ux-content h4, +.swagger-ui .dialog-ux .modal-ux-content h4 code { + font-family: "Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", + "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", + "Helvetica Neue", sans-serif; + font-weight: normal; + font-size: 15px; + color: #121242; +} + +.swagger-ui .dialog-ux .modal-ux-content .btn.authorize { + height: 28px; + border-radius: 14px; +} + +.swagger-ui .auth-btn-wrapper { + display: flex; + flex-direction: row-reverse; + align-items: center; + justify-content: flex-start; +} + +.swagger-ui .auth-btn-wrapper .btn-done { + border: none; + color: #121242; + margin-right: 0; +} + +.swagger-ui .authorization__btn { + fill: #414168; +} diff --git a/server/src/tests/auth/constants.ts b/server/src/tests/auth/constants.ts new file mode 100644 index 0000000..98e4887 --- /dev/null +++ b/server/src/tests/auth/constants.ts @@ -0,0 +1,19 @@ +import { Credentials } from "../../auth/Credentials"; +import { UserInfo } from "../../auth/UserInfo"; + +export const VALID_ID = "1"; + +export const TEST_USER: UserInfo = { + id: "cl7qmjh4h0000tothyjqapgj5", + roles: ["User"], + username: "ofek", +}; +export const SIGN_TOKEN = "SIGN_TOKEN"; +export const VALID_CREDENTIALS: Credentials = { + username: "Valid User", + password: "Valid User Password", +}; +export const INVALID_CREDENTIALS: Credentials = { + username: "Invalid User", + password: "Invalid User Password", +}; diff --git a/server/src/tests/auth/jwt/jwt.strategy.spec.ts b/server/src/tests/auth/jwt/jwt.strategy.spec.ts new file mode 100644 index 0000000..2463c9b --- /dev/null +++ b/server/src/tests/auth/jwt/jwt.strategy.spec.ts @@ -0,0 +1,26 @@ +import { UnauthorizedException } from "@nestjs/common"; +import { mock } from "jest-mock-extended"; +import { JwtStrategyBase } from "../../../auth/jwt/base/jwt.strategy.base"; +import { TEST_USER } from "../constants"; +import { UserService } from "../../../user/user.service"; +describe("Testing the jwtStrategyBase.validate()", () => { + const userService = mock<UserService>(); + const jwtStrategy = new JwtStrategyBase(userService, "Secrete"); + beforeEach(() => { + userService.findOne.mockClear(); + }); + it("should throw UnauthorizedException where there is no user", async () => { + //ARRANGE + userService.findOne + .calledWith({ where: { username: TEST_USER.username } }) + .mockReturnValue(Promise.resolve(null)); + //ACT + const result = jwtStrategy.validate({ + id: TEST_USER.id, + username: TEST_USER.username, + roles: TEST_USER.roles, + }); + //ASSERT + return expect(result).rejects.toThrowError(UnauthorizedException); + }); +}); diff --git a/server/src/tests/auth/token.service.spec.ts b/server/src/tests/auth/token.service.spec.ts new file mode 100644 index 0000000..83b5a51 --- /dev/null +++ b/server/src/tests/auth/token.service.spec.ts @@ -0,0 +1,47 @@ +import { JwtService } from "@nestjs/jwt"; +import { mock } from "jest-mock-extended"; +import { TokenServiceBase } from "../../auth/base/token.service.base"; +import { + INVALID_PASSWORD_ERROR, + INVALID_USERNAME_ERROR, +} from "../../auth/constants"; +import { SIGN_TOKEN, VALID_CREDENTIALS, VALID_ID } from "./constants"; + +describe("Testing the TokenServiceBase", () => { + let tokenServiceBase: TokenServiceBase; + const jwtService = mock<JwtService>(); + beforeEach(() => { + tokenServiceBase = new TokenServiceBase(jwtService); + jwtService.signAsync.mockClear(); + }); + describe("Testing the BasicTokenService.createToken()", () => { + it("should create valid token for valid username and password", async () => { + jwtService.signAsync.mockReturnValue(Promise.resolve(SIGN_TOKEN)); + expect( + await tokenServiceBase.createToken({ + id: VALID_ID, + username: VALID_CREDENTIALS.username, + password: VALID_CREDENTIALS.password, + }) + ).toBe(SIGN_TOKEN); + }); + it("should reject when username missing", () => { + const result = tokenServiceBase.createToken({ + id: VALID_ID, + //@ts-ignore + username: null, + password: VALID_CREDENTIALS.password, + }); + return expect(result).rejects.toBe(INVALID_USERNAME_ERROR); + }); + it("should reject when password missing", () => { + const result = tokenServiceBase.createToken({ + id: VALID_ID, + username: VALID_CREDENTIALS.username, + //@ts-ignore + password: null, + }); + return expect(result).rejects.toBe(INVALID_PASSWORD_ERROR); + }); + }); +}); diff --git a/server/src/tests/health/health.service.spec.ts b/server/src/tests/health/health.service.spec.ts new file mode 100644 index 0000000..4b191f1 --- /dev/null +++ b/server/src/tests/health/health.service.spec.ts @@ -0,0 +1,36 @@ +import { mock } from "jest-mock-extended"; +import { PrismaService } from "../../prisma/prisma.service"; +import { HealthServiceBase } from "../../health/base/health.service.base"; + +describe("Testing the HealthServiceBase", () => { + //ARRANGE + let prismaService: PrismaService; + let healthServiceBase: HealthServiceBase; + + describe("Testing the isDbReady function in HealthServiceBase class", () => { + beforeEach(() => { + prismaService = mock<PrismaService>(); + healthServiceBase = new HealthServiceBase(prismaService); + }); + it("should return true if allow connection to db", async () => { + //ARRANGE + (prismaService.$queryRaw as jest.Mock).mockReturnValue( + Promise.resolve(true) + ); + //ACT + const response = await healthServiceBase.isDbReady(); + //ASSERT + expect(response).toBe(true); + }); + it("should return false if db is not available", async () => { + //ARRANGE + (prismaService.$queryRaw as jest.Mock).mockReturnValue( + Promise.reject(false) + ); + //ACT + const response = await healthServiceBase.isDbReady(); + //ASSERT + expect(response).toBe(false); + }); + }); +}); diff --git a/server/src/types.ts b/server/src/types.ts new file mode 100644 index 0000000..f762a5d --- /dev/null +++ b/server/src/types.ts @@ -0,0 +1,3 @@ +import type { JsonValue } from "type-fest"; + +export type InputJsonValue = Omit<JsonValue, "null">; diff --git a/server/src/user/base/CreateUserArgs.ts b/server/src/user/base/CreateUserArgs.ts new file mode 100644 index 0000000..092a504 --- /dev/null +++ b/server/src/user/base/CreateUserArgs.ts @@ -0,0 +1,30 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { ArgsType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { UserCreateInput } from "./UserCreateInput"; +import { ValidateNested } from "class-validator"; +import { Type } from "class-transformer"; + +@ArgsType() +class CreateUserArgs { + @ApiProperty({ + required: true, + type: () => UserCreateInput, + }) + @ValidateNested() + @Type(() => UserCreateInput) + @Field(() => UserCreateInput, { nullable: false }) + data!: UserCreateInput; +} + +export { CreateUserArgs as CreateUserArgs }; diff --git a/server/src/user/base/DeleteUserArgs.ts b/server/src/user/base/DeleteUserArgs.ts new file mode 100644 index 0000000..042ed5f --- /dev/null +++ b/server/src/user/base/DeleteUserArgs.ts @@ -0,0 +1,30 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { ArgsType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { UserWhereUniqueInput } from "./UserWhereUniqueInput"; +import { ValidateNested } from "class-validator"; +import { Type } from "class-transformer"; + +@ArgsType() +class DeleteUserArgs { + @ApiProperty({ + required: true, + type: () => UserWhereUniqueInput, + }) + @ValidateNested() + @Type(() => UserWhereUniqueInput) + @Field(() => UserWhereUniqueInput, { nullable: false }) + where!: UserWhereUniqueInput; +} + +export { DeleteUserArgs as DeleteUserArgs }; diff --git a/server/src/user/base/UpdateUserArgs.ts b/server/src/user/base/UpdateUserArgs.ts new file mode 100644 index 0000000..1f13420 --- /dev/null +++ b/server/src/user/base/UpdateUserArgs.ts @@ -0,0 +1,40 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { ArgsType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { UserWhereUniqueInput } from "./UserWhereUniqueInput"; +import { ValidateNested } from "class-validator"; +import { Type } from "class-transformer"; +import { UserUpdateInput } from "./UserUpdateInput"; + +@ArgsType() +class UpdateUserArgs { + @ApiProperty({ + required: true, + type: () => UserWhereUniqueInput, + }) + @ValidateNested() + @Type(() => UserWhereUniqueInput) + @Field(() => UserWhereUniqueInput, { nullable: false }) + where!: UserWhereUniqueInput; + + @ApiProperty({ + required: true, + type: () => UserUpdateInput, + }) + @ValidateNested() + @Type(() => UserUpdateInput) + @Field(() => UserUpdateInput, { nullable: false }) + data!: UserUpdateInput; +} + +export { UpdateUserArgs as UpdateUserArgs }; diff --git a/server/src/user/base/User.ts b/server/src/user/base/User.ts new file mode 100644 index 0000000..45adebe --- /dev/null +++ b/server/src/user/base/User.ts @@ -0,0 +1,84 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { ObjectType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsDate, IsString, IsOptional } from "class-validator"; +import { Type } from "class-transformer"; +import { IsJSONValue } from "@app/custom-validators"; +import { GraphQLJSON } from "graphql-type-json"; +import { JsonValue } from "type-fest"; + +@ObjectType() +class User { + @ApiProperty({ + required: true, + }) + @IsDate() + @Type(() => Date) + @Field(() => Date) + createdAt!: Date; + + @ApiProperty({ + required: false, + type: String, + }) + @IsString() + @IsOptional() + @Field(() => String, { + nullable: true, + }) + firstName!: string | null; + + @ApiProperty({ + required: true, + type: String, + }) + @IsString() + @Field(() => String) + id!: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsString() + @IsOptional() + @Field(() => String, { + nullable: true, + }) + lastName!: string | null; + + @ApiProperty({ + required: true, + }) + @IsJSONValue() + @Field(() => GraphQLJSON) + roles!: JsonValue; + + @ApiProperty({ + required: true, + }) + @IsDate() + @Type(() => Date) + @Field(() => Date) + updatedAt!: Date; + + @ApiProperty({ + required: true, + type: String, + }) + @IsString() + @Field(() => String) + username!: string; +} + +export { User as User }; diff --git a/server/src/user/base/UserCountArgs.ts b/server/src/user/base/UserCountArgs.ts new file mode 100644 index 0000000..f4a14ac --- /dev/null +++ b/server/src/user/base/UserCountArgs.ts @@ -0,0 +1,28 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { ArgsType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { UserWhereInput } from "./UserWhereInput"; +import { Type } from "class-transformer"; + +@ArgsType() +class UserCountArgs { + @ApiProperty({ + required: false, + type: () => UserWhereInput, + }) + @Field(() => UserWhereInput, { nullable: true }) + @Type(() => UserWhereInput) + where?: UserWhereInput; +} + +export { UserCountArgs as UserCountArgs }; diff --git a/server/src/user/base/UserCreateInput.ts b/server/src/user/base/UserCreateInput.ts new file mode 100644 index 0000000..6896f2a --- /dev/null +++ b/server/src/user/base/UserCreateInput.ts @@ -0,0 +1,67 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { InputType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsString, IsOptional } from "class-validator"; +import { IsJSONValue } from "@app/custom-validators"; +import { GraphQLJSON } from "graphql-type-json"; +import { InputJsonValue } from "../../types"; + +@InputType() +class UserCreateInput { + @ApiProperty({ + required: false, + type: String, + }) + @IsString() + @IsOptional() + @Field(() => String, { + nullable: true, + }) + firstName?: string | null; + + @ApiProperty({ + required: false, + type: String, + }) + @IsString() + @IsOptional() + @Field(() => String, { + nullable: true, + }) + lastName?: string | null; + + @ApiProperty({ + required: true, + type: String, + }) + @IsString() + @Field(() => String) + password!: string; + + @ApiProperty({ + required: true, + }) + @IsJSONValue() + @Field(() => GraphQLJSON) + roles!: InputJsonValue; + + @ApiProperty({ + required: true, + type: String, + }) + @IsString() + @Field(() => String) + username!: string; +} + +export { UserCreateInput as UserCreateInput }; diff --git a/server/src/user/base/UserFindManyArgs.ts b/server/src/user/base/UserFindManyArgs.ts new file mode 100644 index 0000000..8ba369c --- /dev/null +++ b/server/src/user/base/UserFindManyArgs.ts @@ -0,0 +1,62 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { ArgsType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { UserWhereInput } from "./UserWhereInput"; +import { IsOptional, ValidateNested, IsInt } from "class-validator"; +import { Type } from "class-transformer"; +import { UserOrderByInput } from "./UserOrderByInput"; + +@ArgsType() +class UserFindManyArgs { + @ApiProperty({ + required: false, + type: () => UserWhereInput, + }) + @IsOptional() + @ValidateNested() + @Field(() => UserWhereInput, { nullable: true }) + @Type(() => UserWhereInput) + where?: UserWhereInput; + + @ApiProperty({ + required: false, + type: [UserOrderByInput], + }) + @IsOptional() + @ValidateNested({ each: true }) + @Field(() => [UserOrderByInput], { nullable: true }) + @Type(() => UserOrderByInput) + orderBy?: Array<UserOrderByInput>; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @IsInt() + @Field(() => Number, { nullable: true }) + @Type(() => Number) + skip?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @IsInt() + @Field(() => Number, { nullable: true }) + @Type(() => Number) + take?: number; +} + +export { UserFindManyArgs as UserFindManyArgs }; diff --git a/server/src/user/base/UserFindUniqueArgs.ts b/server/src/user/base/UserFindUniqueArgs.ts new file mode 100644 index 0000000..c64506f --- /dev/null +++ b/server/src/user/base/UserFindUniqueArgs.ts @@ -0,0 +1,30 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { ArgsType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { UserWhereUniqueInput } from "./UserWhereUniqueInput"; +import { ValidateNested } from "class-validator"; +import { Type } from "class-transformer"; + +@ArgsType() +class UserFindUniqueArgs { + @ApiProperty({ + required: true, + type: () => UserWhereUniqueInput, + }) + @ValidateNested() + @Type(() => UserWhereUniqueInput) + @Field(() => UserWhereUniqueInput, { nullable: false }) + where!: UserWhereUniqueInput; +} + +export { UserFindUniqueArgs as UserFindUniqueArgs }; diff --git a/server/src/user/base/UserListRelationFilter.ts b/server/src/user/base/UserListRelationFilter.ts new file mode 100644 index 0000000..0ff7d94 --- /dev/null +++ b/server/src/user/base/UserListRelationFilter.ts @@ -0,0 +1,56 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { InputType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { UserWhereInput } from "./UserWhereInput"; +import { ValidateNested, IsOptional } from "class-validator"; +import { Type } from "class-transformer"; + +@InputType() +class UserListRelationFilter { + @ApiProperty({ + required: false, + type: () => UserWhereInput, + }) + @ValidateNested() + @Type(() => UserWhereInput) + @IsOptional() + @Field(() => UserWhereInput, { + nullable: true, + }) + every?: UserWhereInput; + + @ApiProperty({ + required: false, + type: () => UserWhereInput, + }) + @ValidateNested() + @Type(() => UserWhereInput) + @IsOptional() + @Field(() => UserWhereInput, { + nullable: true, + }) + some?: UserWhereInput; + + @ApiProperty({ + required: false, + type: () => UserWhereInput, + }) + @ValidateNested() + @Type(() => UserWhereInput) + @IsOptional() + @Field(() => UserWhereInput, { + nullable: true, + }) + none?: UserWhereInput; +} +export { UserListRelationFilter as UserListRelationFilter }; diff --git a/server/src/user/base/UserOrderByInput.ts b/server/src/user/base/UserOrderByInput.ts new file mode 100644 index 0000000..1ded2ed --- /dev/null +++ b/server/src/user/base/UserOrderByInput.ts @@ -0,0 +1,111 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { InputType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional, IsEnum } from "class-validator"; +import { SortOrder } from "../../util/SortOrder"; + +@InputType({ + isAbstract: true, + description: undefined, +}) +class UserOrderByInput { + @ApiProperty({ + required: false, + enum: ["asc", "desc"], + }) + @IsOptional() + @IsEnum(SortOrder) + @Field(() => SortOrder, { + nullable: true, + }) + createdAt?: SortOrder; + + @ApiProperty({ + required: false, + enum: ["asc", "desc"], + }) + @IsOptional() + @IsEnum(SortOrder) + @Field(() => SortOrder, { + nullable: true, + }) + firstName?: SortOrder; + + @ApiProperty({ + required: false, + enum: ["asc", "desc"], + }) + @IsOptional() + @IsEnum(SortOrder) + @Field(() => SortOrder, { + nullable: true, + }) + id?: SortOrder; + + @ApiProperty({ + required: false, + enum: ["asc", "desc"], + }) + @IsOptional() + @IsEnum(SortOrder) + @Field(() => SortOrder, { + nullable: true, + }) + lastName?: SortOrder; + + @ApiProperty({ + required: false, + enum: ["asc", "desc"], + }) + @IsOptional() + @IsEnum(SortOrder) + @Field(() => SortOrder, { + nullable: true, + }) + password?: SortOrder; + + @ApiProperty({ + required: false, + enum: ["asc", "desc"], + }) + @IsOptional() + @IsEnum(SortOrder) + @Field(() => SortOrder, { + nullable: true, + }) + roles?: SortOrder; + + @ApiProperty({ + required: false, + enum: ["asc", "desc"], + }) + @IsOptional() + @IsEnum(SortOrder) + @Field(() => SortOrder, { + nullable: true, + }) + updatedAt?: SortOrder; + + @ApiProperty({ + required: false, + enum: ["asc", "desc"], + }) + @IsOptional() + @IsEnum(SortOrder) + @Field(() => SortOrder, { + nullable: true, + }) + username?: SortOrder; +} + +export { UserOrderByInput as UserOrderByInput }; diff --git a/server/src/user/base/UserUpdateInput.ts b/server/src/user/base/UserUpdateInput.ts new file mode 100644 index 0000000..b6e0e21 --- /dev/null +++ b/server/src/user/base/UserUpdateInput.ts @@ -0,0 +1,76 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { InputType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsString, IsOptional } from "class-validator"; +import { IsJSONValue } from "@app/custom-validators"; +import { GraphQLJSON } from "graphql-type-json"; +import { InputJsonValue } from "../../types"; + +@InputType() +class UserUpdateInput { + @ApiProperty({ + required: false, + type: String, + }) + @IsString() + @IsOptional() + @Field(() => String, { + nullable: true, + }) + firstName?: string | null; + + @ApiProperty({ + required: false, + type: String, + }) + @IsString() + @IsOptional() + @Field(() => String, { + nullable: true, + }) + lastName?: string | null; + + @ApiProperty({ + required: false, + type: String, + }) + @IsString() + @IsOptional() + @Field(() => String, { + nullable: true, + }) + password?: string; + + @ApiProperty({ + required: false, + }) + @IsJSONValue() + @IsOptional() + @Field(() => GraphQLJSON, { + nullable: true, + }) + roles?: InputJsonValue; + + @ApiProperty({ + required: false, + type: String, + }) + @IsString() + @IsOptional() + @Field(() => String, { + nullable: true, + }) + username?: string; +} + +export { UserUpdateInput as UserUpdateInput }; diff --git a/server/src/user/base/UserWhereInput.ts b/server/src/user/base/UserWhereInput.ts new file mode 100644 index 0000000..a8babc1 --- /dev/null +++ b/server/src/user/base/UserWhereInput.ts @@ -0,0 +1,66 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { InputType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { StringNullableFilter } from "../../util/StringNullableFilter"; +import { Type } from "class-transformer"; +import { IsOptional } from "class-validator"; +import { StringFilter } from "../../util/StringFilter"; + +@InputType() +class UserWhereInput { + @ApiProperty({ + required: false, + type: StringNullableFilter, + }) + @Type(() => StringNullableFilter) + @IsOptional() + @Field(() => StringNullableFilter, { + nullable: true, + }) + firstName?: StringNullableFilter; + + @ApiProperty({ + required: false, + type: StringFilter, + }) + @Type(() => StringFilter) + @IsOptional() + @Field(() => StringFilter, { + nullable: true, + }) + id?: StringFilter; + + @ApiProperty({ + required: false, + type: StringNullableFilter, + }) + @Type(() => StringNullableFilter) + @IsOptional() + @Field(() => StringNullableFilter, { + nullable: true, + }) + lastName?: StringNullableFilter; + + @ApiProperty({ + required: false, + type: StringFilter, + }) + @Type(() => StringFilter) + @IsOptional() + @Field(() => StringFilter, { + nullable: true, + }) + username?: StringFilter; +} + +export { UserWhereInput as UserWhereInput }; diff --git a/server/src/user/base/UserWhereUniqueInput.ts b/server/src/user/base/UserWhereUniqueInput.ts new file mode 100644 index 0000000..0bcea12 --- /dev/null +++ b/server/src/user/base/UserWhereUniqueInput.ts @@ -0,0 +1,27 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { InputType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsString } from "class-validator"; + +@InputType() +class UserWhereUniqueInput { + @ApiProperty({ + required: true, + type: String, + }) + @IsString() + @Field(() => String) + id!: string; +} + +export { UserWhereUniqueInput as UserWhereUniqueInput }; diff --git a/server/src/user/base/user.controller.base.spec.ts b/server/src/user/base/user.controller.base.spec.ts new file mode 100644 index 0000000..2a2044a --- /dev/null +++ b/server/src/user/base/user.controller.base.spec.ts @@ -0,0 +1,206 @@ +import { Test } from "@nestjs/testing"; +import { + INestApplication, + HttpStatus, + ExecutionContext, + CallHandler, +} from "@nestjs/common"; +import request from "supertest"; +import { ACGuard } from "nest-access-control"; +import { DefaultAuthGuard } from "../../auth/defaultAuth.guard"; +import { ACLModule } from "../../auth/acl.module"; +import { AclFilterResponseInterceptor } from "../../interceptors/aclFilterResponse.interceptor"; +import { AclValidateRequestInterceptor } from "../../interceptors/aclValidateRequest.interceptor"; +import { map } from "rxjs"; +import { UserController } from "../user.controller"; +import { UserService } from "../user.service"; + +const nonExistingId = "nonExistingId"; +const existingId = "existingId"; +const CREATE_INPUT = { + createdAt: new Date(), + firstName: "exampleFirstName", + id: "exampleId", + lastName: "exampleLastName", + password: "examplePassword", + updatedAt: new Date(), + username: "exampleUsername", +}; +const CREATE_RESULT = { + createdAt: new Date(), + firstName: "exampleFirstName", + id: "exampleId", + lastName: "exampleLastName", + password: "examplePassword", + updatedAt: new Date(), + username: "exampleUsername", +}; +const FIND_MANY_RESULT = [ + { + createdAt: new Date(), + firstName: "exampleFirstName", + id: "exampleId", + lastName: "exampleLastName", + password: "examplePassword", + updatedAt: new Date(), + username: "exampleUsername", + }, +]; +const FIND_ONE_RESULT = { + createdAt: new Date(), + firstName: "exampleFirstName", + id: "exampleId", + lastName: "exampleLastName", + password: "examplePassword", + updatedAt: new Date(), + username: "exampleUsername", +}; + +const service = { + create() { + return CREATE_RESULT; + }, + findMany: () => FIND_MANY_RESULT, + findOne: ({ where }: { where: { id: string } }) => { + switch (where.id) { + case existingId: + return FIND_ONE_RESULT; + case nonExistingId: + return null; + } + }, +}; + +const basicAuthGuard = { + canActivate: (context: ExecutionContext) => { + const argumentHost = context.switchToHttp(); + const request = argumentHost.getRequest(); + request.user = { + roles: ["user"], + }; + return true; + }, +}; + +const acGuard = { + canActivate: () => { + return true; + }, +}; + +const aclFilterResponseInterceptor = { + intercept: (context: ExecutionContext, next: CallHandler) => { + return next.handle().pipe( + map((data) => { + return data; + }) + ); + }, +}; +const aclValidateRequestInterceptor = { + intercept: (context: ExecutionContext, next: CallHandler) => { + return next.handle(); + }, +}; + +describe("User", () => { + let app: INestApplication; + + beforeAll(async () => { + const moduleRef = await Test.createTestingModule({ + providers: [ + { + provide: UserService, + useValue: service, + }, + ], + controllers: [UserController], + imports: [ACLModule], + }) + .overrideGuard(DefaultAuthGuard) + .useValue(basicAuthGuard) + .overrideGuard(ACGuard) + .useValue(acGuard) + .overrideInterceptor(AclFilterResponseInterceptor) + .useValue(aclFilterResponseInterceptor) + .overrideInterceptor(AclValidateRequestInterceptor) + .useValue(aclValidateRequestInterceptor) + .compile(); + + app = moduleRef.createNestApplication(); + await app.init(); + }); + + test("POST /users", async () => { + await request(app.getHttpServer()) + .post("/users") + .send(CREATE_INPUT) + .expect(HttpStatus.CREATED) + .expect({ + ...CREATE_RESULT, + createdAt: CREATE_RESULT.createdAt.toISOString(), + updatedAt: CREATE_RESULT.updatedAt.toISOString(), + }); + }); + + test("GET /users", async () => { + await request(app.getHttpServer()) + .get("/users") + .expect(HttpStatus.OK) + .expect([ + { + ...FIND_MANY_RESULT[0], + createdAt: FIND_MANY_RESULT[0].createdAt.toISOString(), + updatedAt: FIND_MANY_RESULT[0].updatedAt.toISOString(), + }, + ]); + }); + + test("GET /users/:id non existing", async () => { + await request(app.getHttpServer()) + .get(`${"/users"}/${nonExistingId}`) + .expect(HttpStatus.NOT_FOUND) + .expect({ + statusCode: HttpStatus.NOT_FOUND, + message: `No resource was found for {"${"id"}":"${nonExistingId}"}`, + error: "Not Found", + }); + }); + + test("GET /users/:id existing", async () => { + await request(app.getHttpServer()) + .get(`${"/users"}/${existingId}`) + .expect(HttpStatus.OK) + .expect({ + ...FIND_ONE_RESULT, + createdAt: FIND_ONE_RESULT.createdAt.toISOString(), + updatedAt: FIND_ONE_RESULT.updatedAt.toISOString(), + }); + }); + + test("POST /users existing resource", async () => { + const agent = request(app.getHttpServer()); + await agent + .post("/users") + .send(CREATE_INPUT) + .expect(HttpStatus.CREATED) + .expect({ + ...CREATE_RESULT, + createdAt: CREATE_RESULT.createdAt.toISOString(), + updatedAt: CREATE_RESULT.updatedAt.toISOString(), + }) + .then(function () { + agent + .post("/users") + .send(CREATE_INPUT) + .expect(HttpStatus.CONFLICT) + .expect({ + statusCode: HttpStatus.CONFLICT, + }); + }); + }); + + afterAll(async () => { + await app.close(); + }); +}); diff --git a/server/src/user/base/user.controller.base.ts b/server/src/user/base/user.controller.base.ts new file mode 100644 index 0000000..0a05e44 --- /dev/null +++ b/server/src/user/base/user.controller.base.ts @@ -0,0 +1,203 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import * as common from "@nestjs/common"; +import * as swagger from "@nestjs/swagger"; +import { isRecordNotFoundError } from "../../prisma.util"; +import * as errors from "../../errors"; +import { Request } from "express"; +import { plainToClass } from "class-transformer"; +import { ApiNestedQuery } from "../../decorators/api-nested-query.decorator"; +import * as nestAccessControl from "nest-access-control"; +import * as defaultAuthGuard from "../../auth/defaultAuth.guard"; +import { UserService } from "../user.service"; +import { AclValidateRequestInterceptor } from "../../interceptors/aclValidateRequest.interceptor"; +import { AclFilterResponseInterceptor } from "../../interceptors/aclFilterResponse.interceptor"; +import { UserCreateInput } from "./UserCreateInput"; +import { UserWhereInput } from "./UserWhereInput"; +import { UserWhereUniqueInput } from "./UserWhereUniqueInput"; +import { UserFindManyArgs } from "./UserFindManyArgs"; +import { UserUpdateInput } from "./UserUpdateInput"; +import { User } from "./User"; + +@swagger.ApiBearerAuth() +@common.UseGuards(defaultAuthGuard.DefaultAuthGuard, nestAccessControl.ACGuard) +export class UserControllerBase { + constructor( + protected readonly service: UserService, + protected readonly rolesBuilder: nestAccessControl.RolesBuilder + ) {} + @common.UseInterceptors(AclValidateRequestInterceptor) + @common.Post() + @swagger.ApiCreatedResponse({ type: User }) + @nestAccessControl.UseRoles({ + resource: "User", + action: "create", + possession: "any", + }) + @swagger.ApiForbiddenResponse({ + type: errors.ForbiddenException, + }) + async create(@common.Body() data: UserCreateInput): Promise<User> { + return await this.service.create({ + data: data, + select: { + createdAt: true, + firstName: true, + id: true, + lastName: true, + roles: true, + updatedAt: true, + username: true, + }, + }); + } + + @common.UseInterceptors(AclFilterResponseInterceptor) + @common.Get() + @swagger.ApiOkResponse({ type: [User] }) + @ApiNestedQuery(UserFindManyArgs) + @nestAccessControl.UseRoles({ + resource: "User", + action: "read", + possession: "any", + }) + @swagger.ApiForbiddenResponse({ + type: errors.ForbiddenException, + }) + async findMany(@common.Req() request: Request): Promise<User[]> { + const args = plainToClass(UserFindManyArgs, request.query); + return this.service.findMany({ + ...args, + select: { + createdAt: true, + firstName: true, + id: true, + lastName: true, + roles: true, + updatedAt: true, + username: true, + }, + }); + } + + @common.UseInterceptors(AclFilterResponseInterceptor) + @common.Get("/:id") + @swagger.ApiOkResponse({ type: User }) + @swagger.ApiNotFoundResponse({ type: errors.NotFoundException }) + @nestAccessControl.UseRoles({ + resource: "User", + action: "read", + possession: "own", + }) + @swagger.ApiForbiddenResponse({ + type: errors.ForbiddenException, + }) + async findOne( + @common.Param() params: UserWhereUniqueInput + ): Promise<User | null> { + const result = await this.service.findOne({ + where: params, + select: { + createdAt: true, + firstName: true, + id: true, + lastName: true, + roles: true, + updatedAt: true, + username: true, + }, + }); + if (result === null) { + throw new errors.NotFoundException( + `No resource was found for ${JSON.stringify(params)}` + ); + } + return result; + } + + @common.UseInterceptors(AclValidateRequestInterceptor) + @common.Patch("/:id") + @swagger.ApiOkResponse({ type: User }) + @swagger.ApiNotFoundResponse({ type: errors.NotFoundException }) + @nestAccessControl.UseRoles({ + resource: "User", + action: "update", + possession: "any", + }) + @swagger.ApiForbiddenResponse({ + type: errors.ForbiddenException, + }) + async update( + @common.Param() params: UserWhereUniqueInput, + @common.Body() data: UserUpdateInput + ): Promise<User | null> { + try { + return await this.service.update({ + where: params, + data: data, + select: { + createdAt: true, + firstName: true, + id: true, + lastName: true, + roles: true, + updatedAt: true, + username: true, + }, + }); + } catch (error) { + if (isRecordNotFoundError(error)) { + throw new errors.NotFoundException( + `No resource was found for ${JSON.stringify(params)}` + ); + } + throw error; + } + } + + @common.Delete("/:id") + @swagger.ApiOkResponse({ type: User }) + @swagger.ApiNotFoundResponse({ type: errors.NotFoundException }) + @nestAccessControl.UseRoles({ + resource: "User", + action: "delete", + possession: "any", + }) + @swagger.ApiForbiddenResponse({ + type: errors.ForbiddenException, + }) + async delete( + @common.Param() params: UserWhereUniqueInput + ): Promise<User | null> { + try { + return await this.service.delete({ + where: params, + select: { + createdAt: true, + firstName: true, + id: true, + lastName: true, + roles: true, + updatedAt: true, + username: true, + }, + }); + } catch (error) { + if (isRecordNotFoundError(error)) { + throw new errors.NotFoundException( + `No resource was found for ${JSON.stringify(params)}` + ); + } + throw error; + } + } +} diff --git a/server/src/user/base/user.module.base.ts b/server/src/user/base/user.module.base.ts new file mode 100644 index 0000000..a8b6c68 --- /dev/null +++ b/server/src/user/base/user.module.base.ts @@ -0,0 +1,18 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { Module } from "@nestjs/common"; +import { ACLModule } from "../../auth/acl.module"; +@Module({ + imports: [ACLModule], + exports: [ACLModule], +}) +export class UserModuleBase {} diff --git a/server/src/user/base/user.resolver.base.ts b/server/src/user/base/user.resolver.base.ts new file mode 100644 index 0000000..21558be --- /dev/null +++ b/server/src/user/base/user.resolver.base.ts @@ -0,0 +1,134 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import * as graphql from "@nestjs/graphql"; +import { GraphQLError } from "graphql"; +import { isRecordNotFoundError } from "../../prisma.util"; +import { MetaQueryPayload } from "../../util/MetaQueryPayload"; +import * as nestAccessControl from "nest-access-control"; +import * as gqlACGuard from "../../auth/gqlAC.guard"; +import { GqlDefaultAuthGuard } from "../../auth/gqlDefaultAuth.guard"; +import * as common from "@nestjs/common"; +import { AclFilterResponseInterceptor } from "../../interceptors/aclFilterResponse.interceptor"; +import { AclValidateRequestInterceptor } from "../../interceptors/aclValidateRequest.interceptor"; +import { CreateUserArgs } from "./CreateUserArgs"; +import { UpdateUserArgs } from "./UpdateUserArgs"; +import { DeleteUserArgs } from "./DeleteUserArgs"; +import { UserCountArgs } from "./UserCountArgs"; +import { UserFindManyArgs } from "./UserFindManyArgs"; +import { UserFindUniqueArgs } from "./UserFindUniqueArgs"; +import { User } from "./User"; +import { UserService } from "../user.service"; +@common.UseGuards(GqlDefaultAuthGuard, gqlACGuard.GqlACGuard) +@graphql.Resolver(() => User) +export class UserResolverBase { + constructor( + protected readonly service: UserService, + protected readonly rolesBuilder: nestAccessControl.RolesBuilder + ) {} + + @graphql.Query(() => MetaQueryPayload) + @nestAccessControl.UseRoles({ + resource: "User", + action: "read", + possession: "any", + }) + async _usersMeta( + @graphql.Args() args: UserCountArgs + ): Promise<MetaQueryPayload> { + const result = await this.service.count(args); + return { + count: result, + }; + } + + @common.UseInterceptors(AclFilterResponseInterceptor) + @graphql.Query(() => [User]) + @nestAccessControl.UseRoles({ + resource: "User", + action: "read", + possession: "any", + }) + async users(@graphql.Args() args: UserFindManyArgs): Promise<User[]> { + return this.service.findMany(args); + } + + @common.UseInterceptors(AclFilterResponseInterceptor) + @graphql.Query(() => User, { nullable: true }) + @nestAccessControl.UseRoles({ + resource: "User", + action: "read", + possession: "own", + }) + async user(@graphql.Args() args: UserFindUniqueArgs): Promise<User | null> { + const result = await this.service.findOne(args); + if (result === null) { + return null; + } + return result; + } + + @common.UseInterceptors(AclValidateRequestInterceptor) + @graphql.Mutation(() => User) + @nestAccessControl.UseRoles({ + resource: "User", + action: "create", + possession: "any", + }) + async createUser(@graphql.Args() args: CreateUserArgs): Promise<User> { + return await this.service.create({ + ...args, + data: args.data, + }); + } + + @common.UseInterceptors(AclValidateRequestInterceptor) + @graphql.Mutation(() => User) + @nestAccessControl.UseRoles({ + resource: "User", + action: "update", + possession: "any", + }) + async updateUser(@graphql.Args() args: UpdateUserArgs): Promise<User | null> { + try { + return await this.service.update({ + ...args, + data: args.data, + }); + } catch (error) { + if (isRecordNotFoundError(error)) { + throw new GraphQLError( + `No resource was found for ${JSON.stringify(args.where)}` + ); + } + throw error; + } + } + + @graphql.Mutation(() => User) + @nestAccessControl.UseRoles({ + resource: "User", + action: "delete", + possession: "any", + }) + async deleteUser(@graphql.Args() args: DeleteUserArgs): Promise<User | null> { + try { + return await this.service.delete(args); + } catch (error) { + if (isRecordNotFoundError(error)) { + throw new GraphQLError( + `No resource was found for ${JSON.stringify(args.where)}` + ); + } + throw error; + } + } +} diff --git a/server/src/user/base/user.service.base.ts b/server/src/user/base/user.service.base.ts new file mode 100644 index 0000000..3c9de61 --- /dev/null +++ b/server/src/user/base/user.service.base.ts @@ -0,0 +1,74 @@ +/* +------------------------------------------------------------------------------ +This code was generated by Amplication. + +Changes to this file will be lost if the code is regenerated. + +There are other ways to to customize your code, see this doc to learn more +https://docs.amplication.com/how-to/custom-code + +------------------------------------------------------------------------------ + */ +import { PrismaService } from "../../prisma/prisma.service"; +import { Prisma, User } from "@prisma/client"; +import { PasswordService } from "../../auth/password.service"; +import { transformStringFieldUpdateInput } from "../../prisma.util"; + +export class UserServiceBase { + constructor( + protected readonly prisma: PrismaService, + protected readonly passwordService: PasswordService + ) {} + + async count<T extends Prisma.UserCountArgs>( + args: Prisma.SelectSubset<T, Prisma.UserCountArgs> + ): Promise<number> { + return this.prisma.user.count(args); + } + + async findMany<T extends Prisma.UserFindManyArgs>( + args: Prisma.SelectSubset<T, Prisma.UserFindManyArgs> + ): Promise<User[]> { + return this.prisma.user.findMany(args); + } + async findOne<T extends Prisma.UserFindUniqueArgs>( + args: Prisma.SelectSubset<T, Prisma.UserFindUniqueArgs> + ): Promise<User | null> { + return this.prisma.user.findUnique(args); + } + async create<T extends Prisma.UserCreateArgs>( + args: Prisma.SelectSubset<T, Prisma.UserCreateArgs> + ): Promise<User> { + return this.prisma.user.create<T>({ + ...args, + + data: { + ...args.data, + password: await this.passwordService.hash(args.data.password), + }, + }); + } + async update<T extends Prisma.UserUpdateArgs>( + args: Prisma.SelectSubset<T, Prisma.UserUpdateArgs> + ): Promise<User> { + return this.prisma.user.update<T>({ + ...args, + + data: { + ...args.data, + + password: + args.data.password && + (await transformStringFieldUpdateInput( + args.data.password, + (password) => this.passwordService.hash(password) + )), + }, + }); + } + async delete<T extends Prisma.UserDeleteArgs>( + args: Prisma.SelectSubset<T, Prisma.UserDeleteArgs> + ): Promise<User> { + return this.prisma.user.delete(args); + } +} diff --git a/server/src/user/user.controller.ts b/server/src/user/user.controller.ts new file mode 100644 index 0000000..21d9583 --- /dev/null +++ b/server/src/user/user.controller.ts @@ -0,0 +1,17 @@ +import * as common from "@nestjs/common"; +import * as swagger from "@nestjs/swagger"; +import * as nestAccessControl from "nest-access-control"; +import { UserService } from "./user.service"; +import { UserControllerBase } from "./base/user.controller.base"; + +@swagger.ApiTags("users") +@common.Controller("users") +export class UserController extends UserControllerBase { + constructor( + protected readonly service: UserService, + @nestAccessControl.InjectRolesBuilder() + protected readonly rolesBuilder: nestAccessControl.RolesBuilder + ) { + super(service, rolesBuilder); + } +} diff --git a/server/src/user/user.module.ts b/server/src/user/user.module.ts new file mode 100644 index 0000000..2d6dd05 --- /dev/null +++ b/server/src/user/user.module.ts @@ -0,0 +1,14 @@ +import { Module, forwardRef } from "@nestjs/common"; +import { AuthModule } from "../auth/auth.module"; +import { UserModuleBase } from "./base/user.module.base"; +import { UserService } from "./user.service"; +import { UserController } from "./user.controller"; +import { UserResolver } from "./user.resolver"; + +@Module({ + imports: [UserModuleBase, forwardRef(() => AuthModule)], + controllers: [UserController], + providers: [UserService, UserResolver], + exports: [UserService], +}) +export class UserModule {} diff --git a/server/src/user/user.resolver.ts b/server/src/user/user.resolver.ts new file mode 100644 index 0000000..bc3a79b --- /dev/null +++ b/server/src/user/user.resolver.ts @@ -0,0 +1,20 @@ +import * as graphql from "@nestjs/graphql"; +import * as nestAccessControl from "nest-access-control"; +import * as gqlACGuard from "../auth/gqlAC.guard"; +import { GqlDefaultAuthGuard } from "../auth/gqlDefaultAuth.guard"; +import * as common from "@nestjs/common"; +import { UserResolverBase } from "./base/user.resolver.base"; +import { User } from "./base/User"; +import { UserService } from "./user.service"; + +@common.UseGuards(GqlDefaultAuthGuard, gqlACGuard.GqlACGuard) +@graphql.Resolver(() => User) +export class UserResolver extends UserResolverBase { + constructor( + protected readonly service: UserService, + @nestAccessControl.InjectRolesBuilder() + protected readonly rolesBuilder: nestAccessControl.RolesBuilder + ) { + super(service, rolesBuilder); + } +} diff --git a/server/src/user/user.service.ts b/server/src/user/user.service.ts new file mode 100644 index 0000000..a8e4508 --- /dev/null +++ b/server/src/user/user.service.ts @@ -0,0 +1,14 @@ +import { Injectable } from "@nestjs/common"; +import { PrismaService } from "../prisma/prisma.service"; +import { PasswordService } from "../auth/password.service"; +import { UserServiceBase } from "./base/user.service.base"; + +@Injectable() +export class UserService extends UserServiceBase { + constructor( + protected readonly prisma: PrismaService, + protected readonly passwordService: PasswordService + ) { + super(prisma, passwordService); + } +} diff --git a/server/src/util/BooleanFilter.ts b/server/src/util/BooleanFilter.ts new file mode 100644 index 0000000..75f4e34 --- /dev/null +++ b/server/src/util/BooleanFilter.ts @@ -0,0 +1,32 @@ +import { Field, InputType } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { Type } from "class-transformer"; + +@InputType({ + isAbstract: true, + description: undefined, +}) +export class BooleanFilter { + @ApiProperty({ + required: false, + type: Boolean, + }) + @IsOptional() + @Field(() => Boolean, { + nullable: true, + }) + @Type(() => Boolean) + equals?: boolean; + + @ApiProperty({ + required: false, + type: Boolean, + }) + @IsOptional() + @Field(() => Boolean, { + nullable: true, + }) + @Type(() => Boolean) + not?: boolean; +} diff --git a/server/src/util/BooleanNullableFilter.ts b/server/src/util/BooleanNullableFilter.ts new file mode 100644 index 0000000..9f48ac1 --- /dev/null +++ b/server/src/util/BooleanNullableFilter.ts @@ -0,0 +1,31 @@ +import { Field, InputType } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { Type } from "class-transformer"; +@InputType({ + isAbstract: true, + description: undefined, +}) +export class BooleanNullableFilter { + @ApiProperty({ + required: false, + type: Boolean, + }) + @IsOptional() + @Field(() => Boolean, { + nullable: true, + }) + @Type(() => Boolean) + equals?: boolean | null; + + @ApiProperty({ + required: false, + type: Boolean, + }) + @IsOptional() + @Field(() => Boolean, { + nullable: true, + }) + @Type(() => Boolean) + not?: boolean | null; +} diff --git a/server/src/util/DateTimeFilter.ts b/server/src/util/DateTimeFilter.ts new file mode 100644 index 0000000..d2b6dfb --- /dev/null +++ b/server/src/util/DateTimeFilter.ts @@ -0,0 +1,97 @@ +import { Field, InputType } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { Type } from "class-transformer"; +@InputType({ + isAbstract: true, + description: undefined, +}) +export class DateTimeFilter { + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + equals?: Date; + + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + not?: Date; + + @ApiProperty({ + required: false, + type: [Date], + }) + @IsOptional() + @Field(() => [Date], { + nullable: true, + }) + @Type(() => Date) + in?: Date[]; + + @ApiProperty({ + required: false, + type: [Date], + }) + @IsOptional() + @Field(() => [Date], { + nullable: true, + }) + @Type(() => Date) + notIn?: Date[]; + + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + lt?: Date; + + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + lte?: Date; + + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + gt?: Date; + + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + gte?: Date; +} diff --git a/server/src/util/DateTimeNullableFilter.ts b/server/src/util/DateTimeNullableFilter.ts new file mode 100644 index 0000000..ccc00a5 --- /dev/null +++ b/server/src/util/DateTimeNullableFilter.ts @@ -0,0 +1,97 @@ +import { Field, InputType } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { Type } from "class-transformer"; +@InputType({ + isAbstract: true, + description: undefined, +}) +export class DateTimeNullableFilter { + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + equals?: Date | null; + + @ApiProperty({ + required: false, + type: [Date], + }) + @IsOptional() + @Field(() => [Date], { + nullable: true, + }) + @Type(() => Date) + in?: Date[] | null; + + @ApiProperty({ + required: false, + type: [Date], + }) + @IsOptional() + @Field(() => [Date], { + nullable: true, + }) + @Type(() => Date) + notIn?: Date[] | null; + + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + lt?: Date; + + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + lte?: Date; + + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + gt?: Date; + + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + gte?: Date; + + @ApiProperty({ + required: false, + type: Date, + }) + @IsOptional() + @Field(() => Date, { + nullable: true, + }) + @Type(() => Date) + not?: Date; +} diff --git a/server/src/util/FloatFilter.ts b/server/src/util/FloatFilter.ts new file mode 100644 index 0000000..a3266d2 --- /dev/null +++ b/server/src/util/FloatFilter.ts @@ -0,0 +1,98 @@ +import { Field, InputType, Float } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { Type } from "class-transformer"; + +@InputType({ + isAbstract: true, + description: undefined, +}) +export class FloatFilter { + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + equals?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => [Float], { + nullable: true, + }) + @Type(() => Number) + in?: number[]; + + @ApiProperty({ + required: false, + type: [Number], + }) + @IsOptional() + @Field(() => [Float], { + nullable: true, + }) + @Type(() => Number) + notIn?: number[]; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + lt?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + lte?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + gt?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + gte?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + not?: number; +} diff --git a/server/src/util/FloatNullableFilter.ts b/server/src/util/FloatNullableFilter.ts new file mode 100644 index 0000000..feb0fc5 --- /dev/null +++ b/server/src/util/FloatNullableFilter.ts @@ -0,0 +1,98 @@ +import { Field, InputType, Float } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { Type } from "class-transformer"; + +@InputType({ + isAbstract: true, + description: undefined, +}) +export class FloatNullableFilter { + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + equals?: number | null; + + @ApiProperty({ + required: false, + type: [Number], + }) + @IsOptional() + @Field(() => [Float], { + nullable: true, + }) + @Type(() => Number) + in?: number[] | null; + + @ApiProperty({ + required: false, + type: [Number], + }) + @IsOptional() + @Field(() => [Float], { + nullable: true, + }) + @Type(() => Number) + notIn?: number[] | null; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + lt?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + lte?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + gt?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + gte?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Float, { + nullable: true, + }) + @Type(() => Number) + not?: number; +} diff --git a/server/src/util/IntFilter.ts b/server/src/util/IntFilter.ts new file mode 100644 index 0000000..f6880e7 --- /dev/null +++ b/server/src/util/IntFilter.ts @@ -0,0 +1,98 @@ +import { Field, InputType, Int } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { Type } from "class-transformer"; + +@InputType({ + isAbstract: true, + description: undefined, +}) +export class IntFilter { + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + equals?: number; + + @ApiProperty({ + required: false, + type: [Number], + }) + @IsOptional() + @Field(() => [Int], { + nullable: true, + }) + @Type(() => Number) + in?: number[]; + + @ApiProperty({ + required: false, + type: [Number], + }) + @IsOptional() + @Field(() => [Int], { + nullable: true, + }) + @Type(() => Number) + notIn?: number[]; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + lt?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + lte?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + gt?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + gte?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + not?: number; +} diff --git a/server/src/util/IntNullableFilter.ts b/server/src/util/IntNullableFilter.ts new file mode 100644 index 0000000..e3b71a3 --- /dev/null +++ b/server/src/util/IntNullableFilter.ts @@ -0,0 +1,98 @@ +import { Field, InputType, Int } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { Type } from "class-transformer"; + +@InputType({ + isAbstract: true, + description: undefined, +}) +export class IntNullableFilter { + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + equals?: number | null; + + @ApiProperty({ + required: false, + type: [Number], + }) + @IsOptional() + @Field(() => [Int], { + nullable: true, + }) + @Type(() => Number) + in?: number[] | null; + + @ApiProperty({ + required: false, + type: [Number], + }) + @IsOptional() + @Field(() => [Int], { + nullable: true, + }) + @Type(() => Number) + notIn?: number[] | null; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + lt?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + lte?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + gt?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + gte?: number; + + @ApiProperty({ + required: false, + type: Number, + }) + @IsOptional() + @Field(() => Int, { + nullable: true, + }) + @Type(() => Number) + not?: number; +} diff --git a/server/src/util/JsonFilter.ts b/server/src/util/JsonFilter.ts new file mode 100644 index 0000000..7040b74 --- /dev/null +++ b/server/src/util/JsonFilter.ts @@ -0,0 +1,31 @@ +import { Field, InputType } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { GraphQLJSONObject } from "graphql-type-json"; +import { InputJsonValue } from "../types"; + +@InputType({ + isAbstract: true, + description: undefined, +}) +export class JsonFilter { + @ApiProperty({ + required: false, + type: GraphQLJSONObject, + }) + @IsOptional() + @Field(() => GraphQLJSONObject, { + nullable: true, + }) + equals?: InputJsonValue; + + @ApiProperty({ + required: false, + type: GraphQLJSONObject, + }) + @IsOptional() + @Field(() => GraphQLJSONObject, { + nullable: true, + }) + not?: InputJsonValue; +} diff --git a/server/src/util/JsonNullableFilter.ts b/server/src/util/JsonNullableFilter.ts new file mode 100644 index 0000000..3381d52 --- /dev/null +++ b/server/src/util/JsonNullableFilter.ts @@ -0,0 +1,31 @@ +import type { JsonValue } from "type-fest"; +import { Field, InputType } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { GraphQLJSONObject } from "graphql-type-json"; + +@InputType({ + isAbstract: true, + description: undefined, +}) +export class JsonNullableFilter { + @ApiProperty({ + required: false, + type: GraphQLJSONObject, + }) + @IsOptional() + @Field(() => GraphQLJSONObject, { + nullable: true, + }) + equals?: JsonValue; + + @ApiProperty({ + required: false, + type: GraphQLJSONObject, + }) + @IsOptional() + @Field(() => GraphQLJSONObject, { + nullable: true, + }) + not?: JsonValue; +} diff --git a/server/src/util/MetaQueryPayload.ts b/server/src/util/MetaQueryPayload.ts new file mode 100644 index 0000000..fc30531 --- /dev/null +++ b/server/src/util/MetaQueryPayload.ts @@ -0,0 +1,13 @@ +import { ObjectType, Field } from "@nestjs/graphql"; +import { ApiProperty } from "@nestjs/swagger"; + +@ObjectType() +class MetaQueryPayload { + @ApiProperty({ + required: true, + type: [Number], + }) + @Field(() => Number) + count!: number; +} +export { MetaQueryPayload }; diff --git a/server/src/util/QueryMode.ts b/server/src/util/QueryMode.ts new file mode 100644 index 0000000..f9b1653 --- /dev/null +++ b/server/src/util/QueryMode.ts @@ -0,0 +1,10 @@ +import { registerEnumType } from "@nestjs/graphql"; + +export enum QueryMode { + Default = "default", + Insensitive = "insensitive", +} +registerEnumType(QueryMode, { + name: "QueryMode", + description: undefined, +}); diff --git a/server/src/util/SortOrder.ts b/server/src/util/SortOrder.ts new file mode 100644 index 0000000..d4108e6 --- /dev/null +++ b/server/src/util/SortOrder.ts @@ -0,0 +1,10 @@ +import { registerEnumType } from "@nestjs/graphql"; + +export enum SortOrder { + Asc = "asc", + Desc = "desc", +} +registerEnumType(SortOrder, { + name: "SortOrder", + description: undefined, +}); diff --git a/server/src/util/StringFilter.ts b/server/src/util/StringFilter.ts new file mode 100644 index 0000000..80b573d --- /dev/null +++ b/server/src/util/StringFilter.ts @@ -0,0 +1,141 @@ +import { Field, InputType } from "@nestjs/graphql"; +import { QueryMode } from "./QueryMode"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { Type } from "class-transformer"; + +@InputType({ + isAbstract: true, +}) +export class StringFilter { + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + equals?: string; + + @ApiProperty({ + required: false, + type: [String], + }) + @IsOptional() + @Field(() => [String], { + nullable: true, + }) + @Type(() => String) + in?: string[]; + + @ApiProperty({ + required: false, + type: [String], + }) + @IsOptional() + @Field(() => [String], { + nullable: true, + }) + @Type(() => String) + notIn?: string[]; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + lt?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + lte?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + gt?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + gte?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + contains?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + startsWith?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + endsWith?: string; + + @ApiProperty({ + required: false, + enum: ["Default", "Insensitive"], + }) + @IsOptional() + @Field(() => QueryMode, { + nullable: true, + }) + mode?: QueryMode; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + not?: string; +} diff --git a/server/src/util/StringNullableFilter.ts b/server/src/util/StringNullableFilter.ts new file mode 100644 index 0000000..01b399c --- /dev/null +++ b/server/src/util/StringNullableFilter.ts @@ -0,0 +1,141 @@ +import { Field, InputType } from "@nestjs/graphql"; +import { QueryMode } from "./QueryMode"; +import { ApiProperty } from "@nestjs/swagger"; +import { IsOptional } from "class-validator"; +import { Type } from "class-transformer"; + +@InputType({ + isAbstract: true, +}) +export class StringNullableFilter { + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + equals?: string | null; + + @ApiProperty({ + required: false, + type: [String], + }) + @IsOptional() + @Field(() => [String], { + nullable: true, + }) + @Type(() => String) + in?: string[] | null; + + @ApiProperty({ + required: false, + type: [String], + }) + @IsOptional() + @Field(() => [String], { + nullable: true, + }) + @Type(() => String) + notIn?: string[] | null; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + lt?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + lte?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + gt?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + gte?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + contains?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + startsWith?: string; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + endsWith?: string; + + @ApiProperty({ + required: false, + enum: ["Default", "Insensitive"], + }) + @IsOptional() + @Field(() => QueryMode, { + nullable: true, + }) + mode?: QueryMode; + + @ApiProperty({ + required: false, + type: String, + }) + @IsOptional() + @Field(() => String, { + nullable: true, + }) + @Type(() => String) + not?: string; +} diff --git a/server/src/validators/index.ts b/server/src/validators/index.ts new file mode 100644 index 0000000..7f62d84 --- /dev/null +++ b/server/src/validators/index.ts @@ -0,0 +1 @@ +export * from "./is-json-value-validator"; diff --git a/server/src/validators/is-json-value-validator.spec.ts b/server/src/validators/is-json-value-validator.spec.ts new file mode 100644 index 0000000..5a77824 --- /dev/null +++ b/server/src/validators/is-json-value-validator.spec.ts @@ -0,0 +1,44 @@ +import { validate, ValidationError } from "class-validator"; +import { IsJSONValue } from "./is-json-value-validator"; + +class TestClass { + @IsJSONValue() + jsonProperty: unknown; +} + +describe("IsJSONValue", () => { + it("should validate a valid JSON string", async () => { + const testObj = new TestClass(); + testObj.jsonProperty = '{"name": "John", "age": 30}'; + const errors: ValidationError[] = await validate(testObj); + expect(errors.length).toBe(0); + }); + + it("should not validate an invalid JSON string", async () => { + const testObj = new TestClass(); + testObj.jsonProperty = '{name: "John", age: 30}'; + const errors: ValidationError[] = await validate(testObj); + expect(errors.length).toBe(1); + }); + + it("should not validate an invalid JSON string", async () => { + const testObj = new TestClass(); + testObj.jsonProperty = "John"; + const errors: ValidationError[] = await validate(testObj); + expect(errors.length).toBe(1); + }); + + it("should validate a valid JSON object", async () => { + const testObj = new TestClass(); + testObj.jsonProperty = { name: "John", age: 30 }; + const errors: ValidationError[] = await validate(testObj); + expect(errors.length).toBe(0); + }); + + it("should validate a valid JSON array", async () => { + const testObj = new TestClass(); + testObj.jsonProperty = ["John", "30"]; + const errors: ValidationError[] = await validate(testObj); + expect(errors.length).toBe(0); + }); +}); diff --git a/server/src/validators/is-json-value-validator.ts b/server/src/validators/is-json-value-validator.ts new file mode 100644 index 0000000..1002540 --- /dev/null +++ b/server/src/validators/is-json-value-validator.ts @@ -0,0 +1,29 @@ +import { + ValidationArguments, + registerDecorator, + ValidationOptions, +} from "class-validator"; +import isJSONValidator from "validator/lib/isJSON"; + +export function IsJSONValue(validationOptions?: ValidationOptions) { + return function (object: Record<string, any>, propertyName: string) { + registerDecorator({ + name: "IsJSONValue", + target: object.constructor, + propertyName: propertyName, + options: validationOptions, + validator: { + validate(value: any, args: ValidationArguments) { + if (typeof value === "string") { + return isJSONValidator(value); + } + + return isJSONValidator(JSON.stringify(value)); + }, + defaultMessage(args: ValidationArguments): string { + return `${args.property} must be a valid json`; + }, + }, + }); + }; +} diff --git a/server/tsconfig.build.json b/server/tsconfig.build.json new file mode 100644 index 0000000..e579401 --- /dev/null +++ b/server/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["node_modules", "prisma", "test", "dist", "**/*spec.ts", "admin"] +} diff --git a/server/tsconfig.json b/server/tsconfig.json new file mode 100644 index 0000000..f6c463b --- /dev/null +++ b/server/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "baseUrl": "./", + "module": "commonjs", + "declaration": false, + "removeComments": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "es2022", + "lib": ["es2023"], + "sourceMap": true, + "outDir": "./dist", + "incremental": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "strict": true, + "paths": { + "@app/custom-validators": ["src/validators"] + } + }, + "include": ["src"] +}