diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000..a914fd2 --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,25 @@ +# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.209.6/containers/java/.devcontainer/base.Dockerfile + +# [Choice] Java version (use -bullseye variants on local arm64/Apple Silicon): 17, 17-bullseye, 17-buster +ARG VARIANT="17" +FROM mcr.microsoft.com/vscode/devcontainers/java:0-${VARIANT} + +# [Option] Install Maven +ARG INSTALL_MAVEN="false" +ARG MAVEN_VERSION="" +# [Option] Install Gradle +ARG INSTALL_GRADLE="false" +ARG GRADLE_VERSION="" +RUN if [ "${INSTALL_MAVEN}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/sdkman/bin/sdkman-init.sh && sdk install maven \"${MAVEN_VERSION}\""; fi \ + && if [ "${INSTALL_GRADLE}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/sdkman/bin/sdkman-init.sh && sdk install gradle \"${GRADLE_VERSION}\""; fi + +# [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 +ARG NODE_VERSION="none" +RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi + +# [Optional] Uncomment this section to install additional OS packages. +# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ +# && apt-get -y install --no-install-recommends + +# [Optional] Uncomment this line to install global node packages. +# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..8e55b7f --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,57 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: +// https://github.com/microsoft/vscode-dev-containers/tree/v0.209.6/containers/java +{ + "name": "QuestionBank", + "build": { + "dockerfile": "Dockerfile", + "args": { + // Update the VARIANT arg to pick a Java version: 17, 19 + // Append -bullseye or -buster to pin to an OS version. + // Use the -bullseye variants on local arm64/Apple Silicon. + "VARIANT": "21-bullseye", + // Options + // maven and gradle wrappers are used by default, we don't need them installed globally + // "INSTALL_MAVEN": "true", + // "INSTALL_GRADLE": "false", + "NODE_VERSION": "24.20.0" + } + }, + + "customizations": { + "vscode": { + // Set *default* container specific settings.json values on container create. + "settings": { + "java.jdt.ls.java.home": "/docker-java-home" + }, + + // Add the IDs of extensions you want installed when the container is created. + "extensions": [ + "christian-kohler.npm-intellisense", + "firsttris.vscode-jest-runner", + "ms-vscode.vscode-typescript-tslint-plugin", + "dbaeumer.vscode-eslint", + "vscjava.vscode-java-pack", + "pivotal.vscode-boot-dev-pack", + "esbenp.prettier-vscode" + ] + } + }, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + "forwardPorts": [9060, 3001, 9000, 8080], + + // Use 'postCreateCommand' to run commands after the container is created. + // "postCreateCommand": "java -version", + + // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. + "remoteUser": "vscode", + + // Mount the workspace folder to the same path inside the container, so docker-in-docker containers work correctly. See https://github.com/jhipster/generator-jhipster/issues/31239 + "workspaceMount": "source=${localWorkspaceFolder},target=${localWorkspaceFolder},type=bind", + "workspaceFolder": "${localWorkspaceFolder}", + + "features": { + "docker-in-docker": "latest", + "docker-from-docker": "latest" + } +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..864bca4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,24 @@ +# EditorConfig helps developers define and maintain consistent +# coding styles between different editors and IDEs +# editorconfig.org + +root = true + +[*] + +# We recommend you to keep these unchanged +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +# Change these settings to your own preference +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +# Generated by jhipster:java:bootstrap generator +[*.java] +indent_size = 4 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6159150 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,149 @@ +# This file is inspired by https://github.com/alexkaratarakis/gitattributes +# +# Auto detect text files and perform LF normalization +# https://davidlaing.com/2012/09/19/customise-your-gitattributes-to-become-a-git-ninja/ +* text=auto + +# The above will handle all files NOT found below +# These files are text and should be normalized (Convert crlf => lf) + +*.bat text eol=crlf +*.cmd text eol=crlf +*.ps1 text eol=crlf +*.coffee text +*.css text +*.cql text +*.df text +*.ejs text +*.html text +*.java text +*.js text +*.json text +*.less text +*.properties text +*.sass text +*.scss text +*.sh text eol=lf +*.sql text +*.ts text +*.xml text +*.yaml text +*.yml text + +# Documents +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain +*.markdown text +*.md text +*.adoc text +*.textile text +*.mustache text +*.csv text +*.tab text +*.tsv text +*.txt text +AUTHORS text +CHANGELOG text +CHANGES text +CONTRIBUTING text +COPYING text +copyright text +*COPYRIGHT* text +INSTALL text +license text +LICENSE text +NEWS text +readme text +*README* text +TODO text + +# Graphics +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.tif binary +*.tiff binary +*.ico binary +# SVG treated as an asset (binary) by default. If you want to treat it as text, +# comment-out the following line and uncomment the line after. +*.svg binary +#*.svg text +*.eps binary + +# These files are binary and should be left untouched +# (binary is a macro for -text -diff) +*.class binary +*.jar binary +*.war binary + +## LINTERS +.csslintrc text +.eslintrc text +.jscsrc text +.jshintrc text +.jshintignore text +.stylelintrc text + +## CONFIGS +*.conf text +*.config text +.editorconfig text +.gitattributes text +.gitconfig text +.gitignore text +.htaccess text +*.npmignore text + +## HEROKU +Procfile text +.slugignore text + +## AUDIO +*.kar binary +*.m4a binary +*.mid binary +*.midi binary +*.mp3 binary +*.ogg binary +*.ra binary + +## VIDEO +*.3gpp binary +*.3gp binary +*.as binary +*.asf binary +*.asx binary +*.fla binary +*.flv binary +*.m4v binary +*.mng binary +*.mov binary +*.mp4 binary +*.mpeg binary +*.mpg binary +*.swc binary +*.swf binary +*.webm binary + +## ARCHIVES +*.7z binary +*.gz binary +*.rar binary +*.tar binary +*.zip binary + +## FONTS +*.ttf binary +*.eot binary +*.otf binary +*.woff binary +*.woff2 binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c336dd0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,153 @@ +###################### +# Node +###################### +/node/ +node_tmp/ +node_modules/ +npm-debug.log.* +/.awcache/* +/.cache-loader/* +/dist/ + +###################### +# SASS +###################### +.sass-cache/ + +###################### +# Eclipse +###################### +*.pydevproject +.project +.metadata +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath +.factorypath + +# External tool builders +.externalToolBuilders/** + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + +# STS-specific +/.sts4-cache/* + +###################### +# IntelliJ +###################### +.idea/ +*.iml +*.iws +*.ipr +*.ids +*.orig +classes/ +out/ + +###################### +# Visual Studio Code +###################### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +###################### +# Maven +###################### +/log/ +/target/ + +###################### +# Gradle +###################### +.gradle/ +/build/ +/buildSrc/.gradle/ +/buildSrc/build/ + +###################### +# Package Files +###################### +*.jar +*.war +*.ear +*.db + +###################### +# Windows +###################### +# Windows image file caches +Thumbs.db + +# Folder config file +Desktop.ini + +###################### +# Mac OSX +###################### +.DS_Store +.svn + +# Thumbnails +._* + +# Files that might appear on external disk +.Spotlight-V100 +.Trashes + +###################### +# Directories +###################### +/bin/ +/deploy/ + +###################### +# Logs +###################### +*.log* + +###################### +# Others +###################### +*.class +*.*~ +*~ +.merge_file* + +###################### +# Gradle Wrapper +###################### +!gradle/wrapper/gradle-wrapper.jar + +###################### +# Maven Wrapper +###################### +!.mvn/wrapper/maven-wrapper.jar + +###################### +# ESLint +###################### +.eslintcache + +###################### +# Code coverage +###################### +coverage/ +.nyc_output/ diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 0000000..611e501 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,6 @@ +if [ -z "$(which lint-staged)" ]; then + echo 'Running package manager install' + ./npmw install +fi + +lint-staged diff --git a/.lintstagedrc.cjs b/.lintstagedrc.cjs new file mode 100644 index 0000000..6079102 --- /dev/null +++ b/.lintstagedrc.cjs @@ -0,0 +1,3 @@ +module.exports = { + '{,.blueprint/**/,src/**/}*.{md,json,yml,js,cjs,mjs,ts,cts,mts,java,html,vue,css,scss}': ['prettier --write'], +}; diff --git a/.mvn/jvm.config b/.mvn/jvm.config new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/.mvn/jvm.config @@ -0,0 +1 @@ + diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..cb28b0e Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..e788e5e --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..e6e44d6 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,10 @@ +node_modules +package-lock.json +.git + +# Generated by jhipster:java-simple-application:maven +target +.mvn + +# Generated by jhipster:client +target/classes/static/ diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..7849a93 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,14 @@ +endOfLine: auto +printWidth: 140 +singleQuote: true +tabWidth: 2 +useTabs: false +arrowParens: avoid +bracketSameLine: false +plugins: + - prettier-plugin-packagejson + - prettier-plugin-java +overrides: + - files: "*.java" + options: + tabWidth: 4 diff --git a/.yo-rc.json b/.yo-rc.json new file mode 100644 index 0000000..1589107 --- /dev/null +++ b/.yo-rc.json @@ -0,0 +1,27 @@ +{ + "generator-jhipster": { + "applicationType": "monolith", + "authenticationType": "jwt", + "baseName": "questionBank", + "buildTool": "maven", + "cacheProvider": "no", + "clientFramework": "vue", + "creationTimestamp": 1792485949603, + "databaseMigration": "liquibase", + "databaseType": "sql", + "defaultCommand": "app", + "devDatabaseType": "postgresql", + "entities": [], + "jhipsterVersion": "9.3.0", + "jwtSecretKey": "MzY1ZDU0MDM3M2Y5YWRiMDYxYjBmYzZlOTMxMWFiNmYyMDEyZTUzZjYxOWFjNjhlNjU2NzcxYjkwY2Y0MGIwOGUyNTc5NWQyOGY3OGJkMjExZjhkYzU3ZGU4ZDc0ZmZiMTYwMzY0NGM4ZWZmODRhZTZjNzBlNjk5MWJkYjM5YjI=", + "languages": ["en"], + "messageBroker": "no", + "nativeLanguage": "en", + "packageName": "com.example.questionbank", + "prodDatabaseType": "postgresql", + "searchEngine": "no", + "serviceDiscoveryType": "no", + "websocket": "no", + "withAdminUi": true + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..8e7cec5 --- /dev/null +++ b/README.md @@ -0,0 +1,241 @@ +# questionBank + +This application was generated using JHipster 9.3.0, you can find documentation and help at [https://www.jhipster.tech/documentation-archive/v9.3.0](https://www.jhipster.tech/documentation-archive/v9.3.0). + +## Project Structure + +Node is required for generation and recommended for development. `package.json` is always generated for a better development experience with prettier, commit hooks, scripts and so on. + +In the project root, JHipster generates configuration files for tools like git, prettier, eslint, husky, and others that are well known and you can find references in the web. + +`/src/*` structure follows default Java structure. + +- `.yo-rc.json` - Yeoman configuration file + JHipster configuration is stored in this file at `generator-jhipster` key. You may find `generator-jhipster-*` for specific blueprints configuration. +- `.yo-resolve` (optional) - Yeoman conflict resolver + Allows to use a specific action when conflicts are found skipping prompts for files that matches a pattern. Each line should match `[pattern] [action]` with pattern been a [Minimatch](https://github.com/isaacs/minimatch#minimatch) pattern and action been one of skip (default if omitted) or force. Lines starting with `#` are considered comments and are ignored. +- `.jhipster/*.json` - JHipster entity configuration files + +- `npmw` - wrapper to use locally installed npm. + JHipster installs Node and npm locally using the build tool by default. This wrapper makes sure npm is installed locally and uses it avoiding some differences different versions can cause. By using `./npmw` instead of the traditional `npm` you can configure a Node-less environment to develop or test your application. +- `/src/main/docker` - Docker configurations for the application and services that the application depends on + +## Development + +The build system will install automatically the recommended version of Node and npm. + +We provide a wrapper to launch npm. +You will only need to run this command when dependencies change in [package.json](package.json). + +```bash +./npmw install +``` + +We use npm scripts and Vite as our build system. + +Run the following commands in two separate terminals to create a blissful development experience where your browser +auto-refreshes when files change on your hard drive. + +```bash +./npmw run backend:start +./npmw run start +``` + +Npm is also used to manage CSS and JavaScript dependencies used in this application. You can upgrade dependencies by +specifying a newer version in [package.json](package.json). You can also run `./npmw update` and `./npmw install` to manage dependencies. +Add the `help` flag on any command to see how you can use it. For example, `./npmw help update`. + +The `./npmw run` command will list all the scripts available to run for this project. + +### PWA Support + +JHipster ships with PWA (Progressive Web App) support, and it's turned off by default. One of the main components of a PWA is a service worker. + +The service worker initialization code is commented out by default. To enable it, uncomment the following code in `src/main/webapp/index.html`: + +```html + +``` + +Note: [Workbox](https://developer.chrome.com/docs/workbox) powers JHipster's service worker. It dynamically generates the `service-worker.js` file. + +### Managing dependencies + +For example, to add [Leaflet](https://leafletjs.com/) library as a runtime dependency of your application, you would run the following command: + +```bash +./npmw install --save --save-exact leaflet +``` + +To benefit from TypeScript type definitions from [DefinitelyTyped](https://definitelytyped.org/) repository in development, you would run the following command: + +```bash +./npmw install --save-dev --save-exact @types/leaflet +``` + +Then you would import the JS and CSS files specified in library's installation instructions so that [Vite][] knows about them: +Note: There are still a few other things remaining to do for Leaflet that we won't detail here. + +For further instructions on how to develop with JHipster, have a look at [Using JHipster in development](https://www.jhipster.tech/development/). + +## Building for production + +### Packaging as jar + +To build the final jar and optimize the questionBank application for production, run: + +```bash +./mvnw -Pprod clean verify +``` + +This will concatenate and minify the client CSS and JavaScript files. It will also modify `index.html` so it references these new files. +To ensure everything worked, run: + +```bash +java -jar target/*.jar +``` + +Then navigate to [http://localhost:8080](http://localhost:8080) in your browser. + +Refer to [Using JHipster in production][] for more details. + +### Packaging as war + +To package your application as a war in order to deploy it to an application server, run: + +```bash +./mvnw -Pprod,war clean verify +``` + +### JHipster Control Center + +JHipster Control Center can help you manage and control your application(s). You can start a local control center server (accessible on http://localhost:7419) with: + +```bash +docker compose -f src/main/docker/jhipster-control-center.yml up +``` + +## Testing + +### Spring Boot tests + +To launch your application's tests, run: + +```bash +./mvnw verify +``` + +### Client tests + +Unit tests are run by Vitest. They're located near components and can be run with: + +```bash +./npmw test +``` + +## Others + +### Code quality using Sonar + +Sonar is used to analyse code quality. You can start a local Sonar server (accessible on http://localhost:9001) with: + +```bash +docker compose -f src/main/docker/sonar.yml up -d +``` + +Note: we have turned off forced authentication redirect for UI in [src/main/docker/sonar.yml](src/main/docker/sonar.yml) for out of the box experience while trying out SonarQube, for real use cases turn it back on. + +You can run a Sonar analysis with using the [sonar-scanner](https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner) or by using the maven plugin. + +Then, run a Sonar analysis: + +```bash +./mvnw -Pprod clean verify sonar:sonar -Dsonar.login=admin -Dsonar.password=admin +``` + +If you need to re-run the Sonar phase, please be sure to specify at least the `initialize` phase since Sonar properties are loaded from the sonar-project.properties file. + +```bash +./mvnw initialize sonar:sonar -Dsonar.login=admin -Dsonar.password=admin +``` + +Additionally, Instead of passing `sonar.password` and `sonar.login` as CLI arguments, these parameters can be configured from [sonar-project.properties](sonar-project.properties) as shown below: + +```bash +sonar.login=admin +sonar.password=admin +``` + +For more information, refer to the [Code quality page][]. + +### Docker Compose support + +JHipster generates a number of Docker Compose configuration files in the [src/main/docker/](src/main/docker/) folder to launch required third party services. + +For example, to start required services in Docker containers, run: + +```bash +docker compose -f src/main/docker/services.yml up -d +``` + +To stop and remove the containers, run: + +```bash +docker compose -f src/main/docker/services.yml down +``` + +[Spring Docker Compose Integration](https://docs.spring.io/spring-boot/reference/features/dev-services.html) is enabled by default. It's possible to disable it in `application.yml`: + +```yaml +spring: + ... + docker: + compose: + enabled: false +``` + +You can also fully dockerize your application and all the services that it depends on. +To achieve this, first build a Docker image of your app by running: + +```bash +npm run java:docker +``` + +Or build an arm64 Docker image when using an arm64 processor OS, i.e., Apple Silicon chips (M*), running: + +```bash +npm run java:docker:arm64 +``` + +Then run: + +```bash +docker compose -f src/main/docker/app.yml up -d +``` + +For more information refer to [Docker and Docker-Compose](https://www.jhipster.tech/documentation-archive/v9.3.0/docker-compose/), this page also contains information on the Docker Compose sub-generator (`jhipster docker-compose`), which is able to generate Docker configurations for one or several JHipster applications. + +## Continuous Integration (optional) + +To configure CI for your project, run the ci-cd sub-generator (`jhipster ci-cd`), this will let you generate configuration files for a number of Continuous Integration systems. Consult the [Setting up Continuous Integration](https://www.jhipster.tech/documentation-archive/v9.3.0/setting-up-ci/) page for more information. + +## References + +- [JHipster Homepage and latest documentation](https://www.jhipster.tech/) +- [JHipster 9.3.0 archive](https://www.jhipster.tech/documentation-archive/v9.3.0) +- [Using JHipster in development](https://www.jhipster.tech/documentation-archive/v9.3.0/development/) +- [Using Docker and Docker-Compose](https://www.jhipster.tech/documentation-archive/v9.3.0/docker-compose) +- [Using JHipster in production](https://www.jhipster.tech/documentation-archive/v9.3.0/production/) +- [Running tests page](https://www.jhipster.tech/documentation-archive/v9.3.0/running-tests/) +- [Code quality page](https://www.jhipster.tech/documentation-archive/v9.3.0/code-quality/) +- [Setting up Continuous Integration](https://www.jhipster.tech/documentation-archive/v9.3.0/setting-up-ci/) +- [Node.js](https://nodejs.org/) +- [NPM](https://www.npmjs.com/) +- [Leaflet](https://leafletjs.com/) +- [DefinitelyTyped](https://definitelytyped.org/) diff --git a/checkstyle.xml b/checkstyle.xml new file mode 100644 index 0000000..71b9f90 --- /dev/null +++ b/checkstyle.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + diff --git a/eslint.config.ts b/eslint.config.ts new file mode 100644 index 0000000..cff5d6d --- /dev/null +++ b/eslint.config.ts @@ -0,0 +1,66 @@ +import js from '@eslint/js'; +import { defineConfig } from 'eslint/config'; +import prettier from 'eslint-plugin-prettier/recommended'; +import vue from 'eslint-plugin-vue'; +import globals from 'globals'; +import tseslint from 'typescript-eslint'; +// jhipster-needle-eslint-add-import - JHipster will add additional import here + +export default defineConfig( + { + languageOptions: { + globals: { + ...globals.node, + }, + }, + }, + { ignores: ['src/main/docker/'] }, + { ignores: ['target/classes/static/', 'target/'] }, + js.configs.recommended, + ...tseslint.configs.recommended.map(config => + config.name === 'typescript-eslint/base' ? config : { ...config, files: ['**/*.ts', '**/*.tsx', '**/*.mts', '**/*.cts'] }, + ), + { + files: ['**/*.{js,cjs,mjs}'], + rules: { + 'no-unused-vars': ['error', { argsIgnorePattern: '^_' }], + }, + }, + ...vue.configs['flat/recommended'], + { + files: ['**/*.vue'], + languageOptions: { + parserOptions: { parser: '@typescript-eslint/parser' }, + globals: { ...globals.browser }, + }, + }, + { + files: ['src/main/webapp/**/*.vue', 'src/main/webapp/**/*.ts'], + languageOptions: { + globals: { ...globals.browser }, + }, + rules: { + 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', + 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', + 'vue/multi-word-component-names': 'off', + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-unused-vars': 'off', + '@typescript-eslint/explicit-module-boundary-types': 'off', + '@typescript-eslint/no-empty-function': 'off', + '@typescript-eslint/ban-ts-comment': 'off', + '@typescript-eslint/no-var-requires': 'off', + '@typescript-eslint/consistent-type-imports': 'error', + 'vue/no-v-text-v-html-on-component': ['error', { allow: ['router-link', 'b-alert', 'b-badge', 'b-button', 'b-link'] }], + 'vue/no-reserved-component-names': 'off', + 'vue/attributes-order': 'off', + }, + }, + { + files: ['src/main/webapp/**/*.spec.ts'], + rules: { + '@typescript-eslint/no-empty-function': 'off', + }, + }, + // jhipster-needle-eslint-add-config - JHipster will add additional config here + prettier, +); diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..bd8896b --- /dev/null +++ b/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/npmw b/npmw new file mode 100644 index 0000000..bf57625 --- /dev/null +++ b/npmw @@ -0,0 +1,34 @@ +#!/bin/sh + +basedir=$(dirname "$0") + +if [ -f "$basedir/mvnw" ]; then + bindir="$basedir/target/node" + repodir="$basedir/target/node/node_modules" + installCommand="$basedir/mvnw --batch-mode -ntp -Pwebapp frontend:install-node-and-npm@install-node-and-npm" +else + echo "Using npm installed globally" + exec npm "$@" +fi + +NPM_EXE="$repodir/npm/bin/npm-cli.js" +NODE_EXE="$bindir/node" + +if [ ! -x "$NPM_EXE" ] || [ ! -x "$NODE_EXE" ]; then + $installCommand || true +fi + +if [ -x "$NODE_EXE" ]; then + echo "Using node installed locally $($NODE_EXE --version)" + PATH="$bindir:$PATH" +else + NODE_EXE='node' +fi + +if [ ! -x "$NPM_EXE" ]; then + echo "Local npm not found, using npm installed globally" + npm "$@" +else + echo "Using npm installed locally $($NODE_EXE $NPM_EXE --version)" + $NODE_EXE $NPM_EXE "$@" +fi diff --git a/npmw.cmd b/npmw.cmd new file mode 100644 index 0000000..847fcd1 --- /dev/null +++ b/npmw.cmd @@ -0,0 +1,24 @@ +@echo off + +setlocal + +set NPMW_DIR=%~dp0 + +set NODE_EXE=^"^" +set NODE_PATH=%NPMW_DIR%target\node\ +set NPM_EXE=^"%NPMW_DIR%target\node\npm.cmd^" +set INSTALL_NPM_COMMAND=^"%NPMW_DIR%mvnw.cmd^" -Pwebapp frontend:install-node-and-npm@install-node-and-npm + +if not exist %NPM_EXE% ( + call %INSTALL_NPM_COMMAND% +) + +if exist %NODE_EXE% ( + Rem execute local npm with local node, whilst adding local node location to the PATH for this CMD session + endlocal & echo "%PATH%"|find /i "%NODE_PATH%;">nul || set "PATH=%NODE_PATH%;%PATH%" & call %NODE_EXE% %NPM_EXE% %* +) else if exist %NPM_EXE% ( + Rem execute local npm, whilst adding local npm location to the PATH for this CMD session + endlocal & echo "%PATH%"|find /i "%NODE_PATH%;">nul || set "PATH=%NODE_PATH%;%PATH%" & call %NPM_EXE% %* +) else ( + call npm %* +) diff --git a/package.json b/package.json new file mode 100644 index 0000000..ea65749 --- /dev/null +++ b/package.json @@ -0,0 +1,141 @@ +{ + "name": "question-bank", + "version": "0.0.0", + "private": true, + "description": "Description for Question Bank", + "license": "UNLICENSED", + "type": "module", + "scripts": { + "app:start": "./mvnw -ntp --batch-mode", + "app:up": "docker compose -f src/main/docker/app.yml up --wait", + "backend:build-cache": "./mvnw dependency:go-offline -ntp", + "backend:debug": "./mvnw -Dspring-boot.run.jvmArguments=\"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000\"", + "backend:doc:test": "./mvnw -ntp javadoc:javadoc --batch-mode", + "backend:info": "./mvnw --version", + "backend:nohttp:test": "./mvnw -ntp checkstyle:check --batch-mode", + "backend:start": "./mvnw -Dskip.installnodenpm -Dskip.npm -ntp --batch-mode", + "backend:unit:test": "./mvnw -ntp -Dskip.installnodenpm -Dskip.npm verify --batch-mode -Dlogging.level.ROOT=OFF -Dlogging.level.tech.jhipster=OFF -Dlogging.level.com.example.questionbank=OFF -Dlogging.level.org.springframework=OFF -Dlogging.level.org.springframework.web=OFF -Dlogging.level.org.springframework.security=OFF", + "build": "npm run webapp:prod --", + "build-watch": "concurrently 'npm run webapp:build:dev -- --watch' npm:backend:start", + "ci:backend:test": "npm run backend:info && npm run backend:doc:test && npm run backend:nohttp:test && npm run backend:unit:test -- -P$npm_package_config_default_environment", + "ci:e2e:package": "npm run java:$npm_package_config_packaging:$npm_package_config_default_environment -- -Pe2e -Denforcer.skip=true", + "ci:e2e:prepare": "npm run ci:e2e:prepare:docker", + "ci:e2e:prepare:docker": "npm run services:up --if-present && docker ps -a", + "preci:e2e:server:start": "npm run services:db:await --if-present && npm run services:others:await --if-present", + "ci:e2e:server:start": "java -jar target/e2e.$npm_package_config_packaging --spring.profiles.active=e2e,secret-samples,$npm_package_config_default_environment -Dlogging.level.ROOT=OFF -Dlogging.level.tech.jhipster=OFF -Dlogging.level.com.example.questionbank=OFF -Dlogging.level.org.springframework=OFF -Dlogging.level.org.springframework.web=OFF -Dlogging.level.org.springframework.security=OFF --logging.level.org.springframework.web=ERROR", + "ci:e2e:teardown": "npm run ci:e2e:teardown:docker --if-present", + "ci:e2e:teardown:docker": "docker compose -f src/main/docker/services.yml down -v && docker ps -a", + "ci:frontend:build": "npm run webapp:build:$npm_package_config_default_environment", + "ci:frontend:test": "npm run ci:frontend:build && npm test", + "ci:server:await": "echo \"Waiting for server at port $npm_package_config_backend_port to start\" && wait-on -t 180000 http-get://127.0.0.1:$npm_package_config_backend_port/management/health && echo \"Server at port $npm_package_config_backend_port started\"", + "clean-www": "rimraf target/classes/static/", + "cleanup": "rimraf target/", + "docker:db:down": "docker compose -f src/main/docker/postgresql.yml down -v", + "docker:db:up": "docker compose -f src/main/docker/postgresql.yml up --wait", + "java:docker": "./mvnw -ntp verify -DskipTests -Pprod jib:dockerBuild", + "java:docker:arm64": "npm run java:docker -- -Djib-maven-plugin.architecture=arm64", + "java:docker:dev": "npm run java:docker -- -Pdev,webapp", + "java:docker:prod": "npm run java:docker -- -Pprod", + "java:jar": "./mvnw -ntp verify -DskipTests --batch-mode", + "java:jar:dev": "npm run java:jar -- -Pdev,webapp", + "java:jar:prod": "npm run java:jar -- -Pprod", + "java:war": "./mvnw -ntp verify -DskipTests --batch-mode -Pwar", + "java:war:dev": "npm run java:war -- -Pdev,webapp", + "java:war:prod": "npm run java:war -- -Pprod", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "prepare": "husky", + "prettier:check": "prettier --check \"{,.blueprint/**/,src/**/}*.{md,json,yml,js,cjs,mjs,ts,cts,mts,java,html,vue,css,scss}\"", + "prettier:format": "prettier --write \"{,.blueprint/**/,src/**/}*.{md,json,yml,js,cjs,mjs,ts,cts,mts,java,html,vue,css,scss}\"", + "serve": "npm run start --", + "services:up": "docker compose -f src/main/docker/services.yml up --wait", + "start": "npm run webapp:dev --", + "start-tls": "npm run webapp:dev -- --env.tls", + "pretest": "npm run lint", + "test": "npm run vitest-run --", + "test:watch": "npm run vitest", + "vite-build": "vite build", + "vite-serve": "vite", + "vitest": "vitest", + "vitest-run": "vitest --run --coverage", + "watch": "concurrently npm:start npm:backend:start", + "webapp:build": "npm run clean-www && npm run webapp:build:dev --", + "webapp:build:dev": "npm run vite-build", + "webapp:build:prod": "npm run vite-build", + "webapp:dev": "npm run vite-serve", + "webapp:prod": "npm run clean-www && npm run webapp:build:prod --", + "webapp:serve": "npm run vite-serve", + "webapp:test": "npm run test --" + }, + "config": { + "backend_port": 8080, + "default_environment": "prod", + "packaging": "jar" + }, + "browserslist": [ + "> 1%", + "last 2 versions", + "not ie <= 8" + ], + "dependencies": { + "@fortawesome/fontawesome-svg-core": "7.3.1", + "@fortawesome/free-solid-svg-icons": "7.3.1", + "@fortawesome/vue-fontawesome": "3.3.3", + "@vuelidate/core": "2.0.3", + "@vuelidate/validators": "2.0.4", + "@vueuse/core": "14.4.0", + "axios": "1.19.0", + "bootstrap": "5.3.7", + "bootstrap-vue-next": "1.0.1", + "dayjs": "1.11.23", + "deepmerge": "4.3.1", + "pinia": "4.0.3", + "vue": "3.5.41", + "vue-i18n": "11.4.9", + "vue-router": "5.2.0" + }, + "devDependencies": { + "@eslint/js": "10.0.1", + "@pinia/testing": "2.0.1", + "@tsconfig/node18": "18.2.7", + "@types/node": "22.20.1", + "@vitejs/plugin-vue": "6.0.8", + "@vitest/coverage-v8": "4.1.11", + "@vue/test-utils": "2.4.11", + "@vue/tsconfig": "0.9.1", + "autoprefixer": "10.5.4", + "axios-mock-adapter": "2.1.0", + "concurrently": "10.0.5", + "eslint": "10.9.1", + "eslint-config-prettier": "10.1.8", + "eslint-plugin-prettier": "5.5.6", + "eslint-plugin-vue": "10.10.0", + "generator-jhipster": "9.3.0", + "globals": "17.11.0", + "happy-dom": "20.11.6", + "husky": "9.1.7", + "jiti": "2.7.0", + "lint-staged": "17.3.0", + "postcss-import": "17.0.0", + "postcss-url": "10.1.4", + "prettier": "3.9.6", + "prettier-plugin-java": "2.10.3", + "prettier-plugin-packagejson": "3.0.2", + "rimraf": "6.1.3", + "sass": "1.70.0", + "swagger-ui-dist": "5.32.14", + "typescript": "6.0.3", + "typescript-eslint": "8.68.0", + "vite": "8.2.2", + "vite-plugin-static-copy": "4.1.1", + "vitest": "4.1.11", + "vitest-sonar-reporter": "3.0.0", + "wait-on": "9.1.0" + }, + "engines": { + "node": ">=24.20.0" + }, + "cacheDirectories": [ + "node_modules" + ] +} diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..bbbb0f5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,1143 @@ + + + 4.0.0 + + com.example.questionbank + question-bank + 0.0.1-SNAPSHOT + jar + Question Bank + Description for Question Bank + + org.springframework.boot + spring-boot-starter-parent + 4.1.1 + + + + + + + 3.2.5 + 21 + v24.20.0 + 12.0.2 + UTF-8 + UTF-8 + yyyyMMddHHmmss + ${java.version} + ${java.version} + com.example.questionbank.QuestionBankApp + -Xmx1G + jdt_apt + false + ${project.parent.version} + 1.5.0 + 14.0.0 + 1.11 + 2.0.2 + 0.8.15 + 9.3.0 + amd64 + eclipse-temurin:25-jre-noble + 3.5.2 + 1.0.0 + + + + 1.6.3 + 3.2.0 + 3.6.0 + 3.5.0 + 0.0.11 + + + + + + 1.3.0 + @ + 5.7.0.6970 + 3.10.0 + dev + 3.1.0 + + + + + tech.jhipster + jhipster-framework + ${jhipster-framework.version} + + + org.springframework.boot + spring-boot-configuration-processor + provided + + + org.springframework.boot + spring-boot-h2console + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-aspectj + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-jackson + + + org.springframework.boot + spring-boot-starter-jackson-test + test + + + org.springframework.boot + spring-boot-starter-liquibase + + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-security-test + test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-tomcat + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + org.springframework.boot + spring-boot-test + test + + + org.springframework.boot + spring-boot-testcontainers + test + + + org.springframework.security + spring-security-data + + + org.springframework.security + spring-security-test + test + + + org.springdoc + springdoc-openapi-starter-webmvc-api + ${springdoc-openapi-starter-webmvc-api.version} + + + com.tngtech.archunit + archunit-junit5-api + ${archunit-junit5.version} + test + + + org.slf4j + slf4j-api + + + + + com.tngtech.archunit + archunit-junit5-engine + ${archunit-junit5.version} + test + + + org.slf4j + slf4j-api + + + + + com.zaxxer + HikariCP + + + io.micrometer + micrometer-registry-prometheus + + + org.apache.commons + commons-lang3 + + + org.glassfish.jaxb + jaxb-runtime + provided + + + org.hibernate.orm + hibernate-core + + + org.hibernate.orm + hibernate-processor + provided + + + org.hibernate.validator + hibernate-validator + + + org.liquibase + liquibase-core + ${liquibase.version} + + + org.mapstruct + mapstruct + ${mapstruct.version} + + + org.postgresql + postgresql + + + org.testcontainers + testcontainers + test + + + org.testcontainers + testcontainers-jdbc + test + + + org.testcontainers + testcontainers-junit-jupiter + test + + + org.testcontainers + testcontainers-postgresql + test + + + tools.jackson.datatype + jackson-datatype-hibernate7 + + + tools.jackson.module + jackson-module-jaxb-annotations + + + + + spring-boot:run + + + ${basedir}/src/main/resources/ + true + + config/**/*.yml + + + + ${basedir}/src/main/resources/ + + config/**/*.yml + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-enforcer-plugin + + + org.apache.maven.plugins + maven-failsafe-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + + + org.apache.maven.plugins + maven-resources-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + com.diffplug.spotless + spotless-maven-plugin + + + com.google.cloud.tools + jib-maven-plugin + + + org.codehaus.mojo + properties-maven-plugin + + + org.gaul + modernizer-maven-plugin + + + org.jacoco + jacoco-maven-plugin + + + org.sonarsource.scanner.maven + sonar-maven-plugin + + + + + + org.apache.maven.plugins + maven-antrun-plugin + ${maven-antrun-plugin.version} + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven-checkstyle-plugin.version} + + + com.puppycrawl.tools + checkstyle + ${checkstyle.version} + + + io.spring.nohttp + nohttp-checkstyle + ${nohttp-checkstyle.version} + + + + checkstyle.xml + pom.xml,README.md + .git/**/*,target/**/*,node_modules/**/* + ./ + + + + + check + + + + + + org.apache.maven.plugins + maven-clean-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + true + + + org.springframework.boot + spring-boot-configuration-processor + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + + + org.hibernate.orm + hibernate-processor + + + org.glassfish.jaxb + jaxb-runtime + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-versions + + enforce + + + + enforce-dependencyConvergence + + + + + false + + + enforce + + + + + + + You are running an older version of Maven. JHipster requires at least Maven ${maven.version} + [${maven.version},) + + + You are running an incompatible version of Java. JHipster supports JDK 21 to 25. + [21,22),[25,26) + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + ${project.build.outputDirectory} + alphabetical + + **/*IT* + **/*IntTest* + + @{argLine} -Dspring.profiles.active=${profile.test} + + + + integration-test + + integration-test + + + + verify + + verify + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + + ${maven.compiler.source} + + + + org.apache.maven.plugins + maven-surefire-plugin + + + alphabetical + + **/*IT* + **/*IntTest* + + + src/test/resources/logback.xml + + + + + org.apache.maven.plugins + maven-war-plugin + + + default-war + + war + + package + + + + WEB-INF/**,META-INF/** + false + target/classes/static/ + + + src/main/webapp/ + + WEB-INF/** + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + build-info + + build-info + + + + repackage + + repackage + + + + + ${start-class} + + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless-maven-plugin.version} + + + + + + + + spotless + process-sources + + apply + + + + + + com.github.eirslett + frontend-maven-plugin + ${frontend-maven-plugin.version} + + target + ${node.version} + ${npm.version} + + + + com.google.cloud.tools + jib-maven-plugin + ${jib-maven-plugin.version} + + + ${jib-maven-plugin.image} + + + ${jib-maven-plugin.architecture} + linux + + + + + questionbank:latest + + + + bash + + /entrypoint.sh + + + 8080 + + + ALWAYS + 0 + + USE_CURRENT_TIMESTAMP + 1000 + + + src/main/docker/jib + + + /entrypoint.sh + 755 + + + + + + com.google.cloud.tools.jib.maven.extension.springboot.JibSpringBootExtension + + + + + + com.google.cloud.tools + jib-spring-boot-extension-maven + 0.1.0 + + + + + io.github.git-commit-id + git-commit-id-maven-plugin + + + + revision + + + + + false + false + true + + ^git.commit.id.abbrev$ + ^git.commit.id.describe$ + ^git.branch$ + + + + + net.nicoulaj.maven.plugins + checksum-maven-plugin + ${checksum-maven-plugin.version} + + + org.codehaus.mojo + properties-maven-plugin + ${properties-maven-plugin.version} + + + initialize + + read-project-properties + + + + sonar-project.properties + + + + + + + org.gaul + modernizer-maven-plugin + ${modernizer-maven-plugin.version} + + + modernizer + package + + modernizer + + + + + ${java.version} + + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + + pre-unit-tests + + prepare-agent + + + + + post-unit-test + test + + report + + + + pre-integration-tests + + prepare-agent-integration + + + + + post-integration-tests + post-integration-test + + report-integration + + + + + + org.liquibase + liquibase-maven-plugin + ${liquibase.version} + + config/liquibase/master.xml + ${project.basedir}/src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml + org.postgresql.Driver + ${liquibase-plugin.url} + + ${liquibase-plugin.username} + ${liquibase-plugin.password} + hibernate:spring:com.example.questionbank.domain?dialect=org.hibernate.dialect.PostgreSQLDialect&hibernate.physical_naming_strategy=org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.hibernate.SpringImplicitNamingStrategy + true + !test + + + + org.liquibase + liquibase-core + ${liquibase.version} + + + org.liquibase.ext + liquibase-hibernate6 + ${liquibase.version} + + + jakarta.persistence + jakarta.persistence-api + ${jakarta-persistence.version} + + + jakarta.validation + jakarta.validation-api + ${jakarta-validation.version} + + + org.jboss.logging + jboss-logging + ${jboss-logging.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + ${sonar-maven-plugin.version} + + + + + + + + api-docs + + ,api-docs + + + + dev + + true + + + + + jdbc:postgresql://localhost:5432/questionBank + questionBank + test,testdev + dev${profile.tls}${profile.no-liquibase} + + + + org.springframework.boot + spring-boot-devtools + true + + + + + docker-compose + + true + + + + org.springframework.boot + spring-boot-docker-compose + true + + + + + + eclipse + + + m2e.version + + + + + + + + org.eclipse.m2e + lifecycle-mapping + ${lifecycle-mapping.version} + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + prepare-agent + + + + + + + + + com.github.eirslett + frontend-maven-plugin + ${frontend-maven-plugin.version} + + install-node-and-npm + npm + + + + + + + + + + + + + + + + + IDE + + + org.hibernate.orm + hibernate-processor + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + + + + + no-liquibase + + ,no-liquibase + + + + prod + + + + jdbc:postgresql://localhost:5432/questionBank + questionBank + test,testprod + prod${profile.api-docs}${profile.tls}${profile.e2e}${profile.no-liquibase} + + + + + org.apache.maven.plugins + maven-clean-plugin + + + + target/classes/static/ + + + + + + io.github.git-commit-id + git-commit-id-maven-plugin + + + com.github.eirslett + frontend-maven-plugin + + + install-node-and-npm + + install-node-and-npm + + + + npm install + + npm + + + + webapp build test + + npm + + test + + run webapp:test + false + + + + webapp build prod + + npm + + generate-resources + + run webapp:prod + + ${project.version} + + false + + + + + + + + + tls + + ,tls + + + + war + + + + org.apache.maven.plugins + maven-war-plugin + + + + + + webapp + + true + + + + dev${profile.no-liquibase} + + + + + net.nicoulaj.maven.plugins + checksum-maven-plugin + + + create-pre-compiled-webapp-checksum + + files + + generate-resources + + + create-compiled-webapp-checksum + + files + + compile + + checksums.csv.old + + + + + + + ${project.basedir} + + .postcssrc.js + package-lock.json + package.json + src/main/webapp/**/*.* + target/classes/static/**/*.* + tsconfig.app.json + tsconfig.json + vite.config.ts + + + **/app/**/service-worker.js + **/app/**/vendor.css + + + + false + false + false + + SHA-1 + + true + true + + + + org.apache.maven.plugins + maven-antrun-plugin + + + eval-frontend-checksum + generate-resources + + run + + + + + + + + + + + + true + + + + + + com.github.eirslett + frontend-maven-plugin + + + install-node-and-npm + + install-node-and-npm + + + + npm install + + npm + + + + webapp build dev + + npm + + generate-resources + + run webapp:build + + ${project.version} + + false + + + + + + + + + diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 0000000..4965838 --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,55 @@ +sonar.projectKey = questionBank +sonar.projectName = questionBank generated by jhipster + +# Typescript tests files must be inside sources and tests, otherwise `INFO: Test execution data ignored for 80 unknown +# files, including:` is shown. +sonar.sources = src +sonar.tests = src +sonar.host.url = http://localhost:9001 +sonar.sourceEncoding = UTF-8 + +sonar.test.inclusions = src/test/**/*.*, src/main/webapp/app/**/*.spec.ts +sonar.junit.reportPaths = target/surefire-reports,target/failsafe-reports +sonar.java.codeCoveragePlugin = jacoco +sonar.coverage.jacoco.xmlReportPaths = target/site/**/jacoco*.xml +sonar.exclusions = src/main/webapp/content/**/*.*, src/main/webapp/i18n/*.ts, target/classes/static/**/*.* +sonar.javascript.lcov.reportPaths = target/test-results/lcov.info +sonar.testExecutionReportPaths = target/test-results/jest/TESTS-results-sonar.xml + +sonar.issue.ignore.multicriteria = S7027-domain, S3437, S7027-dto, UndocumentedApi, S125, S4502, S4684, S5145, S6437, S6437-2, S6418 +# Rule https://rules.sonarsource.com/java/RSPEC-7027 is ignored for entities +sonar.issue.ignore.multicriteria.S7027-domain.resourceKey = src/main/java/com/example/questionbank/domain/**/* +sonar.issue.ignore.multicriteria.S7027-domain.ruleKey = javaarchitecture:S7027 +# Rule https://rules.sonarsource.com/java/RSPEC-3437 is ignored +sonar.issue.ignore.multicriteria.S3437.resourceKey = src/main/java/com/example/questionbank/**/* +sonar.issue.ignore.multicriteria.S3437.ruleKey = squid:S3437 +# Rule https://rules.sonarsource.com/java/RSPEC-7027 is ignored for dtos +sonar.issue.ignore.multicriteria.S7027-dto.resourceKey = src/main/java/com/example/questionbank/service/dto/**/* +sonar.issue.ignore.multicriteria.S7027-dto.ruleKey = javaarchitecture:S7027 +# Rule https://rules.sonarsource.com/java/RSPEC-1176 is ignored, as we want to follow "clean code" guidelines and +# classes, methods and arguments names should be self-explanatory +sonar.issue.ignore.multicriteria.UndocumentedApi.resourceKey = src/main/java/com/example/questionbank/**/* +sonar.issue.ignore.multicriteria.UndocumentedApi.ruleKey = squid:UndocumentedApi +# Rule https://rules.sonarsource.com/xml/RSPEC-125 is ignored, we provide commented examples +sonar.issue.ignore.multicriteria.S125.resourceKey = src/main/resources/logback-spring.xml +sonar.issue.ignore.multicriteria.S125.ruleKey = xml:S125 +# Rule https://rules.sonarsource.com/java/RSPEC-4502 is ignored, as for JWT tokens we are not subject to CSRF attack +sonar.issue.ignore.multicriteria.S4502.resourceKey = src/main/java/com/example/questionbank/config/SecurityConfiguration.java +sonar.issue.ignore.multicriteria.S4502.ruleKey = java:S4502 +# Rule https://rules.sonarsource.com/java/RSPEC-4684 +sonar.issue.ignore.multicriteria.S4684.resourceKey = src/main/java/com/example/questionbank/web/rest/**/* +sonar.issue.ignore.multicriteria.S4684.ruleKey = java:S4684 +# Rule https://rules.sonarsource.com/java/RSPEC-5145 is ignored, as we use log filter to format log messages +sonar.issue.ignore.multicriteria.S5145.resourceKey = src/main/java/com/example/questionbank/**/* +sonar.issue.ignore.multicriteria.S5145.ruleKey = javasecurity:S5145 +# Rule https://rules.sonarsource.com/java/RSPEC-6437 is ignored, hardcoded passwords are provided for development +# purposes +sonar.issue.ignore.multicriteria.S6437.resourceKey = src/main/resources/config/application-secret-samples.yml +sonar.issue.ignore.multicriteria.S6437.ruleKey = java:S6437 +# Rule https://rules.sonarsource.com/java/RSPEC-6437 is ignored, hardcoded passwords are provided for development +# purposes +sonar.issue.ignore.multicriteria.S6437-2.resourceKey = src/main/resources/config/application-tls.yml +sonar.issue.ignore.multicriteria.S6437-2.ruleKey = java:S6437 +# Rule yaml:S6418 is ignored, hardcoded passwords are provided for development and testing purposes +sonar.issue.ignore.multicriteria.S6418.resourceKey = src/main/resources/config/application-secret-samples.yml +sonar.issue.ignore.multicriteria.S6418.ruleKey = yaml:S6418 diff --git a/src/main/docker/app.yml b/src/main/docker/app.yml new file mode 100644 index 0000000..8a116ed --- /dev/null +++ b/src/main/docker/app.yml @@ -0,0 +1,31 @@ +# This configuration is intended for development purpose, it's **your** responsibility to harden it for production +name: questionbank +services: + app: + image: questionbank + environment: + - _JAVA_OPTIONS=-Xmx512m -Xms256m + - SPRING_PROFILES_ACTIVE=prod,api-docs,secret-samples + - MANAGEMENT_PROMETHEUS_METRICS_EXPORT_ENABLED=true + - SPRING_DATASOURCE_URL=jdbc:postgresql://postgresql:5432/questionBank + - SPRING_DATASOURCE_USERNAME=questionBank + - SPRING_DATASOURCE_PASSWORD= + - SPRING_LIQUIBASE_URL=jdbc:postgresql://postgresql:5432/questionBank + ports: + - 127.0.0.1:8080:8080 + healthcheck: + test: + - CMD-SHELL + - "bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080; printf \"GET + /management/health HTTP/1.0\\r\\nHost: localhost\\r\\n\\r\\n\" >&3; + grep -q \"\\\"status\\\":\\\"UP\\\"\" <&3'" + interval: 5s + timeout: 5s + retries: 40 + depends_on: + postgresql: + condition: service_healthy + postgresql: + extends: + file: ./postgresql.yml + service: postgresql diff --git a/src/main/docker/grafana/provisioning/dashboards/JVM.json b/src/main/docker/grafana/provisioning/dashboards/JVM.json new file mode 100644 index 0000000..d132b00 --- /dev/null +++ b/src/main/docker/grafana/provisioning/dashboards/JVM.json @@ -0,0 +1,3778 @@ +{ + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": "-- Grafana --", + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "limit": 100, + "name": "Annotations & Alerts", + "showIn": 0, + "type": "dashboard" + }, + { + "datasource": "Prometheus", + "enable": true, + "expr": "resets(process_uptime_seconds{application=\"$application\", instance=\"$instance\"}[1m]) > 0", + "iconColor": "rgba(255, 96, 96, 1)", + "name": "Restart Detection", + "showIn": 0, + "step": "1m", + "tagKeys": "restart-tag", + "textFormat": "uptime reset", + "titleFormat": "Restart" + } + ] + }, + "description": "Dashboard for Micrometer instrumented applications (Java, Spring Boot, Micronaut)", + "editable": true, + "gnetId": 4701, + "graphTooltip": 1, + "iteration": 1553765841423, + "links": [], + "panels": [ + { + "content": "\n# Acknowledgments\n\nThank you to [Michael Weirauch](https://twitter.com/emwexx) for creating this dashboard: see original JVM (Micrometer) dashboard at [https://grafana.com/dashboards/4701](https://grafana.com/dashboards/4701)\n\n\n\n", + "gridPos": { + "h": 3, + "w": 24, + "x": 0, + "y": 0 + }, + "id": 141, + "links": [], + "mode": "markdown", + "timeFrom": null, + "timeShift": null, + "title": "Acknowledgments", + "type": "text" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 3 + }, + "id": 125, + "panels": [], + "repeat": null, + "title": "Quick Facts", + "type": "row" + }, + { + "cacheTimeout": null, + "colorBackground": false, + "colorValue": true, + "colors": ["rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)"], + "datasource": "Prometheus", + "decimals": 1, + "editable": true, + "error": false, + "format": "s", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "gridPos": { + "h": 3, + "w": 6, + "x": 0, + "y": 4 + }, + "height": "", + "id": 63, + "interval": null, + "links": [], + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "maxDataPoints": 100, + "nullPointMode": "connected", + "nullText": null, + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "70%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": false + }, + "tableColumn": "", + "targets": [ + { + "expr": "process_uptime_seconds{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "", + "metric": "", + "refId": "A", + "step": 14400 + } + ], + "thresholds": "", + "title": "Uptime", + "type": "singlestat", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "current" + }, + { + "cacheTimeout": null, + "colorBackground": false, + "colorValue": true, + "colors": ["rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)"], + "datasource": "Prometheus", + "decimals": null, + "editable": true, + "error": false, + "format": "dateTimeAsIso", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "gridPos": { + "h": 3, + "w": 6, + "x": 6, + "y": 4 + }, + "height": "", + "id": 92, + "interval": null, + "links": [], + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "maxDataPoints": 100, + "nullPointMode": "connected", + "nullText": null, + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "70%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": false + }, + "tableColumn": "", + "targets": [ + { + "expr": "process_start_time_seconds{application=\"$application\", instance=\"$instance\"}*1000", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "", + "metric": "", + "refId": "A", + "step": 14400 + } + ], + "thresholds": "", + "title": "Start time", + "type": "singlestat", + "valueFontSize": "70%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "current" + }, + { + "cacheTimeout": null, + "colorBackground": false, + "colorValue": true, + "colors": ["rgba(50, 172, 45, 0.97)", "rgba(237, 129, 40, 0.89)", "rgba(245, 54, 54, 0.9)"], + "datasource": "Prometheus", + "decimals": 2, + "editable": true, + "error": false, + "format": "percent", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "gridPos": { + "h": 3, + "w": 6, + "x": 12, + "y": 4 + }, + "id": 65, + "interval": null, + "links": [], + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "maxDataPoints": 100, + "nullPointMode": "connected", + "nullText": null, + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "70%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": false + }, + "tableColumn": "", + "targets": [ + { + "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})*100/sum(jvm_memory_max_bytes{application=\"$application\",instance=\"$instance\", area=\"heap\"})", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "", + "refId": "A", + "step": 14400 + } + ], + "thresholds": "70,90", + "title": "Heap used", + "type": "singlestat", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "current" + }, + { + "cacheTimeout": null, + "colorBackground": false, + "colorValue": true, + "colors": ["rgba(50, 172, 45, 0.97)", "rgba(237, 129, 40, 0.89)", "rgba(245, 54, 54, 0.9)"], + "datasource": "Prometheus", + "decimals": 2, + "editable": true, + "error": false, + "format": "percent", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "gridPos": { + "h": 3, + "w": 6, + "x": 18, + "y": 4 + }, + "id": 75, + "interval": null, + "links": [], + "mappingType": 2, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "maxDataPoints": 100, + "nullPointMode": "connected", + "nullText": null, + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "70%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + }, + { + "from": "-99999999999999999999999999999999", + "text": "N/A", + "to": "0" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": false + }, + "tableColumn": "", + "targets": [ + { + "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})*100/sum(jvm_memory_max_bytes{application=\"$application\",instance=\"$instance\", area=\"nonheap\"})", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "", + "refId": "A", + "step": 14400 + } + ], + "thresholds": "70,90", + "title": "Non-Heap used", + "type": "singlestat", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + }, + { + "op": "=", + "text": "x", + "value": "" + } + ], + "valueName": "current" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 7 + }, + "id": 126, + "panels": [], + "repeat": null, + "title": "I/O Overview", + "type": "row" + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "fill": 1, + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 8 + }, + "id": 111, + "legend": { + "avg": false, + "current": true, + "max": false, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "sum(rate(http_server_requests_seconds_count{application=\"$application\", instance=\"$instance\"}[1m]))", + "format": "time_series", + "intervalFactor": 1, + "legendFormat": "HTTP", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Rate", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "decimals": null, + "format": "ops", + "label": null, + "logBase": 1, + "max": null, + "min": "0", + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": { + "HTTP": "#890f02", + "HTTP - 5xx": "#bf1b00" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "fill": 1, + "gridPos": { + "h": 7, + "w": 8, + "x": 8, + "y": 8 + }, + "id": 112, + "legend": { + "avg": false, + "current": true, + "max": false, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "sum(rate(http_server_requests_seconds_count{application=\"$application\", instance=\"$instance\", status=~\"5..\"}[1m]))", + "format": "time_series", + "intervalFactor": 1, + "legendFormat": "HTTP - 5xx", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Errors", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "decimals": null, + "format": "ops", + "label": null, + "logBase": 1, + "max": null, + "min": "0", + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "fill": 1, + "gridPos": { + "h": 7, + "w": 8, + "x": 16, + "y": 8 + }, + "id": 113, + "legend": { + "avg": false, + "current": true, + "max": false, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "sum(rate(http_server_requests_seconds_sum{application=\"$application\", instance=\"$instance\", status!~\"5..\"}[1m]))/sum(rate(http_server_requests_seconds_count{application=\"$application\", instance=\"$instance\", status!~\"5..\"}[1m]))", + "format": "time_series", + "hide": false, + "intervalFactor": 1, + "legendFormat": "HTTP - AVG", + "refId": "A" + }, + { + "expr": "max(http_server_requests_seconds_max{application=\"$application\", instance=\"$instance\", status!~\"5..\"})", + "format": "time_series", + "hide": false, + "intervalFactor": 1, + "legendFormat": "HTTP - MAX", + "refId": "B" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Duration", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "label": null, + "logBase": 1, + "max": null, + "min": "0", + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 15 + }, + "id": 127, + "panels": [], + "repeat": null, + "title": "JVM Memory", + "type": "row" + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 16 + }, + "id": 24, + "legend": { + "avg": false, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 2400 + }, + { + "expr": "sum(jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "committed", + "refId": "B", + "step": 2400 + }, + { + "expr": "sum(jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "max", + "refId": "C", + "step": 2400 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "JVM Heap", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["mbytes", "short"], + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 8, + "y": 16 + }, + "id": 25, + "legend": { + "avg": false, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})", + "format": "time_series", + "interval": "", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 2400 + }, + { + "expr": "sum(jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "committed", + "refId": "B", + "step": 2400 + }, + { + "expr": "sum(jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "max", + "refId": "C", + "step": 2400 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "JVM Non-Heap", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["mbytes", "short"], + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 16, + "y": 16 + }, + "id": 26, + "legend": { + "alignAsTable": false, + "avg": false, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\"})", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 2400 + }, + { + "expr": "sum(jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\"})", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "committed", + "refId": "B", + "step": 2400 + }, + { + "expr": "sum(jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\"})", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "max", + "refId": "C", + "step": 2400 + }, + { + "expr": "process_memory_vss_bytes{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "hide": true, + "intervalFactor": 2, + "legendFormat": "vss", + "metric": "", + "refId": "D", + "step": 2400 + }, + { + "expr": "process_memory_rss_bytes{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "rss", + "refId": "E", + "step": 2400 + }, + { + "expr": "process_memory_pss_bytes{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "pss", + "refId": "F", + "step": 2400 + }, + { + "expr": "process_memory_swap_bytes{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "swap", + "refId": "G", + "step": 2400 + }, + { + "expr": "process_memory_swappss_bytes{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "swappss", + "refId": "H", + "step": 2400 + }, + { + "expr": "process_memory_pss_bytes{application=\"$application\", instance=\"$instance\"} + process_memory_swap_bytes{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "phys (pss+swap)", + "refId": "I", + "step": 2400 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "JVM Total", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["mbytes", "short"], + "yaxes": [ + { + "format": "bytes", + "label": "", + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 23 + }, + "id": 128, + "panels": [], + "repeat": null, + "title": "JVM Misc", + "type": "row" + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 0, + "y": 24 + }, + "id": 106, + "legend": { + "avg": false, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "system_cpu_usage{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "hide": false, + "intervalFactor": 1, + "legendFormat": "system", + "metric": "", + "refId": "A", + "step": 2400 + }, + { + "expr": "process_cpu_usage{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "hide": false, + "intervalFactor": 1, + "legendFormat": "process", + "refId": "B" + }, + { + "expr": "avg_over_time(process_cpu_usage{application=\"$application\", instance=\"$instance\"}[1h])", + "format": "time_series", + "hide": false, + "intervalFactor": 1, + "legendFormat": "process-1h", + "refId": "C" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "CPU", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["short", "short"], + "yaxes": [ + { + "decimals": 1, + "format": "percentunit", + "label": "", + "logBase": 1, + "max": "1", + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 6, + "y": 24 + }, + "id": 93, + "legend": { + "avg": false, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "system_load_average_1m{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "system-1m", + "metric": "", + "refId": "A", + "step": 2400 + }, + { + "expr": "", + "format": "time_series", + "intervalFactor": 2, + "refId": "B" + }, + { + "expr": "system_cpu_count{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "cpu", + "refId": "C" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Load", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["short", "short"], + "yaxes": [ + { + "decimals": 1, + "format": "short", + "label": "", + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 12, + "y": 24 + }, + "id": 32, + "legend": { + "avg": false, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_threads_live{application=\"$application\", instance=\"$instance\"} or jvm_threads_live_threads{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "live", + "metric": "", + "refId": "A", + "step": 2400 + }, + { + "expr": "jvm_threads_daemon{application=\"$application\", instance=\"$instance\"} or jvm_threads_daemon_threads{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "daemon", + "metric": "", + "refId": "B", + "step": 2400 + }, + { + "expr": "jvm_threads_peak{application=\"$application\", instance=\"$instance\"} or jvm_threads_peak_threads{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "peak", + "refId": "C", + "step": 2400 + }, + { + "expr": "process_threads{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "interval": "", + "intervalFactor": 2, + "legendFormat": "process", + "refId": "D", + "step": 2400 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Threads", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["short", "short"], + "yaxes": [ + { + "decimals": 0, + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": { + "blocked": "#bf1b00", + "new": "#fce2de", + "runnable": "#7eb26d", + "terminated": "#511749", + "timed-waiting": "#c15c17", + "waiting": "#eab839" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "fill": 1, + "gridPos": { + "h": 7, + "w": 6, + "x": 18, + "y": 24 + }, + "id": 124, + "legend": { + "alignAsTable": false, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_threads_states_threads{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "{{state}}", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Thread States", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": { + "debug": "#1F78C1", + "error": "#BF1B00", + "info": "#508642", + "trace": "#6ED0E0", + "warn": "#EAB839" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 18, + "x": 0, + "y": 31 + }, + "height": "", + "id": 91, + "legend": { + "alignAsTable": false, + "avg": false, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "error", + "yaxis": 1 + }, + { + "alias": "warn", + "yaxis": 1 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "increase(logback_events_total{application=\"$application\", instance=\"$instance\"}[1m])", + "format": "time_series", + "interval": "", + "intervalFactor": 2, + "legendFormat": "{{level}}", + "metric": "", + "refId": "A", + "step": 1200 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Log Events (1m)", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["short", "short"], + "yaxes": [ + { + "decimals": 0, + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": "0", + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 18, + "y": 31 + }, + "id": 61, + "legend": { + "avg": false, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "process_open_fds{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "hide": false, + "intervalFactor": 2, + "legendFormat": "open", + "metric": "", + "refId": "A", + "step": 2400 + }, + { + "expr": "process_max_fds{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "hide": false, + "intervalFactor": 2, + "legendFormat": "max", + "metric": "", + "refId": "B", + "step": 2400 + }, + { + "expr": "process_files_open{application=\"$application\", instance=\"$instance\"} or process_files_open_files{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "open", + "refId": "C" + }, + { + "expr": "process_files_max{application=\"$application\", instance=\"$instance\"} or process_files_max_files{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "max", + "refId": "D" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "File Descriptors", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["short", "short"], + "yaxes": [ + { + "decimals": 0, + "format": "short", + "label": null, + "logBase": 10, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 38 + }, + "id": 129, + "panels": [], + "repeat": "persistence_counts", + "title": "JVM Memory Pools (Heap)", + "type": "row" + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 39 + }, + "id": 3, + "legend": { + "alignAsTable": false, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "maxPerRow": 3, + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "repeat": "jvm_memory_pool_heap", + "scopedVars": { + "jvm_memory_pool_heap": { + "selected": false, + "text": "PS Eden Space", + "value": "PS Eden Space" + } + }, + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 1800 + }, + { + "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "committed", + "metric": "", + "refId": "B", + "step": 1800 + }, + { + "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "max", + "metric": "", + "refId": "C", + "step": 1800 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "$jvm_memory_pool_heap", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["mbytes", "short"], + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 8, + "y": 39 + }, + "id": 134, + "legend": { + "alignAsTable": false, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "maxPerRow": 3, + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "repeat": null, + "repeatIteration": 1553765841423, + "repeatPanelId": 3, + "scopedVars": { + "jvm_memory_pool_heap": { + "selected": false, + "text": "PS Old Gen", + "value": "PS Old Gen" + } + }, + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 1800 + }, + { + "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "committed", + "metric": "", + "refId": "B", + "step": 1800 + }, + { + "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "max", + "metric": "", + "refId": "C", + "step": 1800 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "$jvm_memory_pool_heap", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["mbytes", "short"], + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 16, + "y": 39 + }, + "id": 135, + "legend": { + "alignAsTable": false, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "maxPerRow": 3, + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "repeat": null, + "repeatIteration": 1553765841423, + "repeatPanelId": 3, + "scopedVars": { + "jvm_memory_pool_heap": { + "selected": false, + "text": "PS Survivor Space", + "value": "PS Survivor Space" + } + }, + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 1800 + }, + { + "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "committed", + "metric": "", + "refId": "B", + "step": 1800 + }, + { + "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "max", + "metric": "", + "refId": "C", + "step": 1800 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "$jvm_memory_pool_heap", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["mbytes", "short"], + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 46 + }, + "id": 130, + "panels": [], + "repeat": null, + "title": "JVM Memory Pools (Non-Heap)", + "type": "row" + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 47 + }, + "id": 78, + "legend": { + "alignAsTable": false, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "maxPerRow": 3, + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "repeat": "jvm_memory_pool_nonheap", + "scopedVars": { + "jvm_memory_pool_nonheap": { + "selected": false, + "text": "Metaspace", + "value": "Metaspace" + } + }, + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 1800 + }, + { + "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "committed", + "metric": "", + "refId": "B", + "step": 1800 + }, + { + "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "max", + "metric": "", + "refId": "C", + "step": 1800 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "$jvm_memory_pool_nonheap", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["mbytes", "short"], + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 8, + "y": 47 + }, + "id": 136, + "legend": { + "alignAsTable": false, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "maxPerRow": 3, + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "repeat": null, + "repeatIteration": 1553765841423, + "repeatPanelId": 78, + "scopedVars": { + "jvm_memory_pool_nonheap": { + "selected": false, + "text": "Compressed Class Space", + "value": "Compressed Class Space" + } + }, + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 1800 + }, + { + "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "committed", + "metric": "", + "refId": "B", + "step": 1800 + }, + { + "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "max", + "metric": "", + "refId": "C", + "step": 1800 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "$jvm_memory_pool_nonheap", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["mbytes", "short"], + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 8, + "x": 16, + "y": 47 + }, + "id": 137, + "legend": { + "alignAsTable": false, + "avg": false, + "current": true, + "max": true, + "min": false, + "rightSide": false, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "links": [], + "maxPerRow": 3, + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "repeat": null, + "repeatIteration": 1553765841423, + "repeatPanelId": 78, + "scopedVars": { + "jvm_memory_pool_nonheap": { + "selected": false, + "text": "Code Cache", + "value": "Code Cache" + } + }, + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 1800 + }, + { + "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "committed", + "metric": "", + "refId": "B", + "step": 1800 + }, + { + "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "max", + "metric": "", + "refId": "C", + "step": 1800 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "$jvm_memory_pool_nonheap", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["mbytes", "short"], + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 54 + }, + "id": 131, + "panels": [], + "repeat": null, + "title": "Garbage Collection", + "type": "row" + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "fill": 1, + "gridPos": { + "h": 7, + "w": 8, + "x": 0, + "y": 55 + }, + "id": 98, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "rate(jvm_gc_pause_seconds_count{application=\"$application\", instance=\"$instance\"}[1m])", + "format": "time_series", + "hide": false, + "intervalFactor": 2, + "legendFormat": "{{action}} ({{cause}})", + "refId": "A" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Collections", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ops", + "label": null, + "logBase": 1, + "max": null, + "min": "0", + "show": true + }, + { + "format": "short", + "label": "", + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "fill": 1, + "gridPos": { + "h": 7, + "w": 8, + "x": 8, + "y": 55 + }, + "id": 101, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "rate(jvm_gc_pause_seconds_sum{application=\"$application\", instance=\"$instance\"}[1m])/rate(jvm_gc_pause_seconds_count{application=\"$application\", instance=\"$instance\"}[1m])", + "format": "time_series", + "hide": false, + "instant": false, + "intervalFactor": 1, + "legendFormat": "avg {{action}} ({{cause}})", + "refId": "A" + }, + { + "expr": "jvm_gc_pause_seconds_max{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "hide": false, + "instant": false, + "intervalFactor": 1, + "legendFormat": "max {{action}} ({{cause}})", + "refId": "B" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Pause Durations", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "s", + "label": null, + "logBase": 1, + "max": null, + "min": "0", + "show": true + }, + { + "format": "short", + "label": "", + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "fill": 1, + "gridPos": { + "h": 7, + "w": 8, + "x": 16, + "y": 55 + }, + "id": 99, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "rate(jvm_gc_memory_allocated_bytes_total{application=\"$application\", instance=\"$instance\"}[1m])", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "allocated", + "refId": "A" + }, + { + "expr": "rate(jvm_gc_memory_promoted_bytes_total{application=\"$application\", instance=\"$instance\"}[1m])", + "format": "time_series", + "interval": "", + "intervalFactor": 1, + "legendFormat": "promoted", + "refId": "B" + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Allocated/Promoted", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": "0", + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 62 + }, + "id": 132, + "panels": [], + "repeat": null, + "title": "Classloading", + "type": "row" + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 0, + "y": 63 + }, + "id": 37, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_classes_loaded{application=\"$application\", instance=\"$instance\"} or jvm_classes_loaded_classes{application=\"$application\", instance=\"$instance\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "loaded", + "metric": "", + "refId": "A", + "step": 1200 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Classes loaded", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["short", "short"], + "yaxes": [ + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 12, + "x": 12, + "y": 63 + }, + "id": 38, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "delta(jvm_classes_loaded{application=\"$application\",instance=\"$instance\"}[5m]) or delta(jvm_classes_loaded_classes{application=\"$application\",instance=\"$instance\"}[5m])", + "format": "time_series", + "hide": false, + "interval": "", + "intervalFactor": 2, + "legendFormat": "delta", + "metric": "", + "refId": "A", + "step": 1200 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Class delta (5m)", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["ops", "short"], + "yaxes": [ + { + "decimals": null, + "format": "short", + "label": "", + "logBase": 1, + "max": null, + "min": null, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 70 + }, + "id": 133, + "panels": [], + "repeat": null, + "title": "Buffer Pools", + "type": "row" + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 0, + "y": 71 + }, + "id": 33, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_buffer_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"direct\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 2400 + }, + { + "expr": "jvm_buffer_total_capacity_bytes{application=\"$application\", instance=\"$instance\", id=\"direct\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "capacity", + "metric": "", + "refId": "B", + "step": 2400 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Direct Buffers", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["short", "short"], + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 6, + "y": 71 + }, + "id": 83, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_buffer_count{application=\"$application\", instance=\"$instance\", id=\"direct\"} or jvm_buffer_count_buffers{application=\"$application\", instance=\"$instance\", id=\"direct\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "count", + "metric": "", + "refId": "A", + "step": 2400 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Direct Buffers", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["short", "short"], + "yaxes": [ + { + "decimals": 0, + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 12, + "y": 71 + }, + "id": 85, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_buffer_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"mapped\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "used", + "metric": "", + "refId": "A", + "step": 2400 + }, + { + "expr": "jvm_buffer_total_capacity_bytes{application=\"$application\", instance=\"$instance\", id=\"mapped\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "capacity", + "metric": "", + "refId": "B", + "step": 2400 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Mapped Buffers", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["short", "short"], + "yaxes": [ + { + "format": "bytes", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + }, + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": "Prometheus", + "editable": true, + "error": false, + "fill": 1, + "grid": { + "leftLogBase": 1, + "leftMax": null, + "leftMin": null, + "rightLogBase": 1, + "rightMax": null, + "rightMin": null + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 18, + "y": 71 + }, + "id": 84, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "links": [], + "nullPointMode": "null", + "paceLength": 10, + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "expr": "jvm_buffer_count{application=\"$application\", instance=\"$instance\", id=\"mapped\"} or jvm_buffer_count_buffers{application=\"$application\", instance=\"$instance\", id=\"mapped\"}", + "format": "time_series", + "intervalFactor": 2, + "legendFormat": "count", + "metric": "", + "refId": "A", + "step": 2400 + } + ], + "thresholds": [], + "timeFrom": null, + "timeRegions": [], + "timeShift": null, + "title": "Mapped Buffers", + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "type": "graph", + "x-axis": true, + "xaxis": { + "buckets": null, + "mode": "time", + "name": null, + "show": true, + "values": [] + }, + "y-axis": true, + "y_formats": ["short", "short"], + "yaxes": [ + { + "decimals": 0, + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": 0, + "show": true + }, + { + "format": "short", + "label": null, + "logBase": 1, + "max": null, + "min": null, + "show": true + } + ], + "yaxis": { + "align": false, + "alignLevel": null + } + } + ], + "refresh": "10s", + "schemaVersion": 18, + "style": "dark", + "tags": [], + "templating": { + "list": [ + { + "allValue": null, + "current": { + "text": "test", + "value": "test" + }, + "datasource": "Prometheus", + "definition": "", + "hide": 0, + "includeAll": false, + "label": "Application", + "multi": false, + "name": "application", + "options": [], + "query": "label_values(application)", + "refresh": 2, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "tagValuesQuery": "", + "tags": [], + "tagsQuery": "", + "type": "query", + "useTags": false + }, + { + "allFormat": "glob", + "allValue": null, + "current": { + "text": "localhost:8080", + "value": "localhost:8080" + }, + "datasource": "Prometheus", + "definition": "", + "hide": 0, + "includeAll": false, + "label": "Instance", + "multi": false, + "multiFormat": "glob", + "name": "instance", + "options": [], + "query": "label_values(jvm_memory_used_bytes{application=\"$application\"}, instance)", + "refresh": 2, + "regex": "", + "skipUrlSync": false, + "sort": 0, + "tagValuesQuery": "", + "tags": [], + "tagsQuery": "", + "type": "query", + "useTags": false + }, + { + "allFormat": "glob", + "allValue": null, + "current": { + "text": "All", + "value": "$__all" + }, + "datasource": "Prometheus", + "definition": "", + "hide": 0, + "includeAll": true, + "label": "JVM Memory Pools Heap", + "multi": false, + "multiFormat": "glob", + "name": "jvm_memory_pool_heap", + "options": [], + "query": "label_values(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"},id)", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "sort": 1, + "tagValuesQuery": "", + "tags": [], + "tagsQuery": "", + "type": "query", + "useTags": false + }, + { + "allFormat": "glob", + "allValue": null, + "current": { + "text": "All", + "value": "$__all" + }, + "datasource": "Prometheus", + "definition": "", + "hide": 0, + "includeAll": true, + "label": "JVM Memory Pools Non-Heap", + "multi": false, + "multiFormat": "glob", + "name": "jvm_memory_pool_nonheap", + "options": [], + "query": "label_values(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"},id)", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "sort": 2, + "tagValuesQuery": "", + "tags": [], + "tagsQuery": "", + "type": "query", + "useTags": false + } + ] + }, + "time": { + "from": "now-30m", + "to": "now" + }, + "timepicker": { + "now": true, + "refresh_intervals": ["5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d"], + "time_options": ["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"] + }, + "timezone": "browser", + "title": "JVM (Micrometer)", + "uid": "Ud1CFe3iz", + "version": 1 +} diff --git a/src/main/docker/grafana/provisioning/dashboards/dashboard.yml b/src/main/docker/grafana/provisioning/dashboards/dashboard.yml new file mode 100644 index 0000000..4817a83 --- /dev/null +++ b/src/main/docker/grafana/provisioning/dashboards/dashboard.yml @@ -0,0 +1,11 @@ +apiVersion: 1 + +providers: + - name: 'Prometheus' + orgId: 1 + folder: '' + type: file + disableDeletion: false + editable: true + options: + path: /etc/grafana/provisioning/dashboards diff --git a/src/main/docker/grafana/provisioning/datasources/datasource.yml b/src/main/docker/grafana/provisioning/datasources/datasource.yml new file mode 100644 index 0000000..ef8b00d --- /dev/null +++ b/src/main/docker/grafana/provisioning/datasources/datasource.yml @@ -0,0 +1,50 @@ +apiVersion: 1 + +# list of datasources that should be deleted from the database +deleteDatasources: + - name: Prometheus + orgId: 1 + +# list of datasources to insert/update depending +# whats available in the database +datasources: + # name of the datasource. Required + - name: Prometheus + # datasource type. Required + type: prometheus + # access mode. direct or proxy. Required + access: proxy + # org id. will default to orgId 1 if not specified + orgId: 1 + # url + # On macOS, replace localhost by host.docker.internal + url: http://localhost:9090 + # database password, if used + password: + # database user, if used + user: + # database name, if used + database: + # enable/disable basic auth + basicAuth: false + # basic auth username + basicAuthUser: admin + # basic auth password + basicAuthPassword: admin + # enable/disable with credentials headers + withCredentials: + # mark as default datasource. Max one per org + isDefault: true + # fields that will be converted to json and stored in json_data + jsonData: + graphiteVersion: '1.1' + tlsAuth: false + tlsAuthWithCACert: false + # json object of data that will be encrypted. + secureJsonData: + tlsCACert: '...' + tlsClientCert: '...' + tlsClientKey: '...' + version: 1 + # allow users to edit datasources from the UI. + editable: true diff --git a/src/main/docker/jhipster-control-center.yml b/src/main/docker/jhipster-control-center.yml new file mode 100644 index 0000000..03012f7 --- /dev/null +++ b/src/main/docker/jhipster-control-center.yml @@ -0,0 +1,51 @@ +## How to use JHCC docker compose +# To allow JHCC to reach JHipster application from a docker container note that we set the host as host.docker.internal +# To reach the application from a browser, you need to add '127.0.0.1 host.docker.internal' to your hosts file. +### Discovery mode +# JHCC supports 3 kinds of discovery mode: Consul, Eureka and static +# In order to use one, please set SPRING_PROFILES_ACTIVE to one (and only one) of these values: consul,eureka,static +### Discovery properties +# According to the discovery mode choose as Spring profile, you have to set the right properties +# please note that current properties are set to run JHCC with default values, personalize them if needed +# and remove those from other modes. You can only have one mode active. +#### Eureka +# - EUREKA_CLIENT_SERVICE_URL_DEFAULTZONE=http://admin:admin@host.docker.internal:8761/eureka/ +#### Consul +# - SPRING_CLOUD_CONSUL_HOST=host.docker.internal +# - SPRING_CLOUD_CONSUL_PORT=8500 +#### Static +# Add instances to "MyApp" +# - SPRING_CLOUD_DISCOVERY_CLIENT_SIMPLE_INSTANCES_MYAPP_0_URI=http://host.docker.internal:8081 +# - SPRING_CLOUD_DISCOVERY_CLIENT_SIMPLE_INSTANCES_MYAPP_1_URI=http://host.docker.internal:8082 +# Or add a new application named MyNewApp +# - SPRING_CLOUD_DISCOVERY_CLIENT_SIMPLE_INSTANCES_MYNEWAPP_0_URI=http://host.docker.internal:8080 +# This configuration is intended for development purpose, it's **your** responsibility to harden it for production + +#### IMPORTANT +# If you choose Consul or Eureka mode: +# Do not forget to remove the prefix "127.0.0.1" in front of their port in order to expose them. +# This is required because JHCC needs to communicate with Consul or Eureka. +# - In Consul mode, the ports are in the consul.yml file. +# - In Eureka mode, the ports are in the jhipster-registry.yml file. + +name: questionbank +services: + jhipster-control-center: + image: 'jhipster/jhipster-control-center:v0.5.0' + command: + - /bin/sh + - -c + # Patch /etc/hosts to support resolving host.docker.internal to the internal IP address used by the host in all OSes + - echo "`ip route | grep default | cut -d ' ' -f3` host.docker.internal" | tee -a /etc/hosts > /dev/null && java -jar /jhipster-control-center.jar + environment: + - _JAVA_OPTIONS=-Xmx512m -Xms256m + - SPRING_PROFILES_ACTIVE=prod,api-docs,static + - SPRING_SECURITY_USER_PASSWORD=admin + # The token should have the same value as the one declared in you Spring configuration under the jhipster.security.authentication.jwt.base64-secret configuration's entry + - JHIPSTER_SECURITY_AUTHENTICATION_JWT_BASE64_SECRET=MzY1ZDU0MDM3M2Y5YWRiMDYxYjBmYzZlOTMxMWFiNmYyMDEyZTUzZjYxOWFjNjhlNjU2NzcxYjkwY2Y0MGIwOGUyNTc5NWQyOGY3OGJkMjExZjhkYzU3ZGU4ZDc0ZmZiMTYwMzY0NGM4ZWZmODRhZTZjNzBlNjk5MWJkYjM5YjI= + - SPRING_CLOUD_DISCOVERY_CLIENT_SIMPLE_INSTANCES_QUESTIONBANK_0_URI=http://host.docker.internal:8080 + - LOGGING_FILE_NAME=/tmp/jhipster-control-center.log + # If you want to expose these ports outside your dev PC, + # remove the "127.0.0.1:" prefix + ports: + - 127.0.0.1:7419:7419 diff --git a/src/main/docker/jib/entrypoint.sh b/src/main/docker/jib/entrypoint.sh new file mode 100644 index 0000000..3d4b64d --- /dev/null +++ b/src/main/docker/jib/entrypoint.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +echo "The application will start in ${JHIPSTER_SLEEP}s..." && sleep ${JHIPSTER_SLEEP} + +# usage: file_env VAR [DEFAULT] +# ie: file_env 'XYZ_DB_PASSWORD' 'example' +# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of +# "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature) +file_env() { + local var="$1" + local file_var="${var}_FILE" + local def="${2:-}" + if [[ ${!var:-} && ${!file_var:-} ]]; then + echo >&2 "error: both $var and $file_var are set (but are exclusive)" + exit 1 + fi + local val="$def" + if [[ ${!var:-} ]]; then + val="${!var}" + elif [[ ${!file_var:-} ]]; then + val="$(< "${!file_var}")" + fi + + if [[ -n $val ]]; then + export "$var"="$val" + fi + + unset "$file_var" + return 0 +} + +file_env 'SPRING_DATASOURCE_URL' +file_env 'SPRING_DATASOURCE_USERNAME' +file_env 'SPRING_DATASOURCE_PASSWORD' +file_env 'SPRING_LIQUIBASE_URL' +file_env 'SPRING_LIQUIBASE_USER' +file_env 'SPRING_LIQUIBASE_PASSWORD' +file_env 'JHIPSTER_REGISTRY_PASSWORD' + +exec java ${JAVA_OPTS} -noverify -XX:+AlwaysPreTouch -cp /app/resources/:/app/classes/:/app/libs/* "com.example.questionbank.QuestionBankApp" "$@" diff --git a/src/main/docker/monitoring.yml b/src/main/docker/monitoring.yml new file mode 100644 index 0000000..b19a677 --- /dev/null +++ b/src/main/docker/monitoring.yml @@ -0,0 +1,31 @@ +# This configuration is intended for development purpose, it's **your** responsibility to harden it for production +name: questionbank +services: + prometheus: + image: prom/prometheus:v3.14.0 + volumes: + - ./prometheus/:/etc/prometheus/ + command: + - '--config.file=/etc/prometheus/prometheus.yml' + # If you want to expose these ports outside your dev PC, + # remove the "127.0.0.1:" prefix + ports: + - 127.0.0.1:9090:9090 + # On macOS, remove next line and replace localhost by host.docker.internal in prometheus/prometheus.yml and + # grafana/provisioning/datasources/datasource.yml + network_mode: 'host' # to test locally running service + grafana: + image: grafana/grafana:13.2.0 + volumes: + - ./grafana/provisioning/:/etc/grafana/provisioning/ + environment: + - GF_SECURITY_ADMIN_PASSWORD=admin + - GF_USERS_ALLOW_SIGN_UP=false + - GF_INSTALL_PLUGINS=grafana-piechart-panel + # If you want to expose these ports outside your dev PC, + # remove the "127.0.0.1:" prefix + ports: + - 127.0.0.1:3000:3000 + # On macOS, remove next line and replace localhost by host.docker.internal in prometheus/prometheus.yml and + # grafana/provisioning/datasources/datasource.yml + network_mode: 'host' # to test locally running service diff --git a/src/main/docker/postgresql.yml b/src/main/docker/postgresql.yml new file mode 100644 index 0000000..98cbc36 --- /dev/null +++ b/src/main/docker/postgresql.yml @@ -0,0 +1,19 @@ +# This configuration is intended for development purpose, it's **your** responsibility to harden it for production +name: questionbank +services: + postgresql: + image: postgres:18.6 + # volumes: + # - ~/volumes/jhipster/questionBank/postgresql/:/var/lib/postgresql/data/ + environment: + - POSTGRES_USER=questionBank + - POSTGRES_HOST_AUTH_METHOD=trust + healthcheck: + test: ['CMD-SHELL', 'pg_isready -U $${POSTGRES_USER}'] + interval: 5s + timeout: 5s + retries: 10 + # If you want to expose these ports outside your dev PC, + # remove the "127.0.0.1:" prefix + ports: + - 127.0.0.1:5432:5432 diff --git a/src/main/docker/prometheus/prometheus.yml b/src/main/docker/prometheus/prometheus.yml new file mode 100644 index 0000000..5717cac --- /dev/null +++ b/src/main/docker/prometheus/prometheus.yml @@ -0,0 +1,31 @@ +# Sample global config for monitoring JHipster applications +global: + scrape_interval: 15s # By default, scrape targets every 15 seconds. + evaluation_interval: 15s # By default, scrape targets every 15 seconds. + # scrape_timeout is set to the global default (10s). + + # Attach these labels to any time series or alerts when communicating with + # external systems (federation, remote storage, Alertmanager). + external_labels: + monitor: 'jhipster' + +# A scrape configuration containing exactly one endpoint to scrape: +# Here it's Prometheus itself. +scrape_configs: + # The job name is added as a label `job=` to any timeseries scraped from this config. + - job_name: 'prometheus' + + # Override the global default and scrape targets from this job every 5 seconds. + scrape_interval: 5s + + # scheme defaults to 'http' enable https in case your application is server via https + #scheme: https + # basic auth is not needed by default. See https://www.jhipster.tech/monitoring/#configuring-metrics-forwarding for details + #basic_auth: + # username: admin + # password: admin + metrics_path: /management/prometheus + static_configs: + - targets: + # On macOS, replace localhost by host.docker.internal + - localhost:8080 diff --git a/src/main/docker/services.yml b/src/main/docker/services.yml new file mode 100644 index 0000000..01644c5 --- /dev/null +++ b/src/main/docker/services.yml @@ -0,0 +1,7 @@ +# This configuration is intended for development purpose, it's **your** responsibility to harden it for production +name: questionbank +services: + postgresql: + extends: + file: ./postgresql.yml + service: postgresql diff --git a/src/main/docker/sonar.yml b/src/main/docker/sonar.yml new file mode 100644 index 0000000..5647321 --- /dev/null +++ b/src/main/docker/sonar.yml @@ -0,0 +1,15 @@ +# This configuration is intended for development purpose, it's **your** responsibility to harden it for production +name: questionbank +services: + sonar: + container_name: sonarqube + image: sonarqube:26.8.0.126808-community + # Forced authentication redirect for UI is turned off for out of the box experience while trying out SonarQube + # For real use cases delete SONAR_FORCEAUTHENTICATION variable or set SONAR_FORCEAUTHENTICATION=true + environment: + - SONAR_FORCEAUTHENTICATION=false + # If you want to expose these ports outside your dev PC, + # remove the "127.0.0.1:" prefix + ports: + - 127.0.0.1:9001:9000 + - 127.0.0.1:9000:9000 diff --git a/src/main/java/com/example/questionbank/ApplicationWebXml.java b/src/main/java/com/example/questionbank/ApplicationWebXml.java new file mode 100644 index 0000000..d81dada --- /dev/null +++ b/src/main/java/com/example/questionbank/ApplicationWebXml.java @@ -0,0 +1,19 @@ +package com.example.questionbank; + +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import tech.jhipster.config.DefaultProfileUtil; + +/** + * This is a helper Java class that provides an alternative to creating a {@code web.xml}. + * This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc. + */ +public class ApplicationWebXml extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + // set a default to use when no profile is configured. + DefaultProfileUtil.addDefaultProfile(application.application()); + return application.sources(QuestionBankApp.class); + } +} diff --git a/src/main/java/com/example/questionbank/GeneratedByJHipster.java b/src/main/java/com/example/questionbank/GeneratedByJHipster.java new file mode 100644 index 0000000..98acebf --- /dev/null +++ b/src/main/java/com/example/questionbank/GeneratedByJHipster.java @@ -0,0 +1,12 @@ +package com.example.questionbank; + +import jakarta.annotation.Generated; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Generated(value = "JHipster", comments = "Generated by JHipster 9.3.0") +@Retention(RetentionPolicy.SOURCE) +@Target({ ElementType.TYPE }) +public @interface GeneratedByJHipster {} diff --git a/src/main/java/com/example/questionbank/QuestionBankApp.java b/src/main/java/com/example/questionbank/QuestionBankApp.java new file mode 100644 index 0000000..743cd0b --- /dev/null +++ b/src/main/java/com/example/questionbank/QuestionBankApp.java @@ -0,0 +1,110 @@ +package com.example.questionbank; + +import com.example.questionbank.config.ApplicationProperties; +import com.example.questionbank.config.CRLFLogConverter; +import jakarta.annotation.PostConstruct; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.liquibase.autoconfigure.LiquibaseProperties; +import org.springframework.core.env.Environment; +import tech.jhipster.config.DefaultProfileUtil; +import tech.jhipster.config.JHipsterConstants; + +@SpringBootApplication() +@EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class }) +public class QuestionBankApp { + + private static final Logger LOG = LoggerFactory.getLogger(QuestionBankApp.class); + + private final Environment env; + + public QuestionBankApp(Environment env) { + this.env = env; + } + + /** + * Initializes questionBank. + *

+ * Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile + *

+ * You can find more information on how profiles work with JHipster on https://www.jhipster.tech/profiles/. + */ + @PostConstruct + public void initApplication() { + Collection activeProfiles = List.of(env.getActiveProfiles()); + if ( + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION) + ) { + LOG.error( + "You have misconfigured your application! It should not run " + "with both the 'dev' and 'prod' profiles at the same time." + ); + } + if ( + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD) + ) { + LOG.error( + "You have misconfigured your application! It should not " + "run with both the 'dev' and 'cloud' profiles at the same time." + ); + } + } + + /** + * Main method, used to run the application. + * + * @param args the command line arguments. + */ + public static void main(String[] args) { + var app = new SpringApplication(QuestionBankApp.class); + DefaultProfileUtil.addDefaultProfile(app); + Environment env = app.run(args).getEnvironment(); + logApplicationStartup(env); + } + + private static void logApplicationStartup(Environment env) { + String protocol = Optional.ofNullable(env.getProperty("server.ssl.key-store")) + .map(key -> "https") + .orElse("http"); + String applicationName = env.getProperty("spring.application.name"); + String serverPort = env.getProperty("server.port"); + String contextPath = Optional.ofNullable(env.getProperty("server.servlet.context-path")) + .filter(StringUtils::isNotBlank) + .orElse("/"); + var hostAddress = "localhost"; + try { + hostAddress = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + LOG.warn("The host name could not be determined, using `localhost` as fallback"); + } + LOG.info( + CRLFLogConverter.CRLF_SAFE_MARKER, + """ + + ---------------------------------------------------------- + \tApplication '{}' is running! Access URLs: + \tLocal: \t\t{}://localhost:{}{} + \tExternal: \t{}://{}:{}{} + \tProfile(s): \t{} + ----------------------------------------------------------""", + applicationName, + protocol, + serverPort, + contextPath, + protocol, + hostAddress, + serverPort, + contextPath, + env.getActiveProfiles().length == 0 ? env.getDefaultProfiles() : env.getActiveProfiles() + ); + } +} diff --git a/src/main/java/com/example/questionbank/aop/logging/LoggingAspect.java b/src/main/java/com/example/questionbank/aop/logging/LoggingAspect.java new file mode 100644 index 0000000..fab79a2 --- /dev/null +++ b/src/main/java/com/example/questionbank/aop/logging/LoggingAspect.java @@ -0,0 +1,131 @@ +package com.example.questionbank.aop.logging; + +import java.util.Arrays; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; +import tech.jhipster.config.JHipsterConstants; + +/** + * Aspect for logging execution of service and repository Spring components. + * + * By default, it only runs with the "dev" profile. + */ +@Aspect +public class LoggingAspect { + + private final Environment env; + + public LoggingAspect(Environment env) { + this.env = env; + } + + /** + * Pointcut that matches all repositories, services and Web REST endpoints. + */ + @Pointcut( + """ + within(@org.springframework.stereotype.Repository *) + || within(@org.springframework.stereotype.Service *) + || within(@org.springframework.web.bind.annotation.RestController *) + """ + ) + public void springBeanPointcut() { + // Method is empty as this is just a Pointcut, the implementations are in the advice methods. + } + + /** + * Pointcut that matches all Spring beans in the application's main packages. + */ + @Pointcut( + """ + within(com.example.questionbank.repository..*) + || within(com.example.questionbank.service..*) + || within(com.example.questionbank.web.rest..*) + """ + ) + public void applicationPackagePointcut() { + // Method is empty as this is just a Pointcut, the implementations are in the advice methods. + } + + /** + * Retrieves the {@link Logger} associated to the given {@link JoinPoint}. + * + * @param joinPoint join point we want the logger for. + * @return {@link Logger} associated to the given {@link JoinPoint}. + */ + private Logger logger(JoinPoint joinPoint) { + return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName()); + } + + /** + * Advice that logs methods throwing exceptions. + * + * @param joinPoint join point for advice. + * @param e exception. + */ + @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") + public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { + logException(joinPoint, e); + } + + /** + * Advice that logs when a method is entered and exited. + * + * @param joinPoint join point for advice. + * @return result. + * @throws Throwable rethrows the exception thrown by the advised method. + */ + @Around("applicationPackagePointcut() && springBeanPointcut()") + public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { + var log = logger(joinPoint); + if (log.isDebugEnabled()) { + log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); + } + try { + Object result = joinPoint.proceed(); + logExit(log, joinPoint, result); + return result; + } catch (IllegalArgumentException e) { + logIllegalArgument(log, joinPoint); + throw e; + } + } + + private void logExit(Logger log, JoinPoint joinPoint, Object result) { + if (log.isDebugEnabled()) { + log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result); + } + } + + private void logIllegalArgument(Logger log, JoinPoint joinPoint) { + if (log.isErrorEnabled()) { + log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName()); + } + } + + private void logException(JoinPoint joinPoint, Throwable e) { + if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { + logger(joinPoint).error( + "Exception in {}() with cause = '{}' and exception = '{}'", + joinPoint.getSignature().getName(), + e.getCause() != null ? e.getCause() : "NULL", + e.getMessage(), + e + ); + } else { + logger(joinPoint).error( + "Exception in {}() with cause = {}", + joinPoint.getSignature().getName(), + e.getCause() != null ? String.valueOf(e.getCause()) : "NULL" + ); + } + } +} diff --git a/src/main/java/com/example/questionbank/aop/logging/package-info.java b/src/main/java/com/example/questionbank/aop/logging/package-info.java new file mode 100644 index 0000000..d398822 --- /dev/null +++ b/src/main/java/com/example/questionbank/aop/logging/package-info.java @@ -0,0 +1,4 @@ +/** + * Logging aspect. + */ +package com.example.questionbank.aop.logging; diff --git a/src/main/java/com/example/questionbank/config/ApplicationProperties.java b/src/main/java/com/example/questionbank/config/ApplicationProperties.java new file mode 100644 index 0000000..b62de5d --- /dev/null +++ b/src/main/java/com/example/questionbank/config/ApplicationProperties.java @@ -0,0 +1,38 @@ +package com.example.questionbank.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Properties specific to Question Bank. + *

+ * Properties are configured in the {@code application.yml} file. + * See {@link tech.jhipster.config.JHipsterProperties} for a good example. + */ +@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false) +public class ApplicationProperties { + + private final Liquibase liquibase = new Liquibase(); + + // jhipster-needle-application-properties-property + + public Liquibase getLiquibase() { + return liquibase; + } + + // jhipster-needle-application-properties-property-getter + + public static class Liquibase { + + private Boolean asyncStart = true; + + public Boolean getAsyncStart() { + return asyncStart; + } + + public void setAsyncStart(Boolean asyncStart) { + this.asyncStart = asyncStart; + } + } + + // jhipster-needle-application-properties-property-class +} diff --git a/src/main/java/com/example/questionbank/config/AsyncConfiguration.java b/src/main/java/com/example/questionbank/config/AsyncConfiguration.java new file mode 100644 index 0000000..aad90d0 --- /dev/null +++ b/src/main/java/com/example/questionbank/config/AsyncConfiguration.java @@ -0,0 +1,48 @@ +package com.example.questionbank.config; + +import java.util.concurrent.Executor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; +import org.springframework.boot.autoconfigure.task.TaskExecutionProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import tech.jhipster.async.ExceptionHandlingAsyncTaskExecutor; + +@Configuration +@EnableAsync +@EnableScheduling +@Profile("!testdev & !testprod") +public class AsyncConfiguration implements AsyncConfigurer { + + private static final Logger LOG = LoggerFactory.getLogger(AsyncConfiguration.class); + + private final TaskExecutionProperties taskExecutionProperties; + + public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) { + this.taskExecutionProperties = taskExecutionProperties; + } + + @Override + @Bean(name = "taskExecutor") + public Executor getAsyncExecutor() { + LOG.debug("Creating Async Task Executor"); + var executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize()); + executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize()); + executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity()); + executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix()); + return new ExceptionHandlingAsyncTaskExecutor(executor); + } + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return new SimpleAsyncUncaughtExceptionHandler(); + } +} diff --git a/src/main/java/com/example/questionbank/config/CRLFLogConverter.java b/src/main/java/com/example/questionbank/config/CRLFLogConverter.java new file mode 100644 index 0000000..1ef5a01 --- /dev/null +++ b/src/main/java/com/example/questionbank/config/CRLFLogConverter.java @@ -0,0 +1,69 @@ +package com.example.questionbank.config; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.pattern.CompositeConverter; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; +import org.springframework.boot.ansi.AnsiColor; +import org.springframework.boot.ansi.AnsiElement; +import org.springframework.boot.ansi.AnsiOutput; +import org.springframework.boot.ansi.AnsiStyle; + +/** + * Log filter to prevent attackers from forging log entries by submitting input containing CRLF characters. + * CRLF characters are replaced with a red colored _ character. + * + * @see Log Forging Description + * @see JHipster issue + */ +public class CRLFLogConverter extends CompositeConverter { + + public static final Marker CRLF_SAFE_MARKER = MarkerFactory.getMarker("CRLF_SAFE"); + + private static final String[] SAFE_LOGS = { + "org.hibernate", + "org.springframework.boot.autoconfigure", + "org.springframework.boot.diagnostics", + }; + private static final Map ELEMENTS; + + static { + Map ansiElements = new HashMap<>(); + ansiElements.put("faint", AnsiStyle.FAINT); + ansiElements.put("red", AnsiColor.RED); + ansiElements.put("green", AnsiColor.GREEN); + ansiElements.put("yellow", AnsiColor.YELLOW); + ansiElements.put("blue", AnsiColor.BLUE); + ansiElements.put("magenta", AnsiColor.MAGENTA); + ansiElements.put("cyan", AnsiColor.CYAN); + ELEMENTS = Collections.unmodifiableMap(ansiElements); + } + + @Override + protected String transform(ILoggingEvent event, String in) { + AnsiElement element = ELEMENTS.get(getFirstOption()); + List markers = event.getMarkerList(); + if ((markers != null && !markers.isEmpty() && markers.getFirst().contains(CRLF_SAFE_MARKER)) || isLoggerSafe(event)) { + return in; + } + String replacement = element == null ? "_" : toAnsiString("_", element); + return in.replaceAll("[\n\r\t]", replacement); + } + + protected boolean isLoggerSafe(ILoggingEvent event) { + for (String safeLogger : SAFE_LOGS) { + if (event.getLoggerName().startsWith(safeLogger)) { + return true; + } + } + return false; + } + + protected String toAnsiString(String in, AnsiElement element) { + return AnsiOutput.toString(element, in); + } +} diff --git a/src/main/java/com/example/questionbank/config/Constants.java b/src/main/java/com/example/questionbank/config/Constants.java new file mode 100644 index 0000000..1a650cc --- /dev/null +++ b/src/main/java/com/example/questionbank/config/Constants.java @@ -0,0 +1,15 @@ +package com.example.questionbank.config; + +/** + * Application constants. + */ +public final class Constants { + + // Regex for acceptable logins + public static final String LOGIN_REGEX = "^(?>[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*)|(?>[_.@A-Za-z0-9-]+)$"; + + public static final String SYSTEM = "system"; + public static final String DEFAULT_LANGUAGE = "en"; + + private Constants() {} +} diff --git a/src/main/java/com/example/questionbank/config/DatabaseConfiguration.java b/src/main/java/com/example/questionbank/config/DatabaseConfiguration.java new file mode 100644 index 0000000..f0b05f2 --- /dev/null +++ b/src/main/java/com/example/questionbank/config/DatabaseConfiguration.java @@ -0,0 +1,12 @@ +package com.example.questionbank.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableJpaRepositories({ "com.example.questionbank.repository" }) +@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware") +@EnableTransactionManagement +public class DatabaseConfiguration {} diff --git a/src/main/java/com/example/questionbank/config/DateTimeFormatConfiguration.java b/src/main/java/com/example/questionbank/config/DateTimeFormatConfiguration.java new file mode 100644 index 0000000..365eb16 --- /dev/null +++ b/src/main/java/com/example/questionbank/config/DateTimeFormatConfiguration.java @@ -0,0 +1,20 @@ +package com.example.questionbank.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.format.FormatterRegistry; +import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * Configure the converters to use the ISO format for dates by default. + */ +@Configuration +public class DateTimeFormatConfiguration implements WebMvcConfigurer { + + @Override + public void addFormatters(FormatterRegistry registry) { + var registrar = new DateTimeFormatterRegistrar(); + registrar.setUseIsoFormat(true); + registrar.registerFormatters(registry); + } +} diff --git a/src/main/java/com/example/questionbank/config/JacksonHibernateConfiguration.java b/src/main/java/com/example/questionbank/config/JacksonHibernateConfiguration.java new file mode 100644 index 0000000..6af1056 --- /dev/null +++ b/src/main/java/com/example/questionbank/config/JacksonHibernateConfiguration.java @@ -0,0 +1,18 @@ +package com.example.questionbank.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import tools.jackson.datatype.hibernate7.Hibernate7Module; +import tools.jackson.datatype.hibernate7.Hibernate7Module.Feature; + +@Configuration +public class JacksonHibernateConfiguration { + + /* + * Support for Hibernate types in Jackson. + */ + @Bean + public Hibernate7Module hibernate7Module() { + return new Hibernate7Module().configure(Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS, true); + } +} diff --git a/src/main/java/com/example/questionbank/config/LiquibaseConfiguration.java b/src/main/java/com/example/questionbank/config/LiquibaseConfiguration.java new file mode 100644 index 0000000..b6646ff --- /dev/null +++ b/src/main/java/com/example/questionbank/config/LiquibaseConfiguration.java @@ -0,0 +1,83 @@ +package com.example.questionbank.config; + +import java.util.concurrent.Executor; +import javax.sql.DataSource; +import liquibase.integration.spring.SpringLiquibase; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.jdbc.autoconfigure.DataSourceProperties; +import org.springframework.boot.liquibase.autoconfigure.LiquibaseDataSource; +import org.springframework.boot.liquibase.autoconfigure.LiquibaseProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; +import tech.jhipster.config.JHipsterConstants; +import tech.jhipster.config.liquibase.SpringLiquibaseUtil; + +@Configuration +public class LiquibaseConfiguration { + + private static final Logger LOG = LoggerFactory.getLogger(LiquibaseConfiguration.class); + + private final Environment env; + + public LiquibaseConfiguration(Environment env) { + this.env = env; + } + + @Bean + public SpringLiquibase liquibase( + @Qualifier("taskExecutor") Executor executor, + LiquibaseProperties liquibaseProperties, + @LiquibaseDataSource ObjectProvider liquibaseDataSource, + ObjectProvider dataSource, + ApplicationProperties applicationProperties, + DataSourceProperties dataSourceProperties + ) { + SpringLiquibase liquibase; + if (Boolean.TRUE.equals(applicationProperties.getLiquibase().getAsyncStart())) { + liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase( + this.env, + executor, + liquibaseDataSource.getIfAvailable(), + liquibaseProperties, + dataSource.getIfUnique(), + dataSourceProperties + ); + } else { + liquibase = SpringLiquibaseUtil.createSpringLiquibase( + liquibaseDataSource.getIfAvailable(), + liquibaseProperties, + dataSource.getIfUnique(), + dataSourceProperties + ); + } + liquibase.setChangeLog("classpath:config/liquibase/master.xml"); + if (!CollectionUtils.isEmpty(liquibaseProperties.getContexts())) { + liquibase.setContexts(StringUtils.collectionToCommaDelimitedString(liquibaseProperties.getContexts())); + } + liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); + liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema()); + liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace()); + liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable()); + liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable()); + liquibase.setDropFirst(liquibaseProperties.isDropFirst()); + if (!CollectionUtils.isEmpty(liquibaseProperties.getLabelFilter())) { + liquibase.setLabelFilter(StringUtils.collectionToCommaDelimitedString(liquibaseProperties.getLabelFilter())); + } + liquibase.setChangeLogParameters(liquibaseProperties.getParameters()); + liquibase.setRollbackFile(liquibaseProperties.getRollbackFile()); + liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate()); + if (env.matchesProfiles(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE)) { + liquibase.setShouldRun(false); + } else { + liquibase.setShouldRun(liquibaseProperties.isEnabled()); + LOG.debug("Configuring Liquibase"); + } + return liquibase; + } +} diff --git a/src/main/java/com/example/questionbank/config/LoggingAspectConfiguration.java b/src/main/java/com/example/questionbank/config/LoggingAspectConfiguration.java new file mode 100644 index 0000000..f7ae9e0 --- /dev/null +++ b/src/main/java/com/example/questionbank/config/LoggingAspectConfiguration.java @@ -0,0 +1,17 @@ +package com.example.questionbank.config; + +import com.example.questionbank.aop.logging.LoggingAspect; +import org.springframework.context.annotation.*; +import org.springframework.core.env.Environment; +import tech.jhipster.config.JHipsterConstants; + +@Configuration +@EnableAspectJAutoProxy +public class LoggingAspectConfiguration { + + @Bean + @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) + public LoggingAspect loggingAspect(Environment env) { + return new LoggingAspect(env); + } +} diff --git a/src/main/java/com/example/questionbank/config/LoggingConfiguration.java b/src/main/java/com/example/questionbank/config/LoggingConfiguration.java new file mode 100644 index 0000000..55a3d01 --- /dev/null +++ b/src/main/java/com/example/questionbank/config/LoggingConfiguration.java @@ -0,0 +1,47 @@ +package com.example.questionbank.config; + +import static tech.jhipster.config.logging.LoggingUtils.*; + +import ch.qos.logback.classic.LoggerContext; +import java.util.HashMap; +import java.util.Map; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import tech.jhipster.config.JHipsterProperties; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; + +/* + * Configures the console and Logstash log appenders from the app properties + */ +@Configuration +public class LoggingConfiguration { + + public LoggingConfiguration( + @Value("${spring.application.name}") String appName, + @Value("${server.port}") String serverPort, + JHipsterProperties jHipsterProperties, + ObjectMapper mapper + ) throws JacksonException { + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + + Map map = new HashMap<>(); + map.put("app_name", appName); + map.put("app_port", serverPort); + var customFields = mapper.writeValueAsString(map); + + var loggingProperties = jHipsterProperties.getLogging(); + var logstashProperties = loggingProperties.getLogstash(); + + if (loggingProperties.isUseJsonFormat()) { + addJsonConsoleAppender(context, customFields); + } + if (logstashProperties.isEnabled()) { + addLogstashTcpSocketAppender(context, customFields, logstashProperties); + } + if (loggingProperties.isUseJsonFormat() || logstashProperties.isEnabled()) { + addContextListener(context, customFields, loggingProperties); + } + } +} diff --git a/src/main/java/com/example/questionbank/config/SecurityConfiguration.java b/src/main/java/com/example/questionbank/config/SecurityConfiguration.java new file mode 100644 index 0000000..80311d6 --- /dev/null +++ b/src/main/java/com/example/questionbank/config/SecurityConfiguration.java @@ -0,0 +1,85 @@ +package com.example.questionbank.config; + +import static org.springframework.security.config.Customizer.withDefaults; + +import com.example.questionbank.security.*; +import com.example.questionbank.web.filter.SpaWebFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint; +import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; +import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; +import tech.jhipster.config.JHipsterProperties; + +@Configuration +@EnableMethodSecurity(securedEnabled = true) +public class SecurityConfiguration { + + private final JHipsterProperties jHipsterProperties; + + public SecurityConfiguration(JHipsterProperties jHipsterProperties) { + this.jHipsterProperties = jHipsterProperties; + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) { + http.cors(withDefaults()) + .csrf(csrf -> csrf.disable()) + .addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class) + .headers(headers -> + headers + .contentSecurityPolicy(csp -> csp.policyDirectives(jHipsterProperties.getSecurity().getContentSecurityPolicy())) + .frameOptions(FrameOptionsConfig::sameOrigin) + .referrerPolicy(referrer -> referrer.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)) + .permissionsPolicyHeader(permissions -> + permissions.policy( + "camera=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=()" + ) + ) + ) + .authorizeHttpRequests(authz -> + // prettier-ignore + authz + .requestMatchers("/index.html", "/*.js", "/*.txt", "/*.json", "/*.map", "/*.css").permitAll() + .requestMatchers("/*.ico", "/*.png", "/*.svg", "/*.webapp").permitAll() + .requestMatchers("/assets/**").permitAll() + .requestMatchers("/swagger-ui/**").permitAll() + .requestMatchers(HttpMethod.POST, "/api/authenticate").permitAll() + .requestMatchers(HttpMethod.GET, "/api/authenticate").permitAll() + .requestMatchers("/api/register").permitAll() + .requestMatchers("/api/activate").permitAll() + .requestMatchers("/api/account/reset-password/init").permitAll() + .requestMatchers("/api/account/reset-password/finish").permitAll() + .requestMatchers("/api/admin/**").hasAuthority(AuthoritiesConstants.ADMIN) + .requestMatchers("/api/**").authenticated() + .requestMatchers("/v3/api-docs/**").hasAuthority(AuthoritiesConstants.ADMIN) + .requestMatchers("/management/health").permitAll() + .requestMatchers("/management/health/**").permitAll() + .requestMatchers("/management/info").permitAll() + .requestMatchers("/management/prometheus").permitAll() + .requestMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN) + ) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .exceptionHandling(exceptions -> + exceptions + .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint()) + .accessDeniedHandler(new BearerTokenAccessDeniedHandler()) + ) + .oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults())); + return http.build(); + } +} diff --git a/src/main/java/com/example/questionbank/config/SecurityJwtConfiguration.java b/src/main/java/com/example/questionbank/config/SecurityJwtConfiguration.java new file mode 100644 index 0000000..9ac20bc --- /dev/null +++ b/src/main/java/com/example/questionbank/config/SecurityJwtConfiguration.java @@ -0,0 +1,62 @@ +package com.example.questionbank.config; + +import static com.example.questionbank.security.SecurityUtils.JWT_ALGORITHM; + +import com.example.questionbank.management.SecurityMetersService; +import com.nimbusds.jose.jwk.source.ImmutableSecret; +import com.nimbusds.jose.util.Base64; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtEncoder; +import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; +import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; + +@Configuration +public class SecurityJwtConfiguration { + + private static final Logger LOG = LoggerFactory.getLogger(SecurityJwtConfiguration.class); + + @Value("${jhipster.security.authentication.jwt.base64-secret}") + private String jwtKey; + + @Bean + public JwtDecoder jwtDecoder(SecurityMetersService metersService) { + NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(getSecretKey()).macAlgorithm(JWT_ALGORITHM).build(); + return token -> { + try { + return jwtDecoder.decode(token); + } catch (Exception e) { + if (e.getMessage().contains("Invalid signature")) { + metersService.trackTokenInvalidSignature(); + } else if (e.getMessage().contains("Jwt expired at")) { + metersService.trackTokenExpired(); + } else if ( + e.getMessage().contains("Invalid JWT serialization") || + e.getMessage().contains("Malformed token") || + e.getMessage().contains("Invalid unsecured/JWS/JWE") + ) { + metersService.trackTokenMalformed(); + } else { + LOG.error("Unknown JWT error {}", e.getMessage()); + } + throw e; + } + }; + } + + @Bean + public JwtEncoder jwtEncoder() { + return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey())); + } + + private SecretKey getSecretKey() { + byte[] keyBytes = Base64.from(jwtKey).decode(); + return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName()); + } +} diff --git a/src/main/java/com/example/questionbank/config/StaticResourcesWebConfiguration.java b/src/main/java/com/example/questionbank/config/StaticResourcesWebConfiguration.java new file mode 100644 index 0000000..0ca6913 --- /dev/null +++ b/src/main/java/com/example/questionbank/config/StaticResourcesWebConfiguration.java @@ -0,0 +1,47 @@ +package com.example.questionbank.config; + +import java.util.concurrent.TimeUnit; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.http.CacheControl; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import tech.jhipster.config.JHipsterConstants; +import tech.jhipster.config.JHipsterProperties; + +@Configuration +@Profile({ JHipsterConstants.SPRING_PROFILE_PRODUCTION }) +public class StaticResourcesWebConfiguration implements WebMvcConfigurer { + + protected static final String[] RESOURCE_LOCATIONS = { "classpath:/static/", "classpath:/static/content/", "classpath:/static/i18n/" }; + protected static final String[] RESOURCE_PATHS = { "/*.js", "/*.css", "/*.svg", "/*.png", "*.ico", "/content/**", "/i18n/*" }; + + private final JHipsterProperties jhipsterProperties; + + public StaticResourcesWebConfiguration(JHipsterProperties jHipsterProperties) { + this.jhipsterProperties = jHipsterProperties; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + ResourceHandlerRegistration resourceHandlerRegistration = appendResourceHandler(registry); + initializeResourceHandler(resourceHandlerRegistration); + } + + protected ResourceHandlerRegistration appendResourceHandler(ResourceHandlerRegistry registry) { + return registry.addResourceHandler(RESOURCE_PATHS); + } + + protected void initializeResourceHandler(ResourceHandlerRegistration resourceHandlerRegistration) { + resourceHandlerRegistration.addResourceLocations(RESOURCE_LOCATIONS).setCacheControl(getCacheControl()); + } + + protected CacheControl getCacheControl() { + return CacheControl.maxAge(getJHipsterHttpCacheProperty(), TimeUnit.DAYS).cachePublic(); + } + + private int getJHipsterHttpCacheProperty() { + return jhipsterProperties.getHttp().getCache().getTimeToLiveInDays(); + } +} diff --git a/src/main/java/com/example/questionbank/config/WebConfigurer.java b/src/main/java/com/example/questionbank/config/WebConfigurer.java new file mode 100644 index 0000000..94fd28c --- /dev/null +++ b/src/main/java/com/example/questionbank/config/WebConfigurer.java @@ -0,0 +1,96 @@ +package com.example.questionbank.config; + +import static java.net.URLDecoder.decode; + +import jakarta.servlet.*; +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.web.server.*; +import org.springframework.boot.web.server.servlet.ConfigurableServletWebServerFactory; +import org.springframework.boot.web.servlet.ServletContextInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.util.CollectionUtils; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; +import tech.jhipster.config.JHipsterProperties; + +/** + * Configuration of web application with Servlet 3.0 APIs. + */ +@Configuration +public class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer { + + private static final Logger LOG = LoggerFactory.getLogger(WebConfigurer.class); + + private final Environment env; + + private final JHipsterProperties jHipsterProperties; + + public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) { + this.env = env; + this.jHipsterProperties = jHipsterProperties; + } + + @Override + public void onStartup(ServletContext servletContext) { + if (env.getActiveProfiles().length != 0) { + LOG.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); + } + + LOG.info("Web application fully configured"); + } + + /** + * Customize the Servlet engine: Mime types, the document root, the cache. + */ + @Override + public void customize(WebServerFactory server) { + // When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets. + setLocationForStaticAssets(server); + } + + private void setLocationForStaticAssets(WebServerFactory server) { + if (server instanceof ConfigurableServletWebServerFactory servletWebServer) { + File root; + String prefixPath = resolvePathPrefix(); + root = Path.of(prefixPath + "target/classes/static/").toFile(); + if (root.exists() && root.isDirectory()) { + servletWebServer.setDocumentRoot(root); + } + } + } + + /** + * Resolve path prefix to static resources. + */ + private String resolvePathPrefix() { + String fullExecutablePath = decode(this.getClass().getResource("").getPath(), StandardCharsets.UTF_8); + String rootPath = Path.of(".").toUri().normalize().getPath(); + String extractedPath = fullExecutablePath.replace(rootPath, ""); + int extractionEndIndex = extractedPath.indexOf("target/"); + if (extractionEndIndex <= 0) { + return ""; + } + return extractedPath.substring(0, extractionEndIndex); + } + + @Bean + public CorsFilter corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration config = jHipsterProperties.getCors(); + if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns())) { + LOG.debug("Registering CORS filter"); + source.registerCorsConfiguration("/api/**", config); + source.registerCorsConfiguration("/management/**", config); + source.registerCorsConfiguration("/v3/api-docs", config); + source.registerCorsConfiguration("/swagger-ui/**", config); + } + return new CorsFilter(source); + } +} diff --git a/src/main/java/com/example/questionbank/config/package-info.java b/src/main/java/com/example/questionbank/config/package-info.java new file mode 100644 index 0000000..02c8e7d --- /dev/null +++ b/src/main/java/com/example/questionbank/config/package-info.java @@ -0,0 +1,4 @@ +/** + * Application configuration. + */ +package com.example.questionbank.config; diff --git a/src/main/java/com/example/questionbank/domain/AbstractAuditingEntity.java b/src/main/java/com/example/questionbank/domain/AbstractAuditingEntity.java new file mode 100644 index 0000000..d30d365 --- /dev/null +++ b/src/main/java/com/example/questionbank/domain/AbstractAuditingEntity.java @@ -0,0 +1,77 @@ +package com.example.questionbank.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import java.io.Serial; +import java.io.Serializable; +import java.time.Instant; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +/** + * Base abstract class for entities which will hold definitions for created, last modified, created by, + * last modified by attributes. + */ +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +@JsonIgnoreProperties(value = { "createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate" }, allowGetters = true) +public abstract class AbstractAuditingEntity implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + public abstract T getId(); + + @CreatedBy + @Column(name = "created_by", nullable = false, length = 50, updatable = false) + private String createdBy; + + @CreatedDate + @Column(name = "created_date", updatable = false) + private Instant createdDate = Instant.now(); + + @LastModifiedBy + @Column(name = "last_modified_by", length = 50) + private String lastModifiedBy; + + @LastModifiedDate + @Column(name = "last_modified_date") + private Instant lastModifiedDate = Instant.now(); + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public Instant getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Instant createdDate) { + this.createdDate = createdDate; + } + + public String getLastModifiedBy() { + return lastModifiedBy; + } + + public void setLastModifiedBy(String lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + public Instant getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(Instant lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } +} diff --git a/src/main/java/com/example/questionbank/domain/Authority.java b/src/main/java/com/example/questionbank/domain/Authority.java new file mode 100644 index 0000000..50718fd --- /dev/null +++ b/src/main/java/com/example/questionbank/domain/Authority.java @@ -0,0 +1,96 @@ +package com.example.questionbank.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.*; +import jakarta.validation.constraints.*; +import java.io.Serial; +import java.io.Serializable; +import java.util.Objects; +import org.springframework.data.domain.Persistable; + +/** + * A Authority. + */ +@Entity +@Table(name = "jhi_authority") +@JsonIgnoreProperties(value = { "new", "id" }) +@SuppressWarnings("common-java:DuplicatedBlocks") +public class Authority implements Serializable, Persistable { + + @Serial + private static final long serialVersionUID = 1L; + + @NotNull + @Size(max = 50) + @Id + @Column(name = "name", length = 50, nullable = false) + private String name; + + @org.springframework.data.annotation.Transient + @Transient + private boolean isPersisted; + + // jhipster-needle-entity-add-field - JHipster will add fields here + + public String getName() { + return this.name; + } + + public Authority name(String name) { + this.setName(name); + return this; + } + + public void setName(String name) { + this.name = name; + } + + @PostLoad + @PostPersist + public void updateEntityState() { + this.setIsPersisted(); + } + + @Override + public String getId() { + return this.name; + } + + @org.springframework.data.annotation.Transient + @Transient + @Override + public boolean isNew() { + return !this.isPersisted; + } + + public Authority setIsPersisted() { + this.isPersisted = true; + return this; + } + + // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Authority)) { + return false; + } + return getName() != null && getName().equals(((Authority) o).getName()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getName()); + } + + // prettier-ignore + @Override + public String toString() { + return "Authority{" + + "name=" + getName() + + "}"; + } +} diff --git a/src/main/java/com/example/questionbank/domain/User.java b/src/main/java/com/example/questionbank/domain/User.java new file mode 100644 index 0000000..578b02a --- /dev/null +++ b/src/main/java/com/example/questionbank/domain/User.java @@ -0,0 +1,231 @@ +package com.example.questionbank.domain; + +import com.example.questionbank.config.Constants; +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import java.io.Serial; +import java.io.Serializable; +import java.time.Instant; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import org.apache.commons.lang3.StringUtils; +import org.hibernate.annotations.BatchSize; + +/** + * A user. + */ +@Entity +@Table(name = "jhi_user") +public class User extends AbstractAuditingEntity implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + @Column(name = "id") + private Long id; + + @NotNull + @Pattern(regexp = Constants.LOGIN_REGEX) + @Size(min = 1, max = 50) + @Column(name = "login", length = 50, unique = true, nullable = false) + private String login; + + @JsonIgnore + @NotNull + @Size(min = 60, max = 60) + @Column(name = "password_hash", length = 60, nullable = false) + private String password; + + @Size(max = 50) + @Column(name = "first_name", length = 50) + private String firstName; + + @Size(max = 50) + @Column(name = "last_name", length = 50) + private String lastName; + + @Email + @Size(min = 5, max = 254) + @Column(name = "email", length = 254, unique = true) + private String email; + + @NotNull + @Column(name = "activated", nullable = false) + private boolean activated = false; + + @Size(min = 2, max = 10) + @Column(name = "lang_key", length = 10) + private String langKey; + + @Size(max = 256) + @Column(name = "image_url", length = 256) + private String imageUrl; + + @Size(max = 20) + @Column(name = "activation_key", length = 20) + @JsonIgnore + private String activationKey; + + @Size(max = 20) + @Column(name = "reset_key", length = 20) + @JsonIgnore + private String resetKey; + + @Column(name = "reset_date") + private Instant resetDate = null; + + @JsonIgnore + @ManyToMany + @JoinTable( + name = "jhi_user_authority", + joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") }, + inverseJoinColumns = { @JoinColumn(name = "authority_name", referencedColumnName = "name") } + ) + @BatchSize(size = 20) + private Set authorities = new HashSet<>(); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + // Lowercase the login before saving it in database + public void setLogin(String login) { + this.login = StringUtils.lowerCase(login, Locale.ENGLISH); + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + public boolean isActivated() { + return activated; + } + + public void setActivated(boolean activated) { + this.activated = activated; + } + + public String getActivationKey() { + return activationKey; + } + + public void setActivationKey(String activationKey) { + this.activationKey = activationKey; + } + + public String getResetKey() { + return resetKey; + } + + public void setResetKey(String resetKey) { + this.resetKey = resetKey; + } + + public Instant getResetDate() { + return resetDate; + } + + public void setResetDate(Instant resetDate) { + this.resetDate = resetDate; + } + + public String getLangKey() { + return langKey; + } + + public void setLangKey(String langKey) { + this.langKey = langKey; + } + + public Set getAuthorities() { + return authorities; + } + + public void setAuthorities(Set authorities) { + this.authorities = authorities; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof User)) { + return false; + } + return id != null && id.equals(((User) o).id); + } + + @Override + public int hashCode() { + // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ + return getClass().hashCode(); + } + + // prettier-ignore + @Override + public String toString() { + return "User{" + + "login='" + login + '\'' + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", email='" + email + '\'' + + ", imageUrl='" + imageUrl + '\'' + + ", activated='" + activated + '\'' + + ", langKey='" + langKey + '\'' + + ", activationKey='" + activationKey + '\'' + + "}"; + } +} diff --git a/src/main/java/com/example/questionbank/domain/package-info.java b/src/main/java/com/example/questionbank/domain/package-info.java new file mode 100644 index 0000000..e0109ff --- /dev/null +++ b/src/main/java/com/example/questionbank/domain/package-info.java @@ -0,0 +1,4 @@ +/** + * Domain objects. + */ +package com.example.questionbank.domain; diff --git a/src/main/java/com/example/questionbank/management/SecurityMetersService.java b/src/main/java/com/example/questionbank/management/SecurityMetersService.java new file mode 100644 index 0000000..6071434 --- /dev/null +++ b/src/main/java/com/example/questionbank/management/SecurityMetersService.java @@ -0,0 +1,50 @@ +package com.example.questionbank.management; + +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.MeterRegistry; +import org.springframework.stereotype.Service; + +@Service +public class SecurityMetersService { + + public static final String INVALID_TOKENS_METER_NAME = "security.authentication.invalid-tokens"; + public static final String INVALID_TOKENS_METER_DESCRIPTION = + "Indicates validation error count of the tokens presented by the clients."; + public static final String INVALID_TOKENS_METER_BASE_UNIT = "errors"; + public static final String INVALID_TOKENS_METER_CAUSE_DIMENSION = "cause"; + + private final Counter tokenInvalidSignatureCounter; + private final Counter tokenExpiredCounter; + private final Counter tokenUnsupportedCounter; + private final Counter tokenMalformedCounter; + + public SecurityMetersService(MeterRegistry registry) { + this.tokenInvalidSignatureCounter = invalidTokensCounterForCauseBuilder("invalid-signature").register(registry); + this.tokenExpiredCounter = invalidTokensCounterForCauseBuilder("expired").register(registry); + this.tokenUnsupportedCounter = invalidTokensCounterForCauseBuilder("unsupported").register(registry); + this.tokenMalformedCounter = invalidTokensCounterForCauseBuilder("malformed").register(registry); + } + + private Counter.Builder invalidTokensCounterForCauseBuilder(String cause) { + return Counter.builder(INVALID_TOKENS_METER_NAME) + .baseUnit(INVALID_TOKENS_METER_BASE_UNIT) + .description(INVALID_TOKENS_METER_DESCRIPTION) + .tag(INVALID_TOKENS_METER_CAUSE_DIMENSION, cause); + } + + public void trackTokenInvalidSignature() { + this.tokenInvalidSignatureCounter.increment(); + } + + public void trackTokenExpired() { + this.tokenExpiredCounter.increment(); + } + + public void trackTokenUnsupported() { + this.tokenUnsupportedCounter.increment(); + } + + public void trackTokenMalformed() { + this.tokenMalformedCounter.increment(); + } +} diff --git a/src/main/java/com/example/questionbank/management/package-info.java b/src/main/java/com/example/questionbank/management/package-info.java new file mode 100644 index 0000000..0522913 --- /dev/null +++ b/src/main/java/com/example/questionbank/management/package-info.java @@ -0,0 +1,4 @@ +/** + * Application management. + */ +package com.example.questionbank.management; diff --git a/src/main/java/com/example/questionbank/package-info.java b/src/main/java/com/example/questionbank/package-info.java new file mode 100644 index 0000000..75b9769 --- /dev/null +++ b/src/main/java/com/example/questionbank/package-info.java @@ -0,0 +1,4 @@ +/** + * Application root. + */ +package com.example.questionbank; diff --git a/src/main/java/com/example/questionbank/repository/AuthorityRepository.java b/src/main/java/com/example/questionbank/repository/AuthorityRepository.java new file mode 100644 index 0000000..2f05981 --- /dev/null +++ b/src/main/java/com/example/questionbank/repository/AuthorityRepository.java @@ -0,0 +1,12 @@ +package com.example.questionbank.repository; + +import com.example.questionbank.domain.Authority; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + +/** + * Spring Data JPA repository for the Authority entity. + */ +@SuppressWarnings("unused") +@Repository +public interface AuthorityRepository extends JpaRepository {} diff --git a/src/main/java/com/example/questionbank/repository/UserRepository.java b/src/main/java/com/example/questionbank/repository/UserRepository.java new file mode 100644 index 0000000..6c92fed --- /dev/null +++ b/src/main/java/com/example/questionbank/repository/UserRepository.java @@ -0,0 +1,34 @@ +package com.example.questionbank.repository; + +import com.example.questionbank.domain.User; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import org.springframework.data.domain.*; +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * Spring Data JPA repository for the {@link User} entity. + */ +@Repository +public interface UserRepository extends JpaRepository { + Optional findOneByActivationKey(String activationKey); + + List findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant dateTime); + + Optional findOneByResetKey(String resetKey); + + Optional findOneByEmailIgnoreCase(String email); + + Optional findOneByLogin(String login); + + @EntityGraph(attributePaths = "authorities") + Optional findOneWithAuthoritiesByLogin(String login); + + @EntityGraph(attributePaths = "authorities") + Optional findOneWithAuthoritiesByEmailIgnoreCase(String email); + + Page findAllByIdNotNullAndActivatedIsTrue(Pageable pageable); +} diff --git a/src/main/java/com/example/questionbank/repository/package-info.java b/src/main/java/com/example/questionbank/repository/package-info.java new file mode 100644 index 0000000..9c1913d --- /dev/null +++ b/src/main/java/com/example/questionbank/repository/package-info.java @@ -0,0 +1,4 @@ +/** + * Repository layer. + */ +package com.example.questionbank.repository; diff --git a/src/main/java/com/example/questionbank/security/AuthoritiesConstants.java b/src/main/java/com/example/questionbank/security/AuthoritiesConstants.java new file mode 100644 index 0000000..39d4b91 --- /dev/null +++ b/src/main/java/com/example/questionbank/security/AuthoritiesConstants.java @@ -0,0 +1,15 @@ +package com.example.questionbank.security; + +/** + * Constants for Spring Security authorities. + */ +public final class AuthoritiesConstants { + + public static final String ADMIN = "ROLE_ADMIN"; + + public static final String USER = "ROLE_USER"; + + public static final String ANONYMOUS = "ROLE_ANONYMOUS"; + + private AuthoritiesConstants() {} +} diff --git a/src/main/java/com/example/questionbank/security/DomainUserDetailsService.java b/src/main/java/com/example/questionbank/security/DomainUserDetailsService.java new file mode 100644 index 0000000..30a008b --- /dev/null +++ b/src/main/java/com/example/questionbank/security/DomainUserDetailsService.java @@ -0,0 +1,90 @@ +package com.example.questionbank.security; + +import com.example.questionbank.domain.Authority; +import com.example.questionbank.domain.User; +import com.example.questionbank.repository.UserRepository; +import java.util.*; +import org.hibernate.validator.internal.constraintvalidators.bv.EmailValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Authenticate a user from the database. + */ +@Service("userDetailsService") +public class DomainUserDetailsService implements UserDetailsService { + + private static final Logger LOG = LoggerFactory.getLogger(DomainUserDetailsService.class); + + private final UserRepository userRepository; + + public DomainUserDetailsService(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @Override + @Transactional(readOnly = true) + public UserDetails loadUserByUsername(final String login) { + LOG.debug("Authenticating {}", login); + + if (new EmailValidator().isValid(login, null)) { + return userRepository + .findOneWithAuthoritiesByEmailIgnoreCase(login) + .map(user -> createSpringSecurityUser(login, user)) + .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database")); + } + + String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); + return userRepository + .findOneWithAuthoritiesByLogin(lowercaseLogin) + .map(user -> createSpringSecurityUser(lowercaseLogin, user)) + .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); + } + + private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { + if (!user.isActivated()) { + throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); + } + return UserWithId.fromUser(user); + } + + public static class UserWithId extends org.springframework.security.core.userdetails.User { + + private final Long id; + + public UserWithId(String login, String password, Collection authorities, Long id) { + super(login, password, authorities); + this.id = id; + } + + public Long getId() { + return id; + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + public static UserWithId fromUser(User user) { + return new UserWithId( + user.getLogin(), + user.getPassword(), + user.getAuthorities().stream().map(Authority::getName).map(SimpleGrantedAuthority::new).toList(), + user.getId() + ); + } + } +} diff --git a/src/main/java/com/example/questionbank/security/SecurityUtils.java b/src/main/java/com/example/questionbank/security/SecurityUtils.java new file mode 100644 index 0000000..9d70c6f --- /dev/null +++ b/src/main/java/com/example/questionbank/security/SecurityUtils.java @@ -0,0 +1,129 @@ +package com.example.questionbank.security; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.oauth2.core.ClaimAccessor; +import org.springframework.security.oauth2.jose.jws.MacAlgorithm; +import org.springframework.security.oauth2.jwt.Jwt; + +/** + * Utility class for Spring Security. + */ +public final class SecurityUtils { + + public static final MacAlgorithm JWT_ALGORITHM = MacAlgorithm.HS512; + + public static final String AUTHORITIES_CLAIM = "auth"; + + public static final String USER_ID_CLAIM = "userId"; + + private SecurityUtils() {} + + /** + * Get the login of the current user. + * + * @return the login of the current user. + */ + public static Optional getCurrentUserLogin() { + SecurityContext securityContext = SecurityContextHolder.getContext(); + return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication())); + } + + private static String extractPrincipal(Authentication authentication) { + // AnonymousAuthenticationToken has a String principal that would fall through below + if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { + return null; + } else if (authentication.getPrincipal() instanceof UserDetails springSecurityUser) { + return springSecurityUser.getUsername(); + } else if (authentication.getPrincipal() instanceof Jwt jwt) { + return jwt.getSubject(); + } else if (authentication.getPrincipal() instanceof String s) { + return s; + } + return null; + } + + /** + * Get the JWT of the current user. + * + * @return the JWT of the current user. + */ + public static Optional getCurrentUserJWT() { + SecurityContext securityContext = SecurityContextHolder.getContext(); + return Optional.ofNullable(securityContext.getAuthentication()).map(SecurityUtils::extractCredentials); + } + + private static String extractCredentials(Authentication authentication) { + if (authentication.getCredentials() instanceof String token) { + return token; + } else if (authentication.getCredentials() instanceof Jwt jwt) { + return jwt.getTokenValue(); + } + return null; + } + + /** + * Get the Id of the current user. + * + * @return the Id of the current user. + */ + public static Optional getCurrentUserId() { + SecurityContext securityContext = SecurityContextHolder.getContext(); + return Optional.ofNullable(securityContext.getAuthentication()) + .filter(authentication -> authentication.getPrincipal() instanceof ClaimAccessor) + .map(authentication -> (ClaimAccessor) authentication.getPrincipal()) + .map(principal -> principal.getClaim(USER_ID_CLAIM)); + } + + /** + * Check if a user is authenticated. + * + * @return true if the user is authenticated, false otherwise. + */ + public static boolean isAuthenticated() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + return authentication != null && getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals); + } + + /** + * Checks if the current user has any of the authorities. + * + * @param authorities the authorities to check. + * @return true if the current user has any of the authorities, false otherwise. + */ + public static boolean hasCurrentUserAnyOfAuthorities(String... authorities) { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + return authentication != null && getAuthorities(authentication).anyMatch(authority -> List.of(authorities).contains(authority)); + } + + /** + * Checks if the current user has none of the authorities. + * + * @param authorities the authorities to check. + * @return true if the current user has none of the authorities, false otherwise. + */ + public static boolean hasCurrentUserNoneOfAuthorities(String... authorities) { + return !hasCurrentUserAnyOfAuthorities(authorities); + } + + /** + * Checks if the current user has a specific authority. + * + * @param authority the authority to check. + * @return true if the current user has the authority, false otherwise. + */ + public static boolean hasCurrentUserThisAuthority(String authority) { + return hasCurrentUserAnyOfAuthorities(authority); + } + + private static Stream getAuthorities(Authentication authentication) { + return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority); + } +} diff --git a/src/main/java/com/example/questionbank/security/SpringSecurityAuditorAware.java b/src/main/java/com/example/questionbank/security/SpringSecurityAuditorAware.java new file mode 100644 index 0000000..17022a4 --- /dev/null +++ b/src/main/java/com/example/questionbank/security/SpringSecurityAuditorAware.java @@ -0,0 +1,18 @@ +package com.example.questionbank.security; + +import com.example.questionbank.config.Constants; +import java.util.Optional; +import org.springframework.data.domain.AuditorAware; +import org.springframework.stereotype.Component; + +/** + * Implementation of {@link AuditorAware} based on Spring Security. + */ +@Component +public class SpringSecurityAuditorAware implements AuditorAware { + + @Override + public Optional getCurrentAuditor() { + return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM)); + } +} diff --git a/src/main/java/com/example/questionbank/security/UserNotActivatedException.java b/src/main/java/com/example/questionbank/security/UserNotActivatedException.java new file mode 100644 index 0000000..bef9bba --- /dev/null +++ b/src/main/java/com/example/questionbank/security/UserNotActivatedException.java @@ -0,0 +1,21 @@ +package com.example.questionbank.security; + +import java.io.Serial; +import org.springframework.security.core.AuthenticationException; + +/** + * This exception is thrown in case of a not activated user trying to authenticate. + */ +public class UserNotActivatedException extends AuthenticationException { + + @Serial + private static final long serialVersionUID = 1L; + + public UserNotActivatedException(String message) { + super(message); + } + + public UserNotActivatedException(String message, Throwable t) { + super(message, t); + } +} diff --git a/src/main/java/com/example/questionbank/security/package-info.java b/src/main/java/com/example/questionbank/security/package-info.java new file mode 100644 index 0000000..00cd602 --- /dev/null +++ b/src/main/java/com/example/questionbank/security/package-info.java @@ -0,0 +1,4 @@ +/** + * Application security utilities. + */ +package com.example.questionbank.security; diff --git a/src/main/java/com/example/questionbank/service/EmailAlreadyUsedException.java b/src/main/java/com/example/questionbank/service/EmailAlreadyUsedException.java new file mode 100644 index 0000000..e87c8de --- /dev/null +++ b/src/main/java/com/example/questionbank/service/EmailAlreadyUsedException.java @@ -0,0 +1,13 @@ +package com.example.questionbank.service; + +import java.io.Serial; + +public class EmailAlreadyUsedException extends RuntimeException { + + @Serial + private static final long serialVersionUID = 1L; + + public EmailAlreadyUsedException() { + super("Email is already in use!"); + } +} diff --git a/src/main/java/com/example/questionbank/service/InvalidPasswordException.java b/src/main/java/com/example/questionbank/service/InvalidPasswordException.java new file mode 100644 index 0000000..1a99981 --- /dev/null +++ b/src/main/java/com/example/questionbank/service/InvalidPasswordException.java @@ -0,0 +1,13 @@ +package com.example.questionbank.service; + +import java.io.Serial; + +public class InvalidPasswordException extends RuntimeException { + + @Serial + private static final long serialVersionUID = 1L; + + public InvalidPasswordException() { + super("Incorrect password"); + } +} diff --git a/src/main/java/com/example/questionbank/service/MailService.java b/src/main/java/com/example/questionbank/service/MailService.java new file mode 100644 index 0000000..a013ebc --- /dev/null +++ b/src/main/java/com/example/questionbank/service/MailService.java @@ -0,0 +1,120 @@ +package com.example.questionbank.service; + +import com.example.questionbank.domain.User; +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; +import java.nio.charset.StandardCharsets; +import java.util.Locale; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.MessageSource; +import org.springframework.mail.MailException; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.thymeleaf.context.Context; +import org.thymeleaf.spring6.SpringTemplateEngine; +import tech.jhipster.config.JHipsterProperties; + +/** + * Service for sending emails asynchronously. + *

+ * We use the {@link Async} annotation to send emails asynchronously. + */ +@Service +public class MailService { + + private static final Logger LOG = LoggerFactory.getLogger(MailService.class); + + private static final String USER = "user"; + + private static final String BASE_URL = "baseUrl"; + + private final JHipsterProperties jHipsterProperties; + + private final JavaMailSender javaMailSender; + + private final MessageSource messageSource; + + private final SpringTemplateEngine templateEngine; + + public MailService( + JHipsterProperties jHipsterProperties, + JavaMailSender javaMailSender, + MessageSource messageSource, + SpringTemplateEngine templateEngine + ) { + this.jHipsterProperties = jHipsterProperties; + this.javaMailSender = javaMailSender; + this.messageSource = messageSource; + this.templateEngine = templateEngine; + } + + @Async + public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { + sendEmailSync(to, subject, content, isMultipart, isHtml); + } + + private void sendEmailSync(String to, String subject, String content, boolean isMultipart, boolean isHtml) { + LOG.debug( + "Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", + isMultipart, + isHtml, + to, + subject, + content + ); + + // Prepare message using a Spring helper + MimeMessage mimeMessage = javaMailSender.createMimeMessage(); + try { + MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name()); + message.setTo(to); + message.setFrom(jHipsterProperties.getMail().getFrom()); + message.setSubject(subject); + message.setText(content, isHtml); + javaMailSender.send(mimeMessage); + LOG.debug("Sent email to User '{}'", to); + } catch (MailException | MessagingException e) { + LOG.warn("Email could not be sent to user '{}'", to, e); + } + } + + @Async + public void sendEmailFromTemplate(User user, String templateName, String titleKey) { + sendEmailFromTemplateSync(user, templateName, titleKey); + } + + private void sendEmailFromTemplateSync(User user, String templateName, String titleKey) { + if (user.getEmail() == null) { + LOG.debug("Email doesn't exist for user '{}'", user.getLogin()); + return; + } + Locale locale = Locale.forLanguageTag(user.getLangKey()); + Context context = new Context(locale); + context.setVariable(USER, user); + context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); + String content = templateEngine.process(templateName, context); + String subject = messageSource.getMessage(titleKey, null, locale); + sendEmailSync(user.getEmail(), subject, content, false, true); + } + + @Async + public void sendActivationEmail(User user) { + LOG.debug("Sending activation email to '{}'", user.getEmail()); + sendEmailFromTemplateSync(user, "mail/activationEmail", "email.activation.title"); + } + + @Async + public void sendCreationEmail(User user) { + LOG.debug("Sending creation email to '{}'", user.getEmail()); + sendEmailFromTemplateSync(user, "mail/creationEmail", "email.activation.title"); + } + + @Async + public void sendPasswordResetMail(User user) { + LOG.debug("Sending password reset email to '{}'", user.getEmail()); + sendEmailFromTemplateSync(user, "mail/passwordResetEmail", "email.reset.title"); + } +} diff --git a/src/main/java/com/example/questionbank/service/UserService.java b/src/main/java/com/example/questionbank/service/UserService.java new file mode 100644 index 0000000..4b596d8 --- /dev/null +++ b/src/main/java/com/example/questionbank/service/UserService.java @@ -0,0 +1,288 @@ +package com.example.questionbank.service; + +import com.example.questionbank.config.Constants; +import com.example.questionbank.domain.Authority; +import com.example.questionbank.domain.User; +import com.example.questionbank.repository.AuthorityRepository; +import com.example.questionbank.repository.UserRepository; +import com.example.questionbank.security.AuthoritiesConstants; +import com.example.questionbank.security.SecurityUtils; +import com.example.questionbank.service.dto.AdminUserDTO; +import com.example.questionbank.service.dto.UserDTO; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import tech.jhipster.security.RandomUtil; + +/** + * Service class for managing users. + */ +@Service +@Transactional +public class UserService { + + private static final Logger LOG = LoggerFactory.getLogger(UserService.class); + + private final UserRepository userRepository; + + private final PasswordEncoder passwordEncoder; + + private final AuthorityRepository authorityRepository; + + public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository) { + this.userRepository = userRepository; + this.passwordEncoder = passwordEncoder; + this.authorityRepository = authorityRepository; + } + + public Optional activateRegistration(String key) { + LOG.debug("Activating user for activation key {}", key); + return userRepository.findOneByActivationKey(key).map(user -> { + // activate given user for the registration key. + user.setActivated(true); + user.setActivationKey(null); + LOG.debug("Activated user: {}", user); + return user; + }); + } + + public Optional completePasswordReset(String newPassword, String key) { + LOG.debug("Reset user password for reset key {}", key); + return userRepository + .findOneByResetKey(key) + .filter(user -> user.getResetDate().isAfter(Instant.now().minus(1, ChronoUnit.DAYS))) + .map(user -> { + user.setPassword(passwordEncoder.encode(newPassword)); + user.setResetKey(null); + user.setResetDate(null); + return user; + }); + } + + public Optional requestPasswordReset(String mail) { + return userRepository + .findOneByEmailIgnoreCase(mail) + .filter(User::isActivated) + .map(user -> { + user.setResetKey(RandomUtil.generateResetKey()); + user.setResetDate(Instant.now()); + return user; + }); + } + + public User registerUser(AdminUserDTO userDTO, String password) { + userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).ifPresent(existingUser -> { + boolean removed = removeNonActivatedUser(existingUser); + if (!removed) { + throw new UsernameAlreadyUsedException(); + } + }); + userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).ifPresent(existingUser -> { + boolean removed = removeNonActivatedUser(existingUser); + if (!removed) { + throw new EmailAlreadyUsedException(); + } + }); + User newUser = new User(); + String encryptedPassword = passwordEncoder.encode(password); + newUser.setLogin(userDTO.getLogin().toLowerCase()); + // new user gets initially a generated password + newUser.setPassword(encryptedPassword); + newUser.setFirstName(userDTO.getFirstName()); + newUser.setLastName(userDTO.getLastName()); + if (userDTO.getEmail() != null) { + newUser.setEmail(userDTO.getEmail().toLowerCase()); + } + newUser.setImageUrl(userDTO.getImageUrl()); + newUser.setLangKey(userDTO.getLangKey()); + // new user is not active + newUser.setActivated(false); + // new user gets registration key + newUser.setActivationKey(RandomUtil.generateActivationKey()); + Set authorities = new HashSet<>(); + authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add); + newUser.setAuthorities(authorities); + userRepository.save(newUser); + LOG.debug("Created Information for User: {}", newUser); + return newUser; + } + + private boolean removeNonActivatedUser(User existingUser) { + if (existingUser.isActivated()) { + return false; + } + userRepository.delete(existingUser); + userRepository.flush(); + return true; + } + + public User createUser(AdminUserDTO userDTO) { + User user = new User(); + user.setLogin(userDTO.getLogin().toLowerCase()); + user.setFirstName(userDTO.getFirstName()); + user.setLastName(userDTO.getLastName()); + if (userDTO.getEmail() != null) { + user.setEmail(userDTO.getEmail().toLowerCase()); + } + user.setImageUrl(userDTO.getImageUrl()); + if (userDTO.getLangKey() == null) { + user.setLangKey(Constants.DEFAULT_LANGUAGE); // default language + } else { + user.setLangKey(userDTO.getLangKey()); + } + String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword()); + user.setPassword(encryptedPassword); + user.setResetKey(RandomUtil.generateResetKey()); + user.setResetDate(Instant.now()); + user.setActivated(true); + if (userDTO.getAuthorities() != null) { + Set authorities = userDTO + .getAuthorities() + .stream() + .map(authorityRepository::findById) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toSet()); + user.setAuthorities(authorities); + } + userRepository.save(user); + LOG.debug("Created Information for User: {}", user); + return user; + } + + /** + * Update all information for a specific user, and return the modified user. + * + * @param userDTO user to update. + * @return updated user. + */ + public Optional updateUser(AdminUserDTO userDTO) { + return Optional.of(userRepository.findById(userDTO.getId())) + .filter(Optional::isPresent) + .map(Optional::get) + .map(user -> { + user.setLogin(userDTO.getLogin().toLowerCase()); + user.setFirstName(userDTO.getFirstName()); + user.setLastName(userDTO.getLastName()); + if (userDTO.getEmail() != null) { + user.setEmail(userDTO.getEmail().toLowerCase()); + } + user.setImageUrl(userDTO.getImageUrl()); + user.setActivated(userDTO.isActivated()); + user.setLangKey(userDTO.getLangKey()); + Set managedAuthorities = user.getAuthorities(); + managedAuthorities.clear(); + userDTO + .getAuthorities() + .stream() + .map(authorityRepository::findById) + .filter(Optional::isPresent) + .map(Optional::get) + .forEach(managedAuthorities::add); + userRepository.save(user); + LOG.debug("Changed Information for User: {}", user); + return user; + }) + .map(AdminUserDTO::new); + } + + public void deleteUser(String login) { + userRepository.findOneByLogin(login).ifPresent(user -> { + userRepository.delete(user); + LOG.debug("Deleted User: {}", user); + }); + } + + /** + * Update basic information (first name, last name, email, language) for the current user. + * + * @param firstName first name of user. + * @param lastName last name of user. + * @param email email id of user. + * @param langKey language key. + * @param imageUrl image URL of user. + */ + public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) { + SecurityUtils.getCurrentUserLogin() + .flatMap(userRepository::findOneByLogin) + .ifPresent(user -> { + user.setFirstName(firstName); + user.setLastName(lastName); + if (email != null) { + user.setEmail(email.toLowerCase()); + } + user.setLangKey(langKey); + user.setImageUrl(imageUrl); + userRepository.save(user); + LOG.debug("Changed Information for User: {}", user); + }); + } + + @Transactional + public void changePassword(String currentClearTextPassword, String newPassword) { + SecurityUtils.getCurrentUserLogin() + .flatMap(userRepository::findOneByLogin) + .ifPresent(user -> { + String currentEncryptedPassword = user.getPassword(); + if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) { + throw new InvalidPasswordException(); + } + String encryptedPassword = passwordEncoder.encode(newPassword); + user.setPassword(encryptedPassword); + LOG.debug("Changed password for User: {}", user); + }); + } + + @Transactional(readOnly = true) + public Page getAllManagedUsers(Pageable pageable) { + return userRepository.findAll(pageable).map(AdminUserDTO::new); + } + + @Transactional(readOnly = true) + public Page getAllPublicUsers(Pageable pageable) { + return userRepository.findAllByIdNotNullAndActivatedIsTrue(pageable).map(UserDTO::new); + } + + @Transactional(readOnly = true) + public Optional getUserWithAuthoritiesByLogin(String login) { + return userRepository.findOneWithAuthoritiesByLogin(login); + } + + @Transactional(readOnly = true) + public Optional getUserWithAuthorities() { + return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin); + } + + /** + * Not activated users should be automatically deleted after 3 days. + *

+ * This is scheduled to get fired every day, at 01:00 (am). + */ + @Scheduled(cron = "0 0 1 * * ?") + public void removeNotActivatedUsers() { + userRepository + .findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) + .forEach(user -> { + LOG.debug("Deleting not activated user {}", user.getLogin()); + userRepository.delete(user); + }); + } + + /** + * Gets a list of all the authorities. + * @return a list of all the authorities. + */ + @Transactional(readOnly = true) + public List getAuthorities() { + return authorityRepository.findAll().stream().map(Authority::getName).toList(); + } +} diff --git a/src/main/java/com/example/questionbank/service/UsernameAlreadyUsedException.java b/src/main/java/com/example/questionbank/service/UsernameAlreadyUsedException.java new file mode 100644 index 0000000..07993d3 --- /dev/null +++ b/src/main/java/com/example/questionbank/service/UsernameAlreadyUsedException.java @@ -0,0 +1,13 @@ +package com.example.questionbank.service; + +import java.io.Serial; + +public class UsernameAlreadyUsedException extends RuntimeException { + + @Serial + private static final long serialVersionUID = 1L; + + public UsernameAlreadyUsedException() { + super("Login name already used!"); + } +} diff --git a/src/main/java/com/example/questionbank/service/dto/AdminUserDTO.java b/src/main/java/com/example/questionbank/service/dto/AdminUserDTO.java new file mode 100644 index 0000000..91c0cad --- /dev/null +++ b/src/main/java/com/example/questionbank/service/dto/AdminUserDTO.java @@ -0,0 +1,198 @@ +package com.example.questionbank.service.dto; + +import com.example.questionbank.config.Constants; +import com.example.questionbank.domain.Authority; +import com.example.questionbank.domain.User; +import jakarta.validation.constraints.*; +import java.io.Serial; +import java.io.Serializable; +import java.time.Instant; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * A DTO representing a user, with his authorities. + */ +public class AdminUserDTO implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + private Long id; + + @NotBlank + @Pattern(regexp = Constants.LOGIN_REGEX) + @Size(min = 1, max = 50) + private String login; + + @Size(max = 50) + private String firstName; + + @Size(max = 50) + private String lastName; + + @Email + @Size(min = 5, max = 254) + private String email; + + @Size(max = 256) + private String imageUrl; + + private boolean activated = false; + + @Size(min = 2, max = 10) + private String langKey; + + private String createdBy; + + private Instant createdDate; + + private String lastModifiedBy; + + private Instant lastModifiedDate; + + private Set authorities; + + public AdminUserDTO() { + // Empty constructor needed for Jackson. + } + + public AdminUserDTO(User user) { + this.id = user.getId(); + this.login = user.getLogin(); + this.firstName = user.getFirstName(); + this.lastName = user.getLastName(); + this.email = user.getEmail(); + this.activated = user.isActivated(); + this.imageUrl = user.getImageUrl(); + this.langKey = user.getLangKey(); + this.createdBy = user.getCreatedBy(); + this.createdDate = user.getCreatedDate(); + this.lastModifiedBy = user.getLastModifiedBy(); + this.lastModifiedDate = user.getLastModifiedDate(); + this.authorities = user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toSet()); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + public boolean isActivated() { + return activated; + } + + public void setActivated(boolean activated) { + this.activated = activated; + } + + public String getLangKey() { + return langKey; + } + + public void setLangKey(String langKey) { + this.langKey = langKey; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public Instant getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Instant createdDate) { + this.createdDate = createdDate; + } + + public String getLastModifiedBy() { + return lastModifiedBy; + } + + public void setLastModifiedBy(String lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + public Instant getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(Instant lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } + + public Set getAuthorities() { + return authorities; + } + + public void setAuthorities(Set authorities) { + this.authorities = authorities; + } + + // prettier-ignore + @Override + public String toString() { + return "AdminUserDTO{" + + "login='" + login + '\'' + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", email='" + email + '\'' + + ", imageUrl='" + imageUrl + '\'' + + ", activated=" + activated + + ", langKey='" + langKey + '\'' + + ", createdBy=" + createdBy + + ", createdDate=" + createdDate + + ", lastModifiedBy='" + lastModifiedBy + '\'' + + ", lastModifiedDate=" + lastModifiedDate + + ", authorities=" + authorities + + "}"; + } +} diff --git a/src/main/java/com/example/questionbank/service/dto/PasswordChangeDTO.java b/src/main/java/com/example/questionbank/service/dto/PasswordChangeDTO.java new file mode 100644 index 0000000..0c0a992 --- /dev/null +++ b/src/main/java/com/example/questionbank/service/dto/PasswordChangeDTO.java @@ -0,0 +1,41 @@ +package com.example.questionbank.service.dto; + +import java.io.Serial; +import java.io.Serializable; + +/** + * A DTO representing a password change required data - current and new password. + */ +public class PasswordChangeDTO implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + private String currentPassword; + private String newPassword; + + public PasswordChangeDTO() { + // Empty constructor needed for Jackson. + } + + public PasswordChangeDTO(String currentPassword, String newPassword) { + this.currentPassword = currentPassword; + this.newPassword = newPassword; + } + + public String getCurrentPassword() { + return currentPassword; + } + + public void setCurrentPassword(String currentPassword) { + this.currentPassword = currentPassword; + } + + public String getNewPassword() { + return newPassword; + } + + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } +} diff --git a/src/main/java/com/example/questionbank/service/dto/UserDTO.java b/src/main/java/com/example/questionbank/service/dto/UserDTO.java new file mode 100644 index 0000000..7319d84 --- /dev/null +++ b/src/main/java/com/example/questionbank/service/dto/UserDTO.java @@ -0,0 +1,76 @@ +package com.example.questionbank.service.dto; + +import com.example.questionbank.domain.User; +import java.io.Serial; +import java.io.Serializable; +import java.util.Objects; + +/** + * A DTO representing a user, with only the public attributes. + */ +public class UserDTO implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + private Long id; + + private String login; + + public UserDTO() { + // Empty constructor needed for Jackson. + } + + public UserDTO(User user) { + this.id = user.getId(); + // Customize it here if you need, or not, firstName/lastName/etc + this.login = user.getLogin(); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + UserDTO userDTO = (UserDTO) o; + if (userDTO.getId() == null || getId() == null) { + return false; + } + + return Objects.equals(getId(), userDTO.getId()) && Objects.equals(getLogin(), userDTO.getLogin()); + } + + @Override + public int hashCode() { + return Objects.hash(getId(), getLogin()); + } + + // prettier-ignore + @Override + public String toString() { + return "UserDTO{" + + "id='" + id + '\'' + + ", login='" + login + '\'' + + "}"; + } +} diff --git a/src/main/java/com/example/questionbank/service/dto/package-info.java b/src/main/java/com/example/questionbank/service/dto/package-info.java new file mode 100644 index 0000000..8bcb931 --- /dev/null +++ b/src/main/java/com/example/questionbank/service/dto/package-info.java @@ -0,0 +1,4 @@ +/** + * Data transfer objects for rest mapping. + */ +package com.example.questionbank.service.dto; diff --git a/src/main/java/com/example/questionbank/service/mapper/UserMapper.java b/src/main/java/com/example/questionbank/service/mapper/UserMapper.java new file mode 100644 index 0000000..ca0ded3 --- /dev/null +++ b/src/main/java/com/example/questionbank/service/mapper/UserMapper.java @@ -0,0 +1,150 @@ +package com.example.questionbank.service.mapper; + +import com.example.questionbank.domain.Authority; +import com.example.questionbank.domain.User; +import com.example.questionbank.service.dto.AdminUserDTO; +import com.example.questionbank.service.dto.UserDTO; +import java.util.*; +import java.util.stream.Collectors; +import org.mapstruct.BeanMapping; +import org.mapstruct.Mapping; +import org.mapstruct.Named; +import org.springframework.stereotype.Service; + +/** + * Mapper for the entity {@link User} and its DTO called {@link UserDTO}. + * + * Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct + * support is still in beta, and requires a manual step with an IDE. + */ +@Service +public class UserMapper { + + public List usersToUserDTOs(List users) { + return users.stream().filter(Objects::nonNull).map(this::userToUserDTO).toList(); + } + + public UserDTO userToUserDTO(User user) { + return new UserDTO(user); + } + + public List usersToAdminUserDTOs(List users) { + return users.stream().filter(Objects::nonNull).map(this::userToAdminUserDTO).toList(); + } + + public AdminUserDTO userToAdminUserDTO(User user) { + return new AdminUserDTO(user); + } + + public List userDTOsToUsers(List userDTOs) { + return userDTOs.stream().filter(Objects::nonNull).map(this::userDTOToUser).toList(); + } + + public User userDTOToUser(AdminUserDTO userDTO) { + if (userDTO == null) { + return null; + } else { + User user = new User(); + user.setId(userDTO.getId()); + user.setLogin(userDTO.getLogin()); + user.setFirstName(userDTO.getFirstName()); + user.setLastName(userDTO.getLastName()); + user.setEmail(userDTO.getEmail()); + user.setImageUrl(userDTO.getImageUrl()); + user.setCreatedBy(userDTO.getCreatedBy()); + user.setCreatedDate(userDTO.getCreatedDate()); + user.setLastModifiedBy(userDTO.getLastModifiedBy()); + user.setLastModifiedDate(userDTO.getLastModifiedDate()); + user.setActivated(userDTO.isActivated()); + user.setLangKey(userDTO.getLangKey()); + Set authorities = this.authoritiesFromStrings(userDTO.getAuthorities()); + user.setAuthorities(authorities); + return user; + } + } + + private Set authoritiesFromStrings(Set authoritiesAsString) { + Set authorities = new HashSet<>(); + + if (authoritiesAsString != null) { + authorities = authoritiesAsString + .stream() + .map(string -> { + Authority auth = new Authority(); + auth.setName(string); + return auth; + }) + .collect(Collectors.toSet()); + } + + return authorities; + } + + public User userFromId(Long id) { + if (id == null) { + return null; + } + User user = new User(); + user.setId(id); + return user; + } + + @Named("id") + @BeanMapping(ignoreByDefault = true) + @Mapping(target = "id", source = "id") + public UserDTO toDtoId(User user) { + if (user == null) { + return null; + } + UserDTO userDto = new UserDTO(); + userDto.setId(user.getId()); + return userDto; + } + + @Named("idSet") + @BeanMapping(ignoreByDefault = true) + @Mapping(target = "id", source = "id") + public Set toDtoIdSet(Set users) { + if (users == null) { + return Set.of(); + } + + Set userSet = new HashSet<>(); + for (User userEntity : users) { + userSet.add(this.toDtoId(userEntity)); + } + + return userSet; + } + + @Named("login") + @BeanMapping(ignoreByDefault = true) + @Mapping(target = "id", source = "id") + @Mapping(target = "login", source = "login") + public UserDTO toDtoLogin(User user) { + if (user == null) { + return null; + } + UserDTO userDto = new UserDTO(); + userDto.setId(user.getId()); + userDto.setLogin(user.getLogin()); + return userDto; + } + + @Named("loginSet") + @BeanMapping(ignoreByDefault = true) + @Mapping(target = "id", source = "id") + @Mapping(target = "login", source = "login") + public Set toDtoLoginSet(Set users) { + if (users == null) { + return Set.of(); + } + + Set userSet = new HashSet<>(); + for (User userEntity : users) { + userSet.add(this.toDtoLogin(userEntity)); + } + + return userSet; + } +} diff --git a/src/main/java/com/example/questionbank/service/mapper/package-info.java b/src/main/java/com/example/questionbank/service/mapper/package-info.java new file mode 100644 index 0000000..2c345af --- /dev/null +++ b/src/main/java/com/example/questionbank/service/mapper/package-info.java @@ -0,0 +1,4 @@ +/** + * Data transfer objects mappers. + */ +package com.example.questionbank.service.mapper; diff --git a/src/main/java/com/example/questionbank/service/package-info.java b/src/main/java/com/example/questionbank/service/package-info.java new file mode 100644 index 0000000..69637a5 --- /dev/null +++ b/src/main/java/com/example/questionbank/service/package-info.java @@ -0,0 +1,4 @@ +/** + * Service layer. + */ +package com.example.questionbank.service; diff --git a/src/main/java/com/example/questionbank/web/filter/SpaWebFilter.java b/src/main/java/com/example/questionbank/web/filter/SpaWebFilter.java new file mode 100644 index 0000000..83b4c94 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/filter/SpaWebFilter.java @@ -0,0 +1,33 @@ +package com.example.questionbank.web.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import org.springframework.web.filter.OncePerRequestFilter; + +public class SpaWebFilter extends OncePerRequestFilter { + + /** + * Forwards any unmapped paths (except those containing a period) to the client {@code index.html}. + */ + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + // Request URI includes the contextPath if any, removed it. + String path = request.getRequestURI().substring(request.getContextPath().length()); + if ( + !path.startsWith("/api") && + !path.startsWith("/management") && + !path.startsWith("/v3/api-docs") && + !path.contains(".") && + path.matches("/(.*)") + ) { + request.getRequestDispatcher("/index.html").forward(request, response); + return; + } + + filterChain.doFilter(request, response); + } +} diff --git a/src/main/java/com/example/questionbank/web/filter/package-info.java b/src/main/java/com/example/questionbank/web/filter/package-info.java new file mode 100644 index 0000000..2ca428e --- /dev/null +++ b/src/main/java/com/example/questionbank/web/filter/package-info.java @@ -0,0 +1,4 @@ +/** + * Request chain filters. + */ +package com.example.questionbank.web.filter; diff --git a/src/main/java/com/example/questionbank/web/rest/AccountResource.java b/src/main/java/com/example/questionbank/web/rest/AccountResource.java new file mode 100644 index 0000000..657ffd9 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/AccountResource.java @@ -0,0 +1,204 @@ +package com.example.questionbank.web.rest; + +import com.example.questionbank.domain.User; +import com.example.questionbank.repository.UserRepository; +import com.example.questionbank.security.SecurityUtils; +import com.example.questionbank.service.MailService; +import com.example.questionbank.service.UserService; +import com.example.questionbank.service.dto.AdminUserDTO; +import com.example.questionbank.service.dto.PasswordChangeDTO; +import com.example.questionbank.web.rest.errors.*; +import com.example.questionbank.web.rest.vm.KeyAndPasswordVM; +import com.example.questionbank.web.rest.vm.ManagedUserVM; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.Size; +import java.util.*; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +/** + * REST controller for managing the current user's account. + */ +@RestController +@RequestMapping("/api") +@Validated +public class AccountResource { + + @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Account resource request invalid") + private static class AccountResourceException extends RuntimeException { + + private AccountResourceException(String message) { + super(message); + } + } + + private static final Logger LOG = LoggerFactory.getLogger(AccountResource.class); + + private final UserRepository userRepository; + + private final UserService userService; + + private final MailService mailService; + + private final PasswordEncoder passwordEncoder; + + public AccountResource( + UserRepository userRepository, + UserService userService, + MailService mailService, + PasswordEncoder passwordEncoder + ) { + this.userRepository = userRepository; + this.userService = userService; + this.mailService = mailService; + this.passwordEncoder = passwordEncoder; + } + + /** + * {@code POST /register} : register the user. + * + * @param managedUserVM the managed user View Model. + * @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect. + * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used. + * @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already used. + */ + @PostMapping("/register") + @ResponseStatus(HttpStatus.CREATED) + public void registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) { + LOG.debug("REST request to register account"); + if (isPasswordLengthInvalid(managedUserVM.getPassword())) { + throw new InvalidPasswordException(); + } + User user = userService.registerUser(managedUserVM, managedUserVM.getPassword()); + mailService.sendActivationEmail(user); + } + + /** + * {@code GET /activate} : activate the registered user. + * + * @param key the activation key. + * @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be activated. + */ + @GetMapping("/activate") + public void activateAccount(@RequestParam(value = "key") String key) { + LOG.debug("REST request to activate account"); + Optional user = userService.activateRegistration(key); + if (user.isEmpty()) { + throw new AccountResourceException("No user was found for this activation key"); + } + } + + /** + * {@code GET /account} : get the current user. + * + * @return the current user. + * @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be returned. + */ + @GetMapping("/account") + public AdminUserDTO getAccount() { + LOG.debug("REST request to get account"); + return userService + .getUserWithAuthorities() + .map(AdminUserDTO::new) + .orElseThrow(() -> new AccountResourceException("User could not be found")); + } + + /** + * {@code POST /account} : update the current user information. + * + * @param userDTO the current user information. + * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used. + * @throws RuntimeException {@code 500 (Internal Server Error)} if the user login wasn't found. + */ + @PostMapping("/account") + public void saveAccount(@Valid @RequestBody AdminUserDTO userDTO) { + LOG.debug("REST request to save account"); + String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> + new AccountResourceException("Current user login not found") + ); + Optional existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); + if (existingUser.isPresent() && !existingUser.orElseThrow().getLogin().equalsIgnoreCase(userLogin)) { + throw new EmailAlreadyUsedException(); + } + Optional user = userRepository.findOneByLogin(userLogin); + if (user.isEmpty()) { + throw new AccountResourceException("User could not be found"); + } + userService.updateUser( + userDTO.getFirstName(), + userDTO.getLastName(), + userDTO.getEmail(), + userDTO.getLangKey(), + userDTO.getImageUrl() + ); + } + + /** + * {@code POST /account/change-password} : changes the current user's password. + * + * @param passwordChangeDto current and new password. + * @throws InvalidPasswordException {@code 400 (Bad Request)} if the new password is incorrect. + */ + @PostMapping(path = "/account/change-password") + public void changePassword(@RequestBody PasswordChangeDTO passwordChangeDto) { + LOG.debug("REST request to change password"); + if (isPasswordLengthInvalid(passwordChangeDto.getNewPassword())) { + throw new InvalidPasswordException(); + } + userService.changePassword(passwordChangeDto.getCurrentPassword(), passwordChangeDto.getNewPassword()); + } + + /** + * {@code POST /account/reset-password/init} : Send an email to reset the password of the user. + * + * @param mail the mail of the user. + */ + @PostMapping(path = "/account/reset-password/init") + public void requestPasswordReset(@RequestBody @Email @Size(min = 5, max = 254) String mail) { + LOG.debug("REST request to request password reset"); + Optional user = userService.requestPasswordReset(mail); + if (user.isPresent()) { + mailService.sendPasswordResetMail(user.orElseThrow()); + } else { + // Pretend the request has been successful to prevent checking which emails really exist + // but log that an invalid attempt has been made + LOG.warn("Password reset requested for non existing mail"); + } + } + + /** + * {@code POST /account/reset-password/finish} : Finish to reset the password of the user. + * + * @param keyAndPassword the generated key and the new password. + * @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect. + * @throws RuntimeException {@code 500 (Internal Server Error)} if the password could not be reset. + */ + @PostMapping(path = "/account/reset-password/finish") + public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) { + if (isPasswordLengthInvalid(keyAndPassword.getNewPassword())) { + throw new InvalidPasswordException(); + } + Optional user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); + + if (user.isEmpty()) { + // Dummy hash to prevent reset-key enumeration via response-time timing attack: + // mirrors the bcrypt cost of a successful path so both branches take equal time. + passwordEncoder.encode(keyAndPassword.getNewPassword()); + throw new AccountResourceException("No user was found for this reset key"); + } + } + + private static boolean isPasswordLengthInvalid(String password) { + return ( + StringUtils.isEmpty(password) || + password.length() < ManagedUserVM.PASSWORD_MIN_LENGTH || + password.length() > ManagedUserVM.PASSWORD_MAX_LENGTH + ); + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/AuthenticateController.java b/src/main/java/com/example/questionbank/web/rest/AuthenticateController.java new file mode 100644 index 0000000..10afacd --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/AuthenticateController.java @@ -0,0 +1,125 @@ +package com.example.questionbank.web.rest; + +import static com.example.questionbank.security.SecurityUtils.AUTHORITIES_CLAIM; +import static com.example.questionbank.security.SecurityUtils.JWT_ALGORITHM; +import static com.example.questionbank.security.SecurityUtils.USER_ID_CLAIM; + +import com.example.questionbank.security.DomainUserDetailsService.UserWithId; +import com.example.questionbank.web.rest.vm.LoginVM; +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.validation.Valid; +import java.security.Principal; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.JwsHeader; +import org.springframework.security.oauth2.jwt.JwtClaimsSet; +import org.springframework.security.oauth2.jwt.JwtEncoder; +import org.springframework.security.oauth2.jwt.JwtEncoderParameters; +import org.springframework.web.bind.annotation.*; + +/** + * Controller to authenticate users. + */ +@RestController +@RequestMapping("/api") +public class AuthenticateController { + + private static final Logger LOG = LoggerFactory.getLogger(AuthenticateController.class); + + private final JwtEncoder jwtEncoder; + + @Value("${jhipster.security.authentication.jwt.token-validity-in-seconds:0}") + private long tokenValidityInSeconds; + + @Value("${jhipster.security.authentication.jwt.token-validity-in-seconds-for-remember-me:0}") + private long tokenValidityInSecondsForRememberMe; + + private final AuthenticationManagerBuilder authenticationManagerBuilder; + + public AuthenticateController(JwtEncoder jwtEncoder, AuthenticationManagerBuilder authenticationManagerBuilder) { + this.jwtEncoder = jwtEncoder; + this.authenticationManagerBuilder = authenticationManagerBuilder; + } + + @PostMapping("/authenticate") + public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM) { + var authenticationToken = new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); + + var authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); + SecurityContextHolder.getContext().setAuthentication(authentication); + String jwt = this.createToken(authentication, loginVM.isRememberMe()); + var httpHeaders = new HttpHeaders(); + httpHeaders.setBearerAuth(jwt); + return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK); + } + + /** + * {@code GET /authenticate} : check if the user is authenticated. + * + * @return the {@link ResponseEntity} with status {@code 204 (No Content)}, + * or with status {@code 401 (Unauthorized)} if not authenticated. + */ + @GetMapping("/authenticate") + public ResponseEntity isAuthenticated(Principal principal) { + LOG.debug("REST request to check if the current user is authenticated"); + return ResponseEntity.status(principal == null ? HttpStatus.UNAUTHORIZED : HttpStatus.NO_CONTENT).build(); + } + + public String createToken(Authentication authentication, boolean rememberMe) { + String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(" ")); + + var now = Instant.now(); + Instant validity; + if (rememberMe) { + validity = now.plus(this.tokenValidityInSecondsForRememberMe, ChronoUnit.SECONDS); + } else { + validity = now.plus(this.tokenValidityInSeconds, ChronoUnit.SECONDS); + } + + // @formatter:off + JwtClaimsSet.Builder builder = JwtClaimsSet.builder() + .issuedAt(now) + .expiresAt(validity) + .subject(authentication.getName()) + .claim(AUTHORITIES_CLAIM, authorities); + if (authentication.getPrincipal() instanceof UserWithId user) { + builder.claim(USER_ID_CLAIM, user.getId()); + } + + JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build(); + return this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, builder.build())).getTokenValue(); + } + + /** + * Object to return as body in JWT Authentication. + */ + static class JWTToken { + + private String idToken; + + JWTToken(String idToken) { + this.idToken = idToken; + } + + @JsonProperty("id_token") + String getIdToken() { + return idToken; + } + + void setIdToken(String idToken) { + this.idToken = idToken; + } + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/AuthorityResource.java b/src/main/java/com/example/questionbank/web/rest/AuthorityResource.java new file mode 100644 index 0000000..739a3e7 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/AuthorityResource.java @@ -0,0 +1,103 @@ +package com.example.questionbank.web.rest; + +import com.example.questionbank.domain.Authority; +import com.example.questionbank.repository.AuthorityRepository; +import com.example.questionbank.web.rest.errors.BadRequestAlertException; +import jakarta.validation.Valid; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; +import tech.jhipster.web.util.HeaderUtil; +import tech.jhipster.web.util.ResponseUtil; + +/** + * REST controller for managing {@link com.example.questionbank.domain.Authority}. + */ +@RestController +@RequestMapping("/api/authorities") +@Transactional(rollbackFor = Exception.class) +public class AuthorityResource { + + private static final Logger LOG = LoggerFactory.getLogger(AuthorityResource.class); + + private static final String ENTITY_NAME = "adminAuthority"; + + @Value("${jhipster.clientApp.name:questionBank}") + private String applicationName; + + private final AuthorityRepository authorityRepository; + + public AuthorityResource(AuthorityRepository authorityRepository) { + this.authorityRepository = authorityRepository; + } + + /** + * {@code POST /authorities} : Create a new authority. + * + * @param authority the authority to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new authority, or with status {@code 400 (Bad Request)} if the authority has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("") + @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')") + public ResponseEntity createAuthority(@Valid @RequestBody Authority authority) throws URISyntaxException { + LOG.debug("REST request to save Authority : {}", authority); + if (authorityRepository.existsById(authority.getName())) { + throw new BadRequestAlertException("authority already exists", ENTITY_NAME, "idexists"); + } + authority = authorityRepository.save(authority); + return ResponseEntity.created(new URI("/api/authorities/" + authority.getName())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, authority.getName())) + .body(authority); + } + + /** + * {@code GET /authorities} : get all the Authorities. + * + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of Authorities in body. + */ + @GetMapping("") + @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')") + public List getAllAuthorities() { + LOG.debug("REST request to get all Authorities"); + return authorityRepository.findAll(); + } + + /** + * {@code GET /authorities/:id} : get the "id" authority. + * + * @param id the id of the authority to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the authority, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/{id}") + @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')") + public ResponseEntity getAuthority(@PathVariable("id") String id) { + LOG.debug("REST request to get Authority : {}", id); + Optional authority = authorityRepository.findById(id); + return ResponseUtil.wrapOrNotFound(authority); + } + + /** + * {@code DELETE /authorities/:id} : delete the "id" authority. + * + * @param id the id of the authority to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/{id}") + @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')") + public ResponseEntity deleteAuthority(@PathVariable("id") String id) { + LOG.debug("REST request to delete Authority : {}", id); + authorityRepository.deleteById(id); + return ResponseEntity.noContent() + .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id)) + .build(); + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/PublicUserResource.java b/src/main/java/com/example/questionbank/web/rest/PublicUserResource.java new file mode 100644 index 0000000..1144b39 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/PublicUserResource.java @@ -0,0 +1,61 @@ +package com.example.questionbank.web.rest; + +import com.example.questionbank.service.UserService; +import com.example.questionbank.service.dto.UserDTO; +import java.util.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import tech.jhipster.web.util.PaginationUtil; + +@RestController +@RequestMapping("/api") +public class PublicUserResource { + + private static final List ALLOWED_ORDERED_PROPERTIES = List.of( + "id", + "login", + "firstName", + "lastName", + "email", + "activated", + "langKey" + ); + + private static final Logger LOG = LoggerFactory.getLogger(PublicUserResource.class); + + private final UserService userService; + + public PublicUserResource(UserService userService) { + this.userService = userService; + } + + /** + * {@code GET /users} : get all users with only public information - calling this method is allowed for anyone. + * + * @param pageable the pagination information. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users. + */ + @GetMapping("/users") + public ResponseEntity> getAllPublicUsers(@org.springdoc.core.annotations.ParameterObject Pageable pageable) { + LOG.debug("REST request to get all public User names"); + if (!onlyContainsAllowedProperties(pageable)) { + return ResponseEntity.badRequest().build(); + } + + final Page page = userService.getAllPublicUsers(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); + } + + private boolean onlyContainsAllowedProperties(Pageable pageable) { + return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains); + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/UserResource.java b/src/main/java/com/example/questionbank/web/rest/UserResource.java new file mode 100644 index 0000000..567963e --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/UserResource.java @@ -0,0 +1,208 @@ +package com.example.questionbank.web.rest; + +import com.example.questionbank.config.Constants; +import com.example.questionbank.domain.User; +import com.example.questionbank.repository.UserRepository; +import com.example.questionbank.security.AuthoritiesConstants; +import com.example.questionbank.service.MailService; +import com.example.questionbank.service.UserService; +import com.example.questionbank.service.dto.AdminUserDTO; +import com.example.questionbank.web.rest.errors.BadRequestAlertException; +import com.example.questionbank.web.rest.errors.EmailAlreadyUsedException; +import com.example.questionbank.web.rest.errors.LoginAlreadyUsedException; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Pattern; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import tech.jhipster.web.util.HeaderUtil; +import tech.jhipster.web.util.PaginationUtil; +import tech.jhipster.web.util.ResponseUtil; + +/** + * REST controller for managing users. + *

+ * This class accesses the {@link com.example.questionbank.domain.User} entity, and needs to fetch its collection of authorities. + *

+ * For a normal use-case, it would be better to have an eager relationship between User and Authority, + * and send everything to the client side: there would be no View Model and DTO, a lot less code, and an outer-join + * which would be good for performance. + *

+ * We use a View Model and a DTO for 3 reasons: + *

    + *
  • We want to keep a lazy association between the user and the authorities, because people will + * quite often do relationships with the user, and we don't want them to get the authorities all + * the time for nothing (for performance reasons). This is the #1 goal: we should not impact our users' + * application because of this use-case.
  • + *
  • Not having an outer join causes n+1 requests to the database. This is not a real issue as + * we have by default a second-level cache. This means on the first HTTP call we do the n+1 requests, + * but then all authorities come from the cache, so in fact it's much better than doing an outer join + * (which will get lots of data from the database, for each HTTP call).
  • + *
  • As this manages users, for security reasons, we'd rather have a DTO layer.
  • + *
+ *

+ * Another option would be to have a specific JPA entity graph to handle this case. + */ +@RestController +@RequestMapping("/api/admin") +public class UserResource { + + private static final List ALLOWED_ORDERED_PROPERTIES = List.of( + "id", + "login", + "firstName", + "lastName", + "email", + "activated", + "langKey", + "createdBy", + "createdDate", + "lastModifiedBy", + "lastModifiedDate" + ); + + private static final Logger LOG = LoggerFactory.getLogger(UserResource.class); + + @Value("${jhipster.clientApp.name:questionBank}") + private String applicationName; + + private final UserService userService; + + private final UserRepository userRepository; + + private final MailService mailService; + + public UserResource(UserService userService, UserRepository userRepository, MailService mailService) { + this.userService = userService; + this.userRepository = userRepository; + this.mailService = mailService; + } + + /** + * {@code POST /admin/users} : Creates a new user. + *

+ * Creates a new user if the login and email are not already used, and sends a + * mail with an activation link. + * The user needs to be activated on creation. + * + * @param userDTO the user to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new user, or with status {@code 400 (Bad Request)} if the login or email is already in use. + * @throws URISyntaxException if the Location URI syntax is incorrect. + * @throws BadRequestAlertException {@code 400 (Bad Request)} if the login or email is already in use. + */ + @PostMapping("/users") + @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") + public ResponseEntity createUser(@Valid @RequestBody AdminUserDTO userDTO) throws URISyntaxException { + LOG.debug("REST request to save User : {}", userDTO); + + if (userDTO.getId() != null) { + throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists"); + // Lowercase the user login before comparing with database + } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) { + throw new LoginAlreadyUsedException(); + } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) { + throw new EmailAlreadyUsedException(); + } else { + User newUser = userService.createUser(userDTO); + mailService.sendCreationEmail(newUser); + return ResponseEntity.created(new URI("/api/admin/users/" + newUser.getLogin())) + .headers(HeaderUtil.createAlert(applicationName, "userManagement.created", newUser.getLogin())) + .body(newUser); + } + } + + /** + * {@code PUT /admin/users} : Updates an existing User. + * + * @param userDTO the user to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated user. + * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already in use. + * @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already in use. + */ + @PutMapping({ "/users", "/users/{login}" }) + @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") + public ResponseEntity updateUser( + @PathVariable(name = "login", required = false) @Pattern(regexp = Constants.LOGIN_REGEX) String login, + @Valid @RequestBody AdminUserDTO userDTO + ) { + LOG.debug("REST request to update User : {}", userDTO); + Optional existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); + if (existingUser.isPresent() && !existingUser.orElseThrow().getId().equals(userDTO.getId())) { + throw new EmailAlreadyUsedException(); + } + existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()); + if (existingUser.isPresent() && !existingUser.orElseThrow().getId().equals(userDTO.getId())) { + throw new LoginAlreadyUsedException(); + } + Optional updatedUser = userService.updateUser(userDTO); + + return ResponseUtil.wrapOrNotFound( + updatedUser, + HeaderUtil.createAlert(applicationName, "userManagement.updated", userDTO.getLogin()) + ); + } + + /** + * {@code GET /admin/users} : get all users with all the details - calling this are only allowed for the administrators. + * + * @param pageable the pagination information. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users. + */ + @GetMapping("/users") + @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") + public ResponseEntity> getAllUsers(@org.springdoc.core.annotations.ParameterObject Pageable pageable) { + LOG.debug("REST request to get all User for an admin"); + if (!onlyContainsAllowedProperties(pageable)) { + return ResponseEntity.badRequest().build(); + } + + final Page page = userService.getAllManagedUsers(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); + } + + private boolean onlyContainsAllowedProperties(Pageable pageable) { + return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains); + } + + /** + * {@code GET /admin/users/:login} : get the "login" user. + * + * @param login the login of the user to find. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the "login" user, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/users/{login}") + @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") + public ResponseEntity getUser(@PathVariable("login") @Pattern(regexp = Constants.LOGIN_REGEX) String login) { + LOG.debug("REST request to get User : {}", login); + return ResponseUtil.wrapOrNotFound(userService.getUserWithAuthoritiesByLogin(login).map(AdminUserDTO::new)); + } + + /** + * {@code DELETE /admin/users/:login} : delete the "login" User. + * + * @param login the login of the user to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/users/{login}") + @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") + public ResponseEntity deleteUser(@PathVariable("login") @Pattern(regexp = Constants.LOGIN_REGEX) String login) { + LOG.debug("REST request to delete User: {}", login); + userService.deleteUser(login); + return ResponseEntity.noContent() + .headers(HeaderUtil.createAlert(applicationName, "userManagement.deleted", login)) + .build(); + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/errors/BadRequestAlertException.java b/src/main/java/com/example/questionbank/web/rest/errors/BadRequestAlertException.java new file mode 100644 index 0000000..c42ac3e --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/errors/BadRequestAlertException.java @@ -0,0 +1,51 @@ +package com.example.questionbank.web.rest.errors; + +import java.io.Serial; +import java.net.URI; +import org.springframework.http.HttpStatus; +import org.springframework.web.ErrorResponseException; +import tech.jhipster.web.rest.errors.ProblemDetailWithCause; +import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder; + +@SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep +public class BadRequestAlertException extends ErrorResponseException { + + @Serial + private static final long serialVersionUID = 1L; + + private final String entityName; + + private final String errorKey; + + public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) { + this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey); + } + + public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) { + super( + HttpStatus.BAD_REQUEST, + ProblemDetailWithCauseBuilder.instance() + .withStatus(HttpStatus.BAD_REQUEST.value()) + .withType(type) + .withTitle(defaultMessage) + .withProperty("message", "error." + errorKey) + .withProperty("params", entityName) + .build(), + null + ); + this.entityName = entityName; + this.errorKey = errorKey; + } + + public String getEntityName() { + return entityName; + } + + public String getErrorKey() { + return errorKey; + } + + public ProblemDetailWithCause getProblemDetailWithCause() { + return (ProblemDetailWithCause) this.getBody(); + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/errors/EmailAlreadyUsedException.java b/src/main/java/com/example/questionbank/web/rest/errors/EmailAlreadyUsedException.java new file mode 100644 index 0000000..fd4359d --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/errors/EmailAlreadyUsedException.java @@ -0,0 +1,14 @@ +package com.example.questionbank.web.rest.errors; + +import java.io.Serial; + +@SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep +public class EmailAlreadyUsedException extends BadRequestAlertException { + + @Serial + private static final long serialVersionUID = 1L; + + public EmailAlreadyUsedException() { + super(ErrorConstants.EMAIL_ALREADY_USED_TYPE, "Email is already in use!", "userManagement", "emailexists"); + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/errors/ErrorConstants.java b/src/main/java/com/example/questionbank/web/rest/errors/ErrorConstants.java new file mode 100644 index 0000000..237f128 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/errors/ErrorConstants.java @@ -0,0 +1,17 @@ +package com.example.questionbank.web.rest.errors; + +import java.net.URI; + +public final class ErrorConstants { + + public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure"; + public static final String ERR_VALIDATION = "error.validation"; + public static final String PROBLEM_BASE_URL = "https://www.jhipster.tech/problem"; + public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message"); + public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation"); + public static final URI INVALID_PASSWORD_TYPE = URI.create(PROBLEM_BASE_URL + "/invalid-password"); + public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used"); + public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used"); + + private ErrorConstants() {} +} diff --git a/src/main/java/com/example/questionbank/web/rest/errors/ExceptionTranslator.java b/src/main/java/com/example/questionbank/web/rest/errors/ExceptionTranslator.java new file mode 100644 index 0000000..266f316 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/errors/ExceptionTranslator.java @@ -0,0 +1,275 @@ +package com.example.questionbank.web.rest.errors; + +import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.ConstraintViolationException; +import java.net.URI; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.Strings; +import org.jspecify.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.dao.ConcurrencyFailureException; +import org.springframework.dao.DataAccessException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageConversionException; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.web.ErrorResponse; +import org.springframework.web.ErrorResponseException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import tech.jhipster.config.JHipsterConstants; +import tech.jhipster.web.rest.errors.ProblemDetailWithCause; +import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder; +import tech.jhipster.web.util.HeaderUtil; + +/** + * Controller advice to translate the server side exceptions to client-friendly json structures. + * The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807). + */ +@ControllerAdvice +public class ExceptionTranslator extends ResponseEntityExceptionHandler { + + private static final String FIELD_ERRORS_KEY = "fieldErrors"; + private static final String MESSAGE_KEY = "message"; + private static final String PATH_KEY = "path"; + private static final boolean CAUSAL_CHAIN_ENABLED = false; + + private static final Logger LOG = LoggerFactory.getLogger(ExceptionTranslator.class); + + @Value("${jhipster.clientApp.name:questionBank}") + private String applicationName; + + private final Environment env; + + public ExceptionTranslator(Environment env) { + this.env = env; + } + + @ExceptionHandler + public ResponseEntity handleAnyException(Throwable ex, NativeWebRequest request) { + LOG.debug("Converting Exception to Problem Details:", ex); + ProblemDetailWithCause pdCause = wrapAndCustomizeProblem(ex, request); + return handleExceptionInternal((Exception) ex, pdCause, buildHeaders(ex), HttpStatusCode.valueOf(pdCause.getStatus()), request); + } + + @SuppressWarnings("java:S2638") + @Nullable + @Override + protected ResponseEntity handleExceptionInternal( + Exception ex, + @Nullable Object body, + HttpHeaders headers, + HttpStatusCode statusCode, + WebRequest request + ) { + body = body == null ? wrapAndCustomizeProblem(ex, (NativeWebRequest) request) : body; + return super.handleExceptionInternal(ex, body, headers, statusCode, request); + } + + protected ProblemDetailWithCause wrapAndCustomizeProblem(Throwable ex, NativeWebRequest request) { + return customizeProblem(getProblemDetailWithCause(ex), ex, request); + } + + private ProblemDetailWithCause getProblemDetailWithCause(Throwable ex) { + if ( + ex instanceof com.example.questionbank.service.UsernameAlreadyUsedException + ) return (ProblemDetailWithCause) new LoginAlreadyUsedException().getBody(); + if ( + ex instanceof com.example.questionbank.service.EmailAlreadyUsedException + ) return (ProblemDetailWithCause) new EmailAlreadyUsedException().getBody(); + if ( + ex instanceof com.example.questionbank.service.InvalidPasswordException + ) return (ProblemDetailWithCause) new InvalidPasswordException().getBody(); + + if ( + ex instanceof ErrorResponseException exp && exp.getBody() instanceof ProblemDetailWithCause problemDetailWithCause + ) return problemDetailWithCause; + return ProblemDetailWithCauseBuilder.instance().withStatus(toStatus(ex).value()).build(); + } + + protected ProblemDetailWithCause customizeProblem(ProblemDetailWithCause problem, Throwable err, NativeWebRequest request) { + if (problem.getStatus() <= 0) problem.setStatus(toStatus(err)); + + if (problem.getType() == null || problem.getType().equals(URI.create("about:blank"))) problem.setType(getMappedType(err)); + + // higher precedence to Custom/ResponseStatus types + String title = extractTitle(err, problem.getStatus()); + String problemTitle = problem.getTitle(); + if (problemTitle == null || !problemTitle.equals(title)) { + problem.setTitle(title); + } + + if (problem.getDetail() == null) { + // higher precedence to cause + problem.setDetail(getCustomizedErrorDetails(err)); + } + + Map problemProperties = problem.getProperties(); + if (problemProperties == null || !problemProperties.containsKey(MESSAGE_KEY)) problem.setProperty( + MESSAGE_KEY, + getMappedMessageKey(err) != null ? getMappedMessageKey(err) : "error.http." + problem.getStatus() + ); + + if (problemProperties == null || !problemProperties.containsKey(PATH_KEY)) problem.setProperty(PATH_KEY, getPathValue(request)); + + if ( + err instanceof MethodArgumentNotValidException fieldException && + (problemProperties == null || !problemProperties.containsKey(FIELD_ERRORS_KEY)) + ) problem.setProperty(FIELD_ERRORS_KEY, getFieldErrors(fieldException)); + + problem.setCause(buildCause(err.getCause(), request).orElse(null)); + + return problem; + } + + private String extractTitle(Throwable err, int statusCode) { + return getCustomizedTitle(err) != null ? getCustomizedTitle(err) : extractTitleForResponseStatus(err, statusCode); + } + + private List getFieldErrors(MethodArgumentNotValidException ex) { + return ex + .getBindingResult() + .getFieldErrors() + .stream() + .map(f -> + new FieldErrorVM( + f.getObjectName().replaceFirst("DTO$", ""), + f.getField(), + StringUtils.isNotBlank(f.getDefaultMessage()) ? f.getDefaultMessage() : f.getCode() + ) + ) + .toList(); + } + + private String extractTitleForResponseStatus(Throwable err, int statusCode) { + var specialStatus = extractResponseStatus(err); + return specialStatus == null ? HttpStatus.valueOf(statusCode).getReasonPhrase() : specialStatus.reason(); + } + + private String extractURI(NativeWebRequest request) { + HttpServletRequest nativeRequest = request.getNativeRequest(HttpServletRequest.class); + return nativeRequest != null ? nativeRequest.getRequestURI() : StringUtils.EMPTY; + } + + private HttpStatus toStatus(final Throwable throwable) { + // Let the ErrorResponse take this responsibility + if (throwable instanceof ErrorResponse err) return HttpStatus.valueOf(err.getBody().getStatus()); + + return Optional.ofNullable(getMappedStatus(throwable)).orElse( + Optional.ofNullable(resolveResponseStatus(throwable)).map(ResponseStatus::value).orElse(HttpStatus.INTERNAL_SERVER_ERROR) + ); + } + + private ResponseStatus extractResponseStatus(final Throwable throwable) { + return resolveResponseStatus(throwable); + } + + private ResponseStatus resolveResponseStatus(final Throwable type) { + final ResponseStatus candidate = findMergedAnnotation(type.getClass(), ResponseStatus.class); + return candidate == null && type.getCause() != null ? resolveResponseStatus(type.getCause()) : candidate; + } + + private URI getMappedType(Throwable err) { + if ( + err instanceof MethodArgumentNotValidException || err instanceof ConstraintViolationException + ) return ErrorConstants.CONSTRAINT_VIOLATION_TYPE; + return ErrorConstants.DEFAULT_TYPE; + } + + private String getMappedMessageKey(Throwable err) { + if (err instanceof MethodArgumentNotValidException || err instanceof ConstraintViolationException) { + return ErrorConstants.ERR_VALIDATION; + } else if (err instanceof ConcurrencyFailureException || err.getCause() instanceof ConcurrencyFailureException) { + return ErrorConstants.ERR_CONCURRENCY_FAILURE; + } + return null; + } + + private String getCustomizedTitle(Throwable err) { + if ( + err instanceof MethodArgumentNotValidException || err instanceof ConstraintViolationException + ) return "Method argument not valid"; + return null; + } + + private String getCustomizedErrorDetails(Throwable err) { + Collection activeProfiles = List.of(env.getActiveProfiles()); + if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { + if (err instanceof HttpMessageConversionException) return "Unable to convert http message"; + if (err instanceof DataAccessException) return "Failure during data access"; + if (containsPackageName(err.getMessage())) return "Unexpected runtime exception"; + } + return err.getCause() != null ? err.getCause().getMessage() : err.getMessage(); + } + + private HttpStatus getMappedStatus(Throwable err) { + // Where we disagree with Spring defaults + if (err instanceof AccessDeniedException) return HttpStatus.FORBIDDEN; + if (err instanceof ConcurrencyFailureException) return HttpStatus.CONFLICT; + if (err instanceof BadCredentialsException) return HttpStatus.UNAUTHORIZED; + if (err instanceof ConstraintViolationException) return HttpStatus.BAD_REQUEST; + return null; + } + + private URI getPathValue(NativeWebRequest request) { + if (request == null) return URI.create("about:blank"); + return URI.create(extractURI(request)); + } + + private HttpHeaders buildHeaders(Throwable err) { + return err instanceof BadRequestAlertException badRequestAlertException + ? HeaderUtil.createFailureAlert( + applicationName, + true, + badRequestAlertException.getEntityName(), + badRequestAlertException.getErrorKey(), + badRequestAlertException.getMessage() + ) + : null; + } + + public Optional buildCause(final Throwable throwable, NativeWebRequest request) { + if (throwable != null && isCausalChainEnabled()) { + return Optional.of(customizeProblem(getProblemDetailWithCause(throwable), throwable, request)); + } + return Optional.ofNullable(null); + } + + private boolean isCausalChainEnabled() { + // Customize as per the needs + return CAUSAL_CHAIN_ENABLED; + } + + private boolean containsPackageName(String message) { + // This list is for sure not complete + return Strings.CS.containsAny( + message, + "org.", + "java.", + "net.", + "jakarta.", + "javax.", + "com.", + "io.", + "de.", + "com.example.questionbank" + ); + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/errors/FieldErrorVM.java b/src/main/java/com/example/questionbank/web/rest/errors/FieldErrorVM.java new file mode 100644 index 0000000..b8cf0c5 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/errors/FieldErrorVM.java @@ -0,0 +1,34 @@ +package com.example.questionbank.web.rest.errors; + +import java.io.Serial; +import java.io.Serializable; + +public class FieldErrorVM implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + private final String objectName; + + private final String field; + + private final String message; + + public FieldErrorVM(String dto, String field, String message) { + this.objectName = dto; + this.field = field; + this.message = message; + } + + public String getObjectName() { + return objectName; + } + + public String getField() { + return field; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/errors/InvalidPasswordException.java b/src/main/java/com/example/questionbank/web/rest/errors/InvalidPasswordException.java new file mode 100644 index 0000000..84f2e0e --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/errors/InvalidPasswordException.java @@ -0,0 +1,25 @@ +package com.example.questionbank.web.rest.errors; + +import java.io.Serial; +import org.springframework.http.HttpStatus; +import org.springframework.web.ErrorResponseException; +import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder; + +@SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep +public class InvalidPasswordException extends ErrorResponseException { + + @Serial + private static final long serialVersionUID = 1L; + + public InvalidPasswordException() { + super( + HttpStatus.BAD_REQUEST, + ProblemDetailWithCauseBuilder.instance() + .withStatus(HttpStatus.BAD_REQUEST.value()) + .withType(ErrorConstants.INVALID_PASSWORD_TYPE) + .withTitle("Incorrect password") + .build(), + null + ); + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/errors/LoginAlreadyUsedException.java b/src/main/java/com/example/questionbank/web/rest/errors/LoginAlreadyUsedException.java new file mode 100644 index 0000000..ee06808 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/errors/LoginAlreadyUsedException.java @@ -0,0 +1,14 @@ +package com.example.questionbank.web.rest.errors; + +import java.io.Serial; + +@SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep +public class LoginAlreadyUsedException extends BadRequestAlertException { + + @Serial + private static final long serialVersionUID = 1L; + + public LoginAlreadyUsedException() { + super(ErrorConstants.LOGIN_ALREADY_USED_TYPE, "Login name already used!", "userManagement", "userexists"); + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/errors/package-info.java b/src/main/java/com/example/questionbank/web/rest/errors/package-info.java new file mode 100644 index 0000000..2acb4ba --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/errors/package-info.java @@ -0,0 +1,4 @@ +/** + * Rest layer error handling. + */ +package com.example.questionbank.web.rest.errors; diff --git a/src/main/java/com/example/questionbank/web/rest/package-info.java b/src/main/java/com/example/questionbank/web/rest/package-info.java new file mode 100644 index 0000000..c54b9c5 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/package-info.java @@ -0,0 +1,4 @@ +/** + * Rest layer. + */ +package com.example.questionbank.web.rest; diff --git a/src/main/java/com/example/questionbank/web/rest/vm/KeyAndPasswordVM.java b/src/main/java/com/example/questionbank/web/rest/vm/KeyAndPasswordVM.java new file mode 100644 index 0000000..db55109 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/vm/KeyAndPasswordVM.java @@ -0,0 +1,27 @@ +package com.example.questionbank.web.rest.vm; + +/** + * View Model object for storing the user's key and password. + */ +public class KeyAndPasswordVM { + + private String key; + + private String newPassword; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getNewPassword() { + return newPassword; + } + + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/vm/LoginVM.java b/src/main/java/com/example/questionbank/web/rest/vm/LoginVM.java new file mode 100644 index 0000000..b04d351 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/vm/LoginVM.java @@ -0,0 +1,53 @@ +package com.example.questionbank.web.rest.vm; + +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + +/** + * View Model object for storing a user's credentials. + */ +public class LoginVM { + + @NotNull + @Size(min = 1, max = 254) + private String username; + + @NotNull + @Size(min = 4, max = 100) + private String password; + + private boolean rememberMe; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean isRememberMe() { + return rememberMe; + } + + public void setRememberMe(boolean rememberMe) { + this.rememberMe = rememberMe; + } + + // prettier-ignore + @Override + public String toString() { + return "LoginVM{" + + "username='" + username + '\'' + + ", rememberMe=" + rememberMe + + '}'; + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/vm/ManagedUserVM.java b/src/main/java/com/example/questionbank/web/rest/vm/ManagedUserVM.java new file mode 100644 index 0000000..95d430f --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/vm/ManagedUserVM.java @@ -0,0 +1,35 @@ +package com.example.questionbank.web.rest.vm; + +import com.example.questionbank.service.dto.AdminUserDTO; +import jakarta.validation.constraints.Size; + +/** + * View Model extending the AdminUserDTO, which is meant to be used in the user management UI. + */ +public class ManagedUserVM extends AdminUserDTO { + + public static final int PASSWORD_MIN_LENGTH = 4; + + public static final int PASSWORD_MAX_LENGTH = 100; + + @Size(min = PASSWORD_MIN_LENGTH, max = PASSWORD_MAX_LENGTH) + private String password; + + public ManagedUserVM() { + // Empty constructor needed for Jackson. + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + // prettier-ignore + @Override + public String toString() { + return "ManagedUserVM{" + super.toString() + "} "; + } +} diff --git a/src/main/java/com/example/questionbank/web/rest/vm/package-info.java b/src/main/java/com/example/questionbank/web/rest/vm/package-info.java new file mode 100644 index 0000000..1bc8ee7 --- /dev/null +++ b/src/main/java/com/example/questionbank/web/rest/vm/package-info.java @@ -0,0 +1,4 @@ +/** + * Rest layer visual models. + */ +package com.example.questionbank.web.rest.vm; diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt new file mode 100644 index 0000000..a731cf4 --- /dev/null +++ b/src/main/resources/banner.txt @@ -0,0 +1,10 @@ + + ${AnsiColor.GREEN} ██╗${AnsiColor.BLUE} ██╗ ██╗ ████████╗ ███████╗ ██████╗ ████████╗ ████████╗ ████${AnsiColor.GREEN}███╗ + ${AnsiColor.GREEN} ██║ ██║ ${AnsiColor.BLUE} ██║ ╚══██╔══╝ ██╔═══██╗ ██╔════╝ ╚══██╔══╝ ██╔══${AnsiColor.GREEN}═══╝ ██╔═══██╗ + ${AnsiColor.GREEN} ██║ ████████║${AnsiColor.BLUE} ██║ ███████╔╝ ╚█████╗ ██║ ${AnsiColor.GREEN} ██████╗ ███████╔╝ + ${AnsiColor.GREEN}██╗ ██║ ██╔═══██║ ██║ ${AnsiColor.BLUE} ██╔════╝ ╚═══██╗ ${AnsiColor.GREEN}██║ ██╔═══╝ ██╔══██║ + ${AnsiColor.GREEN}╚██████╔╝ ██║ ██║ ████████╗ ██║ ${AnsiColor.BLUE} ██████${AnsiColor.GREEN}╔╝ ██║ ████████╗ ██║ ╚██╗ + ${AnsiColor.GREEN} ╚═════╝ ╚═╝ ╚═╝ ╚═══════╝ ╚═╝ ${AnsiColor.BLUE} ╚═${AnsiColor.GREEN}════╝ ╚═╝ ╚═══════╝ ╚═╝ ╚═╝ + +${AnsiColor.BRIGHT_BLUE}:: JHipster 🤓 :: Running Spring Boot ${spring-boot.version} :: Startup profile(s) ${spring.profiles.active} :: +:: https://www.jhipster.tech ::${AnsiColor.DEFAULT} diff --git a/src/main/resources/config/application-dev.yml b/src/main/resources/config/application-dev.yml new file mode 100644 index 0000000..c764467 --- /dev/null +++ b/src/main/resources/config/application-dev.yml @@ -0,0 +1,97 @@ +# =================================================================== +# Spring Boot configuration for the "dev" profile. +# +# This configuration overrides the application.yml file. +# +# More information on profiles: https://www.jhipster.tech/profiles/ +# More information on configuration properties: https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +# =================================================================== +# Standard Spring Boot properties. +# Full reference is available at: +# https://docs.spring.io/spring-boot/appendix/application-properties/index.html +# =================================================================== + +logging: + level: + ROOT: DEBUG + tech.jhipster: DEBUG + org.hibernate.SQL: DEBUG + com.example.questionbank: DEBUG + +spring: + devtools: + restart: + enabled: true + additional-exclude: static/** + livereload: + enabled: false # we use Webpack dev server + BrowserSync for livereload + jackson: + serialization: + indent-output: true + datasource: + type: com.zaxxer.hikari.HikariDataSource + url: jdbc:postgresql://localhost:5432/questionBank + hikari: + poolName: Hikari + auto-commit: false + liquibase: + # Remove 'faker' if you do not want the sample data to be loaded automatically + contexts: dev, faker + mail: + host: localhost + port: 25 + messages: + cache-duration: PT1S # 1 second, see the ISO 8601 standard + thymeleaf: + cache: false + +server: + port: 8080 + # make sure requests the proxy uri instead of the server one + forward-headers-strategy: native + +# =================================================================== +# JHipster specific properties +# +# Full reference is available at: https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +jhipster: + # CORS is only enabled by default with the "dev" profile + cors: + # Allow Ionic for JHipster by default (* no longer allowed in Spring Boot 2.4+) + allowed-origins: 'http://localhost:8100,https://localhost:8100,http://localhost:9000,https://localhost:9000' + # Enable CORS when running in GitHub Codespaces + allowed-origin-patterns: 'https://*.githubpreview.dev' + allowed-methods: '*' + allowed-headers: '*' + exposed-headers: 'Authorization,Link,X-Total-Count,X-${jhipster.clientApp.name}-alert,X-${jhipster.clientApp.name}-error,X-${jhipster.clientApp.name}-params' + allow-credentials: true + max-age: 1800 + security: + authentication: + jwt: + # Token is valid 24 hours + token-validity-in-seconds: 86400 + token-validity-in-seconds-for-remember-me: 2592000 + mail: # specific JHipster mail property, for standard properties see MailProperties + base-url: http://127.0.0.1:8080 + logging: + use-json-format: false # By default, logs are not in Json format + logstash: # Forward logs to logstash over a socket, used by LoggingConfiguration + enabled: false + host: localhost + port: 5000 + ring-buffer-size: 512 +# =================================================================== +# Application specific properties +# Add your own application properties here, see the ApplicationProperties class +# to have type-safe configuration, like in the JHipsterProperties above +# +# More documentation is available at: +# https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +# application: diff --git a/src/main/resources/config/application-prod.yml b/src/main/resources/config/application-prod.yml new file mode 100644 index 0000000..3269a26 --- /dev/null +++ b/src/main/resources/config/application-prod.yml @@ -0,0 +1,110 @@ +# =================================================================== +# Spring Boot configuration for the "prod" profile. +# +# This configuration overrides the application.yml file. +# +# More information on profiles: https://www.jhipster.tech/profiles/ +# More information on configuration properties: https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +# =================================================================== +# Standard Spring Boot properties. +# Full reference is available at: +# https://docs.spring.io/spring-boot/appendix/application-properties/index.html +# =================================================================== + +logging: + level: + ROOT: INFO + tech.jhipster: INFO + com.example.questionbank: INFO + +management: + prometheus: + metrics: + export: + enabled: false + +spring: + devtools: + restart: + enabled: false + livereload: + enabled: false + datasource: + type: com.zaxxer.hikari.HikariDataSource + url: jdbc:postgresql://localhost:5432/questionBank + hikari: + poolName: Hikari + auto-commit: false + # Replace by 'prod, faker' to add the faker context and have sample data loaded in production + liquibase: + contexts: prod + mail: + host: localhost + port: 25 + thymeleaf: + cache: true + +# =================================================================== +# To enable TLS in production, generate a certificate using: +# keytool -genkey -alias questionbank -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650 +# +# You can also use Let's Encrypt: +# See details in topic "Create a Java Keystore (.JKS) from Let's Encrypt Certificates" on https://maximilian-boehm.com/en-gb/blog +# +# Then, modify the server.ssl properties so your "server" configuration looks like: +# +# server: +# port: 443 +# ssl: +# key-store: classpath:config/tls/keystore.p12 +# key-store-password: password +# key-store-type: PKCS12 +# key-alias: selfsigned +# # The ciphers suite enforce the security by deactivating some old and deprecated SSL cipher, this list was tested against SSL Labs (https://www.ssllabs.com/ssltest/) +# ciphers: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ,TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 ,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_RSA_WITH_AES_128_GCM_SHA256,TLS_RSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_256_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,TLS_RSA_WITH_CAMELLIA_128_CBC_SHA +# =================================================================== +server: + port: 8080 + shutdown: graceful # see https://docs.spring.io/spring-boot/reference/web/graceful-shutdown.html#web.graceful-shutdown + compression: + enabled: true + mime-types: text/html,text/xml,text/plain,text/css,application/javascript,application/json,image/svg+xml + min-response-size: 1024 + +# =================================================================== +# JHipster specific properties +# +# Full reference is available at: https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +jhipster: + http: + cache: # Used by the CachingHttpHeadersFilter + timeToLiveInDays: 1461 + security: + authentication: + jwt: + # Token is valid 24 hours + token-validity-in-seconds: 86400 + token-validity-in-seconds-for-remember-me: 2592000 + mail: # specific JHipster mail property, for standard properties see MailProperties + base-url: http://my-server-url-to-change # Modify according to your server's URL + logging: + use-json-format: false # By default, logs are not in Json format + logstash: # Forward logs to logstash over a socket, used by LoggingConfiguration + enabled: false + host: localhost + port: 5000 + ring-buffer-size: 512 +# =================================================================== +# Application specific properties +# Add your own application properties here, see the ApplicationProperties class +# to have type-safe configuration, like in the JHipsterProperties above +# +# More documentation is available at: +# https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +# application: diff --git a/src/main/resources/config/application-secret-samples.yml b/src/main/resources/config/application-secret-samples.yml new file mode 100644 index 0000000..bdb3478 --- /dev/null +++ b/src/main/resources/config/application-secret-samples.yml @@ -0,0 +1,23 @@ +# =================================================================== +# Spring Boot configuration for the "secret-samples" profile. +# +# This configuration overrides the application.yml file. +# +# More information on profiles: https://www.jhipster.tech/profiles/ +# More information on configuration properties: https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +# =================================================================== +# Samples for required secrets to be used in development and ci using prod profile. +# =================================================================== + +spring: + datasource: + username: questionBank + password: + +jhipster: + security: + authentication: + jwt: + base64-secret: MzY1ZDU0MDM3M2Y5YWRiMDYxYjBmYzZlOTMxMWFiNmYyMDEyZTUzZjYxOWFjNjhlNjU2NzcxYjkwY2Y0MGIwOGUyNTc5NWQyOGY3OGJkMjExZjhkYzU3ZGU4ZDc0ZmZiMTYwMzY0NGM4ZWZmODRhZTZjNzBlNjk5MWJkYjM5YjI= diff --git a/src/main/resources/config/application-tls.yml b/src/main/resources/config/application-tls.yml new file mode 100644 index 0000000..07bb104 --- /dev/null +++ b/src/main/resources/config/application-tls.yml @@ -0,0 +1,27 @@ +# =================================================================== +# Activate this profile to enable TLS and HTTP/2. +# +# JHipster has generated a self-signed certificate, which will be used to encrypt traffic. +# As your browser will not understand this certificate, you will need to import it. +# +# Another (easiest) solution with Chrome is to enable the "allow-insecure-localhost" flag +# at chrome://flags/#allow-insecure-localhost +# =================================================================== +server: + ssl: + key-store: classpath:config/tls/keystore.p12 + key-store-password: password + key-store-type: PKCS12 + key-alias: selfsigned + ciphers: + - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA + - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA + - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA + - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA + enabled-protocols: TLSv1.2 + http2: + enabled: true diff --git a/src/main/resources/config/application.yml b/src/main/resources/config/application.yml new file mode 100644 index 0000000..28a83d0 --- /dev/null +++ b/src/main/resources/config/application.yml @@ -0,0 +1,229 @@ +# =================================================================== +# Spring Boot configuration. +# +# This configuration will be overridden by the Spring profile you use, +# for example application-dev.yml if you use the "dev" profile. +# +# More information on profiles: https://www.jhipster.tech/profiles/ +# More information on configuration properties: https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +# =================================================================== +# Standard Spring Boot properties. +# Full reference is available at: +# https://docs.spring.io/spring-boot/appendix/application-properties/index.html +# =================================================================== + +--- +# Conditionally disable springdoc on missing api-docs profile +spring: + config: + activate: + on-profile: '!api-docs' +springdoc: + api-docs: + enabled: false +--- +management: + endpoints: + web: + base-path: /management + exposure: + include: + - configprops + - env + - health + - info + - jhimetrics + - jhiopenapigroups + - logfile + - loggers + - prometheus + - threaddump + - liquibase + endpoint: + health: + show-details: when_authorized + roles: 'ROLE_ADMIN' + probes: + enabled: true + group: + liveness: + include: livenessState + readiness: + include: readinessState,db + jhimetrics: + access: read-only + info: + git: + mode: full + env: + enabled: true + health: + mail: + enabled: false # When using the MailService, configure an SMTP server and set this to true + prometheus: + metrics: + export: + enabled: true + step: 60 + observations: + key-values: + application: ${spring.application.name} + metrics: + enable: + http: true + jvm: true + logback: true + process: true + system: true + distribution: + percentiles-histogram: + all: true + percentiles: + all: 0, 0.5, 0.75, 0.95, 0.99, 1.0 + data: + repository: + autotime: + enabled: true + tags: + application: ${spring.application.name} + +spring: + application: + name: questionBank + docker: + compose: + enabled: true + lifecycle-management: start-only + file: src/main/docker/services.yml + profiles: + # The commented value for `active` can be replaced with valid Spring profiles to load. + # Otherwise, it will be filled in by maven when building the JAR file + # Either way, it can be overridden by `--spring.profiles.active` value passed in the commandline or `-Dspring.profiles.active` set in `JAVA_OPTS` + active: '@spring.profiles.active@' + group: + dev: + - secret-samples + - api-docs + # Uncomment to activate TLS for the dev profile + #- tls + jmx: + enabled: false + data: + jpa: + repositories: + bootstrap-mode: deferred + jpa: + open-in-view: false + properties: + hibernate.jdbc.time_zone: UTC + hibernate.timezone.default_storage: NORMALIZE + hibernate.type.preferred_instant_jdbc_type: TIMESTAMP + hibernate.id.new_generator_mappings: true + hibernate.connection.provider_disables_autocommit: true + hibernate.cache.use_second_level_cache: false + hibernate.cache.use_query_cache: false + hibernate.generate_statistics: false + # modify batch size as necessary + hibernate.jdbc.batch_size: 25 + hibernate.order_inserts: true + hibernate.order_updates: true + hibernate.query.fail_on_pagination_over_collection_fetch: true + hibernate.query.in_clause_parameter_padding: true + hibernate: + ddl-auto: none + naming: + physical-strategy: org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy + implicit-strategy: org.springframework.boot.hibernate.SpringImplicitNamingStrategy + messages: + basename: i18n/messages + main: + allow-bean-definition-overriding: true + mvc: + problemdetails: + enabled: true + security: + oauth2: + resourceserver: + jwt: + authority-prefix: '' + authorities-claim-name: auth + task: + execution: + thread-name-prefix: question-bank-task- + pool: + core-size: 2 + max-size: 50 + queue-capacity: 10000 + scheduling: + thread-name-prefix: question-bank-scheduling- + pool: + size: 2 + thymeleaf: + mode: HTML + output: + ansi: + console-available: true + +server: + servlet: + session: + cookie: + http-only: true + +springdoc: + show-actuator: true + +# Properties to be exposed on the /info management endpoint +info: + # Comma separated list of profiles that will trigger the ribbon to show + display-ribbon-on-profiles: 'dev' + +# =================================================================== +# JHipster specific properties +# +# Full reference is available at: https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +jhipster: + clientApp: + name: 'questionBankApp' + # By default CORS is disabled. Uncomment to enable. + # cors: + # allowed-origins: "http://localhost:8100,http://localhost:9000" + # allowed-methods: "*" + # allowed-headers: "*" + # exposed-headers: "Authorization,Link,X-Total-Count,X-${jhipster.clientApp.name}-alert,X-${jhipster.clientApp.name}-error,X-${jhipster.clientApp.name}-params" + # allow-credentials: true + # max-age: 1800 + mail: + from: questionBank@localhost + api-docs: + default-include-pattern: /api/** + management-include-pattern: /management/** + title: Question Bank API + description: Question Bank API documentation + version: 0.0.1 + terms-of-service-url: + contact-name: + contact-url: + contact-email: + license: unlicensed + license-url: + security: + content-security-policy: "default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:" + + +# jhipster-needle-add-application-yaml-document +--- +# =================================================================== +# Application specific properties +# Add your own application properties here, see the ApplicationProperties class +# to have type-safe configuration, like in the JHipsterProperties above +# +# More documentation is available at: +# https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +# application: diff --git a/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml b/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml new file mode 100644 index 0000000..8ee1b04 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml @@ -0,0 +1,121 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/data/authority.csv b/src/main/resources/config/liquibase/data/authority.csv new file mode 100644 index 0000000..af5c6df --- /dev/null +++ b/src/main/resources/config/liquibase/data/authority.csv @@ -0,0 +1,3 @@ +name +ROLE_ADMIN +ROLE_USER diff --git a/src/main/resources/config/liquibase/data/user.csv b/src/main/resources/config/liquibase/data/user.csv new file mode 100644 index 0000000..fbc52da --- /dev/null +++ b/src/main/resources/config/liquibase/data/user.csv @@ -0,0 +1,3 @@ +id;login;password_hash;first_name;last_name;email;image_url;activated;lang_key;created_by;last_modified_by +1;admin;$2a$10$gSAhZrxMllrbgj/kkK9UceBPpChGWJA7SYIb1Mqo.n5aNLq1/oRrC;Administrator;Administrator;admin@localhost;;true;en;system;system +2;user;$2a$10$VEjxo0jq2YG9Rbk2HmX9S.k1uZBGYUHdUcid3g/vfiEl7lwWgOH/K;User;User;user@localhost;;true;en;system;system diff --git a/src/main/resources/config/liquibase/data/user_authority.csv b/src/main/resources/config/liquibase/data/user_authority.csv new file mode 100644 index 0000000..01dbdef --- /dev/null +++ b/src/main/resources/config/liquibase/data/user_authority.csv @@ -0,0 +1,4 @@ +user_id;authority_name +1;ROLE_ADMIN +1;ROLE_USER +2;ROLE_USER diff --git a/src/main/resources/config/liquibase/master.xml b/src/main/resources/config/liquibase/master.xml new file mode 100644 index 0000000..315d9ec --- /dev/null +++ b/src/main/resources/config/liquibase/master.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/tls/keystore.p12 b/src/main/resources/config/tls/keystore.p12 new file mode 100644 index 0000000..c868a33 Binary files /dev/null and b/src/main/resources/config/tls/keystore.p12 differ diff --git a/src/main/resources/i18n/messages.properties b/src/main/resources/i18n/messages.properties new file mode 100644 index 0000000..14a3062 --- /dev/null +++ b/src/main/resources/i18n/messages.properties @@ -0,0 +1,21 @@ +# Error page +error.title=Your request cannot be processed +error.subtitle=Sorry, an error has occurred. +error.status=Status: +error.message=Message: + +# Activation email +email.activation.title=questionBank account activation +email.activation.greeting=Dear {0} +email.activation.text1=Your questionBank account has been created, please click on the URL below to activate it: +email.activation.text2=Regards, +email.signature=questionBank Team. + +# Creation email +email.creation.text1=Your questionBank account has been created, please click on the URL below to access it: + +# Reset email +email.reset.title=questionBank password reset +email.reset.greeting=Dear {0} +email.reset.text1=For your questionBank account a password reset was requested, please click on the URL below to reset it: +email.reset.text2=Regards, diff --git a/src/main/resources/i18n/messages_en.properties b/src/main/resources/i18n/messages_en.properties new file mode 100644 index 0000000..14a3062 --- /dev/null +++ b/src/main/resources/i18n/messages_en.properties @@ -0,0 +1,21 @@ +# Error page +error.title=Your request cannot be processed +error.subtitle=Sorry, an error has occurred. +error.status=Status: +error.message=Message: + +# Activation email +email.activation.title=questionBank account activation +email.activation.greeting=Dear {0} +email.activation.text1=Your questionBank account has been created, please click on the URL below to activate it: +email.activation.text2=Regards, +email.signature=questionBank Team. + +# Creation email +email.creation.text1=Your questionBank account has been created, please click on the URL below to access it: + +# Reset email +email.reset.title=questionBank password reset +email.reset.greeting=Dear {0} +email.reset.text1=For your questionBank account a password reset was requested, please click on the URL below to reset it: +email.reset.text2=Regards, diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..8d0f3e1 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html new file mode 100644 index 0000000..21c5f7e --- /dev/null +++ b/src/main/resources/templates/error.html @@ -0,0 +1,94 @@ + + + + + + Your request cannot be processed + + + +
+

Your request cannot be processed :(

+ +

Sorry, an error has occurred.

+ + Status:  ()
+ + Message: 
+
+
+ + diff --git a/src/main/resources/templates/mail/activationEmail.html b/src/main/resources/templates/mail/activationEmail.html new file mode 100644 index 0000000..6be1e4f --- /dev/null +++ b/src/main/resources/templates/mail/activationEmail.html @@ -0,0 +1,20 @@ + + + + JHipster activation + + + + +

Dear

+

Your JHipster account has been created, please click on the URL below to activate it:

+

+ Activation link +

+

+ Regards, +
+ JHipster. +

+ + diff --git a/src/main/resources/templates/mail/creationEmail.html b/src/main/resources/templates/mail/creationEmail.html new file mode 100644 index 0000000..ab46621 --- /dev/null +++ b/src/main/resources/templates/mail/creationEmail.html @@ -0,0 +1,20 @@ + + + + JHipster creation + + + + +

Dear

+

Your JHipster account has been created, please click on the URL below to access it:

+

+ Login link +

+

+ Regards, +
+ JHipster. +

+ + diff --git a/src/main/resources/templates/mail/passwordResetEmail.html b/src/main/resources/templates/mail/passwordResetEmail.html new file mode 100644 index 0000000..eb74196 --- /dev/null +++ b/src/main/resources/templates/mail/passwordResetEmail.html @@ -0,0 +1,22 @@ + + + + JHipster password reset + + + + +

Dear

+

+ For your JHipster account a password reset was requested, please click on the URL below to reset it: +

+

+ Login link +

+

+ Regards, +
+ JHipster. +

+ + diff --git a/src/main/webapp/404.html b/src/main/webapp/404.html new file mode 100644 index 0000000..f061c66 --- /dev/null +++ b/src/main/webapp/404.html @@ -0,0 +1,57 @@ + + + + + Page Not Found + + + + + +

Page Not Found

+

Sorry, but the page you were trying to view does not exist.

+ + diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..f1611b5 --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,13 @@ + + + + + html + text/html;charset=utf-8 + + + diff --git a/src/main/webapp/app/account/account.service.spec.ts b/src/main/webapp/app/account/account.service.spec.ts new file mode 100644 index 0000000..f725014 --- /dev/null +++ b/src/main/webapp/app/account/account.service.spec.ts @@ -0,0 +1,121 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { createTestingPinia } from '@pinia/testing'; +import axios from 'axios'; + +import { AUTHENTICATION_TOKEN_KEY } from '@/shared/jhipster/constants'; +import { type AccountStore, useStore } from '@/store'; + +import AccountService from './account.service'; + +const resetStore = (store: AccountStore) => { + store.logout(); + store.authenticate(null); + store.profilesLoaded = false; + store.activeProfiles = ''; + store.ribbonOnProfiles = ''; +}; + +const axiosStub = { + get: vi.spyOn(axios, 'get'), + post: vi.spyOn(axios, 'post'), +}; + +createTestingPinia({ stubActions: false }); +const store = useStore(); + +describe('Account Service test suite', () => { + let accountService: AccountService; + + beforeEach(() => { + localStorage.clear(); + localStorage.setItem(AUTHENTICATION_TOKEN_KEY, 'token'); + + axiosStub.get.mockReset(); + resetStore(store); + }); + + it('should init service and do not retrieve account', async () => { + axiosStub.get.mockImplementation((...args: any[]) => { + if (args[0] === 'management/info') { + return Promise.resolve({ status: 200, data: { 'display-ribbon-on-profiles': 'dev', activeProfiles: ['dev', 'test'] } }); + } + return Promise.resolve({}); + }); + + accountService = new AccountService(store); + await accountService.update(); + + expect(store.logon).toBeNull(); + expect(accountService.authenticated).toBe(false); + expect(store.account).toBeNull(); + expect(axiosStub.get).toHaveBeenCalledWith('management/info'); + expect(store.activeProfiles[0]).toBe('dev'); + expect(store.activeProfiles[1]).toBe('test'); + expect(store.ribbonOnProfiles).toBe('dev'); + }); + + it('should init service and retrieve profiles if already logged in before but no account found', async () => { + axiosStub.get.mockResolvedValue({}); + accountService = new AccountService(store); + await accountService.update(); + + expect(store.logon).toBeNull(); + expect(accountService.authenticated).toBe(false); + expect(store.account).toBeNull(); + expect(axiosStub.get).toHaveBeenCalledWith('management/info'); + }); + + it('should init service and retrieve profiles if already logged in before but exception occurred and should be logged out', async () => { + axiosStub.get.mockImplementation((...args: any[]) => { + if (args[0] === 'api/account') return Promise.reject(new Error()); + return Promise.resolve({}); + }); + accountService = new AccountService(store); + await accountService.update(); + + expect(accountService.authenticated).toBe(false); + expect(store.account).toBeNull(); + expect(axiosStub.get).toHaveBeenCalledWith('management/info'); + }); + + it('should init service and check for authority after retrieving account but getAccount failed', async () => { + axiosStub.get.mockRejectedValue(new Error()); + accountService = new AccountService(store); + await accountService.update(); + + return accountService.hasAnyAuthorityAndCheckAuth('USER').then((value: boolean) => { + expect(value).toBe(false); + }); + }); + + it('should init service and check for authority after retrieving account', async () => { + axiosStub.get.mockResolvedValue({ status: 200, data: { authorities: ['USER'], langKey: 'en', login: 'ADMIN' } }); + accountService = new AccountService(store); + await accountService.update(); + + return accountService.hasAnyAuthorityAndCheckAuth('USER').then((value: boolean) => { + expect(value).toBe(true); + }); + }); + + it('should init service as not authenticated and not return any authorities admin and not retrieve account', async () => { + axiosStub.get.mockRejectedValue(new Error()); + accountService = new AccountService(store); + await accountService.update(); + + return accountService.hasAnyAuthorityAndCheckAuth('ADMIN').then((value: boolean) => { + expect(value).toBe(false); + }); + }); + + it('should init service as not authenticated and not return authority user', async () => { + axiosStub.get.mockRejectedValue(new Error()); + accountService = new AccountService(store); + await accountService.update(); + + return accountService.hasAnyAuthorityAndCheckAuth('USER').then((value: boolean) => { + expect(value).toBe(false); + }); + }); +}); diff --git a/src/main/webapp/app/account/account.service.ts b/src/main/webapp/app/account/account.service.ts new file mode 100644 index 0000000..17b311d --- /dev/null +++ b/src/main/webapp/app/account/account.service.ts @@ -0,0 +1,87 @@ +import axios from 'axios'; + +import { AUTHENTICATION_TOKEN_KEY } from '@/shared/jhipster/constants'; +import { type AccountStore } from '@/store'; + +export default class AccountService { + constructor(private readonly store: AccountStore) {} + + async update(): Promise { + if (!this.store.profilesLoaded) { + await this.retrieveProfiles(); + this.store.setProfilesLoaded(); + } + await this.loadAccount(); + } + + async retrieveProfiles(): Promise { + try { + const res = await axios.get('management/info'); + if (res.data?.activeProfiles) { + this.store.setRibbonOnProfiles(res.data['display-ribbon-on-profiles']); + this.store.setActiveProfiles(res.data.activeProfiles); + } + return true; + } catch { + return false; + } + } + + async retrieveAccount(): Promise { + try { + const response = await axios.get('api/account'); + if (response.status === 200 && response.data?.login) { + const account = response.data; + this.store.setAuthentication(account); + return true; + } + } catch { + // Ignore error + } + + this.store.logout(); + return false; + } + + async loadAccount() { + if (this.store.logon) { + return this.store.logon; + } + const token = localStorage.getItem(AUTHENTICATION_TOKEN_KEY) ?? sessionStorage.getItem(AUTHENTICATION_TOKEN_KEY); + if (this.authenticated && this.userAuthorities && token) { + return; + } + + const promise = this.retrieveAccount(); + this.store.authenticate(promise); + promise.then(() => this.store.authenticate(null)); + await promise; + } + + async hasAnyAuthorityAndCheckAuth(authorities: any): Promise { + if (typeof authorities === 'string') { + authorities = [authorities]; + } + + return this.checkAuthorities(authorities); + } + + get authenticated(): boolean { + return this.store.authenticated; + } + + get userAuthorities(): string[] { + return this.store.account?.authorities; + } + + private checkAuthorities(authorities: string[]): boolean { + if (this.userAuthorities) { + for (const authority of authorities) { + if (this.userAuthorities.includes(authority)) { + return true; + } + } + } + return false; + } +} diff --git a/src/main/webapp/app/account/activate/activate.component.spec.ts b/src/main/webapp/app/account/activate/activate.component.spec.ts new file mode 100644 index 0000000..62844c2 --- /dev/null +++ b/src/main/webapp/app/account/activate/activate.component.spec.ts @@ -0,0 +1,59 @@ +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { createTestingPinia } from '@pinia/testing'; +import { type ComponentMountingOptions, shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import Activate from './activate.vue'; + +type ActivateComponentType = InstanceType; + +const route = { query: { key: 'key' } }; + +vi.mock('vue-router', () => ({ + useRoute: () => route, +})); + +const axiosStub = { + get: vi.spyOn(axios, 'get'), + post: vi.spyOn(axios, 'post'), +}; + +describe('Activate Component', () => { + let activate: ActivateComponentType; + let mountOptions: ComponentMountingOptions; + + beforeEach(() => { + mountOptions = { + global: { + plugins: [createTestingPinia()], + }, + }; + }); + + afterAll(() => { + vi.restoreAllMocks(); + }); + + it('should display error when activation fails', async () => { + axiosStub.get.mockRejectedValue({}); + + const wrapper = shallowMount(Activate, mountOptions); + activate = wrapper.vm; + await activate.$nextTick(); + + expect(activate.error).toBeTruthy(); + expect(activate.success).toBeFalsy(); + }); + + it('should display success when activation succeeds', async () => { + axiosStub.get.mockResolvedValue({}); + + const wrapper = shallowMount(Activate, mountOptions); + activate = wrapper.vm; + await activate.$nextTick(); + + expect(activate.error).toBeFalsy(); + expect(activate.success).toBeTruthy(); + }); +}); diff --git a/src/main/webapp/app/account/activate/activate.component.ts b/src/main/webapp/app/account/activate/activate.component.ts new file mode 100644 index 0000000..7877a2a --- /dev/null +++ b/src/main/webapp/app/account/activate/activate.component.ts @@ -0,0 +1,38 @@ +import { type Ref, defineComponent, inject, onMounted, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; +import { useRoute } from 'vue-router'; + +import { useLoginModal } from '@/account/login-modal'; + +import ActivateService from './activate.service'; + +export default defineComponent({ + setup() { + const activateService = inject('activateService', () => new ActivateService(), true); + const { showLogin } = useLoginModal(); + const route = useRoute(); + + const success: Ref = ref(false); + const error: Ref = ref(false); + + onMounted(async () => { + const key = Array.isArray(route.query.key) ? route.query.key[0] : route.query.key; + try { + await activateService.activateAccount(key); + success.value = true; + error.value = false; + } catch { + error.value = true; + success.value = false; + } + }); + + return { + activateService, + showLogin, + success, + error, + t$: useI18n().t, + }; + }, +}); diff --git a/src/main/webapp/app/account/activate/activate.service.ts b/src/main/webapp/app/account/activate/activate.service.ts new file mode 100644 index 0000000..dee5d0b --- /dev/null +++ b/src/main/webapp/app/account/activate/activate.service.ts @@ -0,0 +1,13 @@ +import axios, { type AxiosInstance } from 'axios'; + +export default class ActivateService { + private readonly axios: AxiosInstance; + + constructor() { + this.axios = axios; + } + + activateAccount(key: string): Promise { + return this.axios.get(`api/activate?key=${key}`); + } +} diff --git a/src/main/webapp/app/account/activate/activate.vue b/src/main/webapp/app/account/activate/activate.vue new file mode 100644 index 0000000..a902f51 --- /dev/null +++ b/src/main/webapp/app/account/activate/activate.vue @@ -0,0 +1,17 @@ + + + diff --git a/src/main/webapp/app/account/change-password/change-password.component.spec.ts b/src/main/webapp/app/account/change-password/change-password.component.spec.ts new file mode 100644 index 0000000..228adf7 --- /dev/null +++ b/src/main/webapp/app/account/change-password/change-password.component.spec.ts @@ -0,0 +1,83 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { computed } from 'vue'; + +import { createTestingPinia } from '@pinia/testing'; +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import ChangePassword from './change-password.vue'; + +type ChangePasswordComponentType = InstanceType; + +const pinia = createTestingPinia(); + +const axiosStub = { + get: vi.spyOn(axios, 'get'), + post: vi.spyOn(axios, 'post'), +}; + +describe('ChangePassword Component', () => { + let changePassword: ChangePasswordComponentType; + + beforeEach(() => { + axiosStub.get.mockResolvedValue({}); + axiosStub.post.mockReset(); + + const wrapper = shallowMount(ChangePassword, { + global: { + plugins: [pinia], + provide: { + currentUsername: computed(() => 'username'), + }, + }, + }); + changePassword = wrapper.vm; + }); + + it('should show error if passwords do not match', () => { + // GIVEN + changePassword.resetPassword = { newPassword: 'password1', confirmPassword: 'password2' }; + // WHEN + changePassword.changePassword(); + // THEN + expect(changePassword.doNotMatch).toBe('ERROR'); + expect(changePassword.error).toBeNull(); + expect(changePassword.success).toBeNull(); + }); + + it('should call Auth.changePassword when passwords match and set success to OK upon success', async () => { + // GIVEN + changePassword.resetPassword = { currentPassword: 'password1', newPassword: 'password1', confirmPassword: 'password1' }; + axiosStub.post.mockResolvedValue({}); + + // WHEN + changePassword.changePassword(); + await changePassword.$nextTick(); + + // THEN + expect(axiosStub.post).toHaveBeenCalledWith('api/account/change-password', { + currentPassword: 'password1', + newPassword: 'password1', + }); + + expect(changePassword.doNotMatch).toBeNull(); + expect(changePassword.error).toBeNull(); + expect(changePassword.success).toBe('OK'); + }); + + it('should notify of error if change password fails', async () => { + // GIVEN + changePassword.resetPassword = { currentPassword: 'password1', newPassword: 'password1', confirmPassword: 'password1' }; + axiosStub.post.mockRejectedValue({}); + + // WHEN + changePassword.changePassword(); + await changePassword.$nextTick(); + + // THEN + expect(changePassword.doNotMatch).toBeNull(); + expect(changePassword.success).toBeNull(); + await changePassword.$nextTick(); + expect(changePassword.error).toBe('ERROR'); + }); +}); diff --git a/src/main/webapp/app/account/change-password/change-password.component.ts b/src/main/webapp/app/account/change-password/change-password.component.ts new file mode 100644 index 0000000..b3424cc --- /dev/null +++ b/src/main/webapp/app/account/change-password/change-password.component.ts @@ -0,0 +1,71 @@ +import { type ComputedRef, type Ref, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { useVuelidate } from '@vuelidate/core'; +import { maxLength, minLength, required, sameAs } from '@vuelidate/validators'; +import axios from 'axios'; + +export default defineComponent({ + validations() { + return { + resetPassword: { + currentPassword: { + required, + }, + newPassword: { + required, + minLength: minLength(4), + maxLength: maxLength(254), + }, + confirmPassword: { + sameAsPassword: sameAs(this.resetPassword.newPassword), + }, + }, + }; + }, + setup() { + const username = inject>('currentUsername'); + const success: Ref = ref(null); + const error: Ref = ref(null); + const doNotMatch: Ref = ref(null); + const resetPassword: Ref = ref({ + currentPassword: null, + newPassword: null, + confirmPassword: null, + }); + + return { + username, + success, + error, + doNotMatch, + resetPassword, + v$: useVuelidate(), + t$: useI18n().t, + }; + }, + methods: { + changePassword(): void { + if (this.resetPassword.newPassword !== this.resetPassword.confirmPassword) { + this.error = null; + this.success = null; + this.doNotMatch = 'ERROR'; + } else { + this.doNotMatch = null; + axios + .post('api/account/change-password', { + currentPassword: this.resetPassword.currentPassword, + newPassword: this.resetPassword.newPassword, + }) + .then(() => { + this.success = 'OK'; + this.error = null; + }) + .catch(() => { + this.success = null; + this.error = 'ERROR'; + }); + } + }, + }, +}); diff --git a/src/main/webapp/app/account/change-password/change-password.vue b/src/main/webapp/app/account/change-password/change-password.vue new file mode 100644 index 0000000..123d705 --- /dev/null +++ b/src/main/webapp/app/account/change-password/change-password.vue @@ -0,0 +1,92 @@ + + + diff --git a/src/main/webapp/app/account/login-form/login-form.component.spec.ts b/src/main/webapp/app/account/login-form/login-form.component.spec.ts new file mode 100644 index 0000000..df5310b --- /dev/null +++ b/src/main/webapp/app/account/login-form/login-form.component.spec.ts @@ -0,0 +1,125 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { type RouteLocation } from 'vue-router'; + +import { createTestingPinia } from '@pinia/testing'; +import { type MountingOptions, shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import { AUTHENTICATION_TOKEN_KEY } from '@/shared/jhipster/constants'; +import { useStore } from '@/store'; +import AccountService from '../account.service'; + +import LoginForm from './login-form.vue'; + +type LoginFormComponentType = InstanceType; + +let route: Partial; +const routerGoMock = vi.fn(); +vi.mock('vue-router', () => ({ + useRoute: () => route, + useRouter: () => ({ go: routerGoMock }), +})); + +const axiosStub = { + get: vi.spyOn(axios, 'get'), + post: vi.spyOn(axios, 'post'), +}; + +describe('LoginForm Component', () => { + let loginForm: LoginFormComponentType; + + beforeEach(() => { + route = {}; + axiosStub.get.mockResolvedValue({}); + axiosStub.post.mockReset(); + + const pinia = createTestingPinia(); + const store = useStore(); + + const globalOptions: MountingOptions['global'] = { + stubs: { + 'b-alert': true, + 'b-button': true, + 'b-form': true, + 'b-form-input': true, + 'b-form-group': true, + 'b-form-checkbox': true, + 'b-link': true, + }, + plugins: [pinia], + provide: { + accountService: new AccountService(store), + }, + }; + const wrapper = shallowMount(LoginForm, { global: globalOptions }); + + loginForm = wrapper.vm; + }); + + it('should not store token if authentication is KO', async () => { + // GIVEN + loginForm.login = 'login'; + loginForm.password = 'pwd'; + loginForm.rememberMe = true; + axiosStub.post.mockRejectedValue(new Error()); + + // WHEN + loginForm.doLogin(); + await loginForm.$nextTick(); + + // THEN + expect(axiosStub.post).toHaveBeenCalledWith('api/authenticate', { + username: 'login', + password: 'pwd', + rememberMe: true, + }); + await loginForm.$nextTick(); + expect(loginForm.authenticationError).toBeTruthy(); + }); + + it('should store token if authentication is OK', async () => { + // GIVEN + loginForm.login = 'login'; + loginForm.password = 'pwd'; + loginForm.rememberMe = true; + const jwtSecret = 'jwt-secret'; + axiosStub.post.mockResolvedValue({ headers: { authorization: `Bearer ${jwtSecret}` } }); + + // WHEN + loginForm.doLogin(); + await loginForm.$nextTick(); + + // THEN + expect(axiosStub.post).toHaveBeenCalledWith('api/authenticate', { + username: 'login', + password: 'pwd', + rememberMe: true, + }); + + expect(loginForm.authenticationError).toBeFalsy(); + expect(localStorage.getItem(AUTHENTICATION_TOKEN_KEY)).toEqual(jwtSecret); + }); + + it('should store token if authentication is OK in session', async () => { + // GIVEN + loginForm.login = 'login'; + loginForm.password = 'pwd'; + loginForm.rememberMe = false; + const jwtSecret = 'jwt-secret'; + axiosStub.post.mockResolvedValue({ headers: { authorization: `Bearer ${jwtSecret}` } }); + + // WHEN + loginForm.doLogin(); + await loginForm.$nextTick(); + + // THEN + expect(axiosStub.post).toHaveBeenCalledWith('api/authenticate', { + username: 'login', + password: 'pwd', + rememberMe: false, + }); + + expect(loginForm.authenticationError).toBeFalsy(); + expect(sessionStorage.getItem(AUTHENTICATION_TOKEN_KEY)).toEqual(jwtSecret); + }); +}); diff --git a/src/main/webapp/app/account/login-form/login-form.component.ts b/src/main/webapp/app/account/login-form/login-form.component.ts new file mode 100644 index 0000000..6a41dae --- /dev/null +++ b/src/main/webapp/app/account/login-form/login-form.component.ts @@ -0,0 +1,62 @@ +import { type Ref, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; +import { useRoute, useRouter } from 'vue-router'; + +import axios from 'axios'; + +import { useLoginModal } from '@/account/login-modal'; +import { AUTHENTICATION_TOKEN_KEY } from '@/shared/jhipster/constants'; +import type AccountService from '../account.service'; + +export default defineComponent({ + setup() { + const authenticationError: Ref = ref(false); + const login: Ref = ref(null); + const password: Ref = ref(null); + const rememberMe: Ref = ref(false); + + const { hideLogin } = useLoginModal(); + const route = useRoute(); + const router = useRouter(); + + const previousState = () => router.go(-1); + + const accountService = inject('accountService'); + + const doLogin = async () => { + const data = { username: login.value, password: password.value, rememberMe: rememberMe.value }; + try { + const result = await axios.post('api/authenticate', data); + const bearerToken = result.headers.authorization; + if (bearerToken?.startsWith('Bearer ')) { + const jwt = bearerToken.slice(7, bearerToken.length); + if (rememberMe.value) { + localStorage.setItem(AUTHENTICATION_TOKEN_KEY, jwt); + sessionStorage.removeItem(AUTHENTICATION_TOKEN_KEY); + } else { + sessionStorage.setItem(AUTHENTICATION_TOKEN_KEY, jwt); + localStorage.removeItem(AUTHENTICATION_TOKEN_KEY); + } + } + + authenticationError.value = false; + hideLogin(); + await accountService.retrieveAccount(); + if (route.path === '/forbidden') { + previousState(); + } + } catch { + authenticationError.value = true; + } + }; + return { + authenticationError, + login, + password, + rememberMe, + accountService, + doLogin, + t$: useI18n().t, + }; + }, +}); diff --git a/src/main/webapp/app/account/login-form/login-form.vue b/src/main/webapp/app/account/login-form/login-form.vue new file mode 100644 index 0000000..73ed27a --- /dev/null +++ b/src/main/webapp/app/account/login-form/login-form.vue @@ -0,0 +1,62 @@ + + + diff --git a/src/main/webapp/app/account/login-modal.ts b/src/main/webapp/app/account/login-modal.ts new file mode 100644 index 0000000..240b8ea --- /dev/null +++ b/src/main/webapp/app/account/login-modal.ts @@ -0,0 +1,21 @@ +import { ref } from 'vue'; + +import { defineStore } from 'pinia'; + +export const useLoginModal = defineStore('login', () => { + const loginModalOpen = ref(false); + + function showLogin() { + loginModalOpen.value = true; + } + + function hideLogin() { + loginModalOpen.value = false; + } + + return { + loginModalOpen, + showLogin, + hideLogin, + }; +}); diff --git a/src/main/webapp/app/account/register/register.component.spec.ts b/src/main/webapp/app/account/register/register.component.spec.ts new file mode 100644 index 0000000..d2acd54 --- /dev/null +++ b/src/main/webapp/app/account/register/register.component.spec.ts @@ -0,0 +1,142 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { computed } from 'vue'; + +import { createTestingPinia } from '@pinia/testing'; +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import { useLoginModal } from '@/account/login-modal'; +import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from '@/shared/jhipster/error.constants'; + +import Register from './register.vue'; + +type RegisterComponentType = InstanceType; + +const axiosStub = { + get: vi.spyOn(axios, 'get'), + post: vi.spyOn(axios, 'post'), +}; + +describe('Register Component', () => { + let register: RegisterComponentType; + const filledRegisterAccount = { + email: 'jhi@pster.net', + langKey: 'en', + login: 'jhi', + password: 'jhipster', + }; + + beforeEach(() => { + axiosStub.get.mockResolvedValue({}); + axiosStub.post.mockReset(); + + const wrapper = shallowMount(Register, { + global: { + plugins: [createTestingPinia()], + provide: { + currentLanguage: computed(() => 'en'), + }, + }, + }); + register = wrapper.vm; + }); + + it('should set all default values correctly', () => { + expect(register.success).toBe(false); + expect(register.error).toBe(''); + expect(register.errorEmailExists).toBe(''); + expect(register.errorUserExists).toBe(''); + expect(register.confirmPassword).toBeNull(); + expect(register.registerAccount.login).toBeUndefined(); + expect(register.registerAccount.password).toBeUndefined(); + expect(register.registerAccount.email).toBeUndefined(); + }); + + it('should open login modal when asked to', () => { + const login = useLoginModal(); + register.showLogin(); + expect(login.showLogin).toHaveBeenCalledOnce(); + }); + + it('should register when password match', async () => { + axiosStub.post.mockResolvedValue(undefined); + register.registerAccount = filledRegisterAccount; + register.confirmPassword = filledRegisterAccount.password; + register.register(); + await register.$nextTick(); + + expect(axiosStub.post).toHaveBeenCalledWith('api/register', { + email: 'jhi@pster.net', + langKey: 'en', + login: 'jhi', + password: 'jhipster', + }); + expect(register.success).toBe(true); + expect(register.error).toBeNull(); + expect(register.errorEmailExists).toBeNull(); + expect(register.errorUserExists).toBeNull(); + }); + + it('should register when password match but throw error when login already exist', async () => { + const error = { response: { status: 400, data: { type: LOGIN_ALREADY_USED_TYPE } } }; + axiosStub.post.mockRejectedValue(error); + register.registerAccount = filledRegisterAccount; + register.confirmPassword = filledRegisterAccount.password; + register.register(); + await register.$nextTick(); + + expect(axiosStub.post).toHaveBeenCalledWith('api/register', { + email: 'jhi@pster.net', + langKey: 'en', + login: 'jhi', + password: 'jhipster', + }); + await register.$nextTick(); + expect(register.success).toBeNull(); + expect(register.error).toBeNull(); + expect(register.errorEmailExists).toBeNull(); + expect(register.errorUserExists).toBe('ERROR'); + }); + + it('should register when password match but throw error when email already used', async () => { + const error = { response: { status: 400, data: { type: EMAIL_ALREADY_USED_TYPE } } }; + axiosStub.post.mockRejectedValue(error); + register.registerAccount = filledRegisterAccount; + register.confirmPassword = filledRegisterAccount.password; + register.register(); + await register.$nextTick(); + + expect(axiosStub.post).toHaveBeenCalledWith('api/register', { + email: 'jhi@pster.net', + langKey: 'en', + login: 'jhi', + password: 'jhipster', + }); + await register.$nextTick(); + expect(register.success).toBeNull(); + expect(register.error).toBeNull(); + expect(register.errorEmailExists).toBe('ERROR'); + expect(register.errorUserExists).toBeNull(); + }); + + it('should register when password match but throw error', async () => { + const error = { response: { status: 400, data: { type: 'unknown' } } }; + axiosStub.post.mockRejectedValue(error); + register.registerAccount = filledRegisterAccount; + register.confirmPassword = filledRegisterAccount.password; + register.register(); + await register.$nextTick(); + + expect(axiosStub.post).toHaveBeenCalledWith('api/register', { + email: 'jhi@pster.net', + langKey: 'en', + login: 'jhi', + password: 'jhipster', + }); + await register.$nextTick(); + expect(register.success).toBeNull(); + expect(register.errorEmailExists).toBeNull(); + expect(register.errorUserExists).toBeNull(); + expect(register.error).toBe('ERROR'); + }); +}); diff --git a/src/main/webapp/app/account/register/register.component.ts b/src/main/webapp/app/account/register/register.component.ts new file mode 100644 index 0000000..85fbe52 --- /dev/null +++ b/src/main/webapp/app/account/register/register.component.ts @@ -0,0 +1,98 @@ +import { type Ref, computed, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { useVuelidate } from '@vuelidate/core'; +import { email, helpers, maxLength, minLength, required, sameAs } from '@vuelidate/validators'; + +import { useLoginModal } from '@/account/login-modal'; +import RegisterService from '@/account/register/register.service'; +import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from '@/shared/jhipster/error.constants'; + +const loginPattern = helpers.regex(/^[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$|^[_.@A-Za-z0-9-]+$/); + +export default defineComponent({ + name: 'Register', + validations() { + return { + registerAccount: { + login: { + required, + minLength: minLength(1), + maxLength: maxLength(50), + pattern: loginPattern, + }, + email: { + required, + minLength: minLength(5), + maxLength: maxLength(254), + email, + }, + password: { + required, + minLength: minLength(4), + maxLength: maxLength(254), + }, + }, + confirmPassword: { + required, + minLength: minLength(4), + maxLength: maxLength(50), + sameAsPassword: sameAs(this.registerAccount.password), + }, + }; + }, + setup() { + const { showLogin } = useLoginModal(); + const registerService = inject('registerService', () => new RegisterService(), true); + const currentLanguage = inject('currentLanguage', () => computed(() => navigator.language ?? 'en'), true); + + const error: Ref = ref(''); + const errorEmailExists: Ref = ref(''); + const errorUserExists: Ref = ref(''); + const success: Ref = ref(false); + + const confirmPassword: Ref = ref(null); + const registerAccount: Ref = ref({ + login: undefined, + email: undefined, + password: undefined, + }); + + return { + showLogin, + currentLanguage, + registerService, + error, + errorEmailExists, + errorUserExists, + success, + confirmPassword, + registerAccount, + v$: useVuelidate(), + t$: useI18n().t, + }; + }, + methods: { + register(): void { + this.error = null; + this.errorUserExists = null; + this.errorEmailExists = null; + this.registerAccount.langKey = this.currentLanguage; + this.registerService + .processRegistration(this.registerAccount) + .then(() => { + this.success = true; + }) + .catch(error => { + this.success = null; + if (error.response.status === 400 && error.response.data.type === LOGIN_ALREADY_USED_TYPE) { + this.errorUserExists = 'ERROR'; + } else if (error.response.status === 400 && error.response.data.type === EMAIL_ALREADY_USED_TYPE) { + this.errorEmailExists = 'ERROR'; + } else { + this.error = 'ERROR'; + } + }); + }, + }, +}); diff --git a/src/main/webapp/app/account/register/register.service.ts b/src/main/webapp/app/account/register/register.service.ts new file mode 100644 index 0000000..77b7cdc --- /dev/null +++ b/src/main/webapp/app/account/register/register.service.ts @@ -0,0 +1,7 @@ +import axios from 'axios'; + +export default class RegisterService { + processRegistration(account: any): Promise { + return axios.post('api/register', account); + } +} diff --git a/src/main/webapp/app/account/register/register.vue b/src/main/webapp/app/account/register/register.vue new file mode 100644 index 0000000..130d468 --- /dev/null +++ b/src/main/webapp/app/account/register/register.vue @@ -0,0 +1,152 @@ + + + diff --git a/src/main/webapp/app/account/reset-password/finish/reset-password-finish.component.spec.ts b/src/main/webapp/app/account/reset-password/finish/reset-password-finish.component.spec.ts new file mode 100644 index 0000000..732f50b --- /dev/null +++ b/src/main/webapp/app/account/reset-password/finish/reset-password-finish.component.spec.ts @@ -0,0 +1,59 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { createTestingPinia } from '@pinia/testing'; +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import ResetPasswordFinish from './reset-password-finish.vue'; + +type ResetPasswordFinishComponentType = InstanceType; + +const axiosStub = { + get: vi.spyOn(axios, 'get'), + post: vi.spyOn(axios, 'post'), +}; + +describe('ResetPasswordFinish Component', () => { + let resetPasswordFinish: ResetPasswordFinishComponentType; + + beforeEach(() => { + axiosStub.post.mockReset(); + const wrapper = shallowMount(ResetPasswordFinish, { + global: { + plugins: [createTestingPinia()], + }, + }); + resetPasswordFinish = wrapper.vm; + }); + + it('should reset finish be a success', async () => { + // Given + axiosStub.post.mockResolvedValue(undefined); + + // When + await resetPasswordFinish.finishReset(); + + // Then + expect(resetPasswordFinish.success).toBeTruthy(); + }); + + it('should reset request fail as an error', async () => { + // Given + axiosStub.post.mockRejectedValue({ + response: { + status: null, + data: { + type: null, + }, + }, + }); + + // When + await resetPasswordFinish.finishReset(); + await resetPasswordFinish.$nextTick(); + + // Then + expect(resetPasswordFinish.success).toBeNull(); + expect(resetPasswordFinish.error).toEqual('ERROR'); + }); +}); diff --git a/src/main/webapp/app/account/reset-password/finish/reset-password-finish.component.ts b/src/main/webapp/app/account/reset-password/finish/reset-password-finish.component.ts new file mode 100644 index 0000000..d350d3d --- /dev/null +++ b/src/main/webapp/app/account/reset-password/finish/reset-password-finish.component.ts @@ -0,0 +1,77 @@ +import { type Ref, defineComponent, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { useVuelidate } from '@vuelidate/core'; +import { maxLength, minLength, required, sameAs } from '@vuelidate/validators'; +import axios from 'axios'; + +import { useLoginModal } from '@/account/login-modal'; + +export default defineComponent({ + name: 'ResetPasswordFinish', + validations() { + return { + resetAccount: { + newPassword: { + required, + minLength: minLength(4), + maxLength: maxLength(254), + }, + confirmPassword: { + sameAsPassword: sameAs(this.resetAccount.newPassword), + }, + }, + }; + }, + setup() { + const { showLogin } = useLoginModal(); + + const doNotMatch: Ref = ref(null); + const success: Ref = ref(null); + const error: Ref = ref(null); + const keyMissing: Ref = ref(false); + const key: Ref = ref(null); + const resetAccount: Ref = ref({ + newPassword: null, + confirmPassword: null, + }); + + return { + showLogin, + doNotMatch, + success, + error, + keyMissing, + key, + resetAccount, + v$: useVuelidate(), + t$: useI18n().t, + }; + }, + created(): void { + if (this.$route?.query?.key !== undefined) { + this.key = this.$route.query.key; + } + this.keyMissing = !this.key; + }, + methods: { + finishReset() { + this.doNotMatch = null; + this.success = null; + this.error = null; + if (this.resetAccount.newPassword !== this.resetAccount.confirmPassword) { + this.doNotMatch = 'ERROR'; + } else { + return axios + .post('api/account/reset-password/finish', { key: this.key, newPassword: this.resetAccount.newPassword }) + .then(() => { + this.success = 'OK'; + }) + .catch(() => { + this.success = null; + this.error = 'ERROR'; + }); + } + }, + }, +}); diff --git a/src/main/webapp/app/account/reset-password/finish/reset-password-finish.vue b/src/main/webapp/app/account/reset-password/finish/reset-password-finish.vue new file mode 100644 index 0000000..2140b24 --- /dev/null +++ b/src/main/webapp/app/account/reset-password/finish/reset-password-finish.vue @@ -0,0 +1,85 @@ + + + diff --git a/src/main/webapp/app/account/reset-password/init/reset-password-init.component.spec.ts b/src/main/webapp/app/account/reset-password/init/reset-password-init.component.spec.ts new file mode 100644 index 0000000..ffc6c58 --- /dev/null +++ b/src/main/webapp/app/account/reset-password/init/reset-password-init.component.spec.ts @@ -0,0 +1,54 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import ResetPasswordInit from './reset-password-init.vue'; + +type ResetPasswordInitComponentType = InstanceType; + +const axiosStub = { + get: vi.spyOn(axios, 'get'), + post: vi.spyOn(axios, 'post'), +}; + +describe('ResetPasswordInit Component', () => { + let resetPasswordInit: ResetPasswordInitComponentType; + + beforeEach(() => { + axiosStub.post.mockReset(); + const wrapper = shallowMount(ResetPasswordInit, {}); + resetPasswordInit = wrapper.vm; + }); + + it('should reset request be a success', async () => { + // Given + axiosStub.post.mockResolvedValue(undefined); + + // When + await resetPasswordInit.requestReset(); + + // Then + expect(resetPasswordInit.success).toBeTruthy(); + }); + + it('should reset request fail as an error', async () => { + // Given + axiosStub.post.mockRejectedValue({ + response: { + status: null, + data: { + type: null, + }, + }, + }); + + // When + await resetPasswordInit.requestReset(); + await resetPasswordInit.$nextTick(); + + // Then + expect(resetPasswordInit.success).toBe(false); + expect(resetPasswordInit.error).toEqual('ERROR'); + }); +}); diff --git a/src/main/webapp/app/account/reset-password/init/reset-password-init.component.ts b/src/main/webapp/app/account/reset-password/init/reset-password-init.component.ts new file mode 100644 index 0000000..34dd377 --- /dev/null +++ b/src/main/webapp/app/account/reset-password/init/reset-password-init.component.ts @@ -0,0 +1,60 @@ +import { type Ref, defineComponent, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { useVuelidate } from '@vuelidate/core'; +import { email, maxLength, minLength, required } from '@vuelidate/validators'; +import axios from 'axios'; + +const validations = { + resetAccount: { + email: { + required, + minLength: minLength(5), + maxLength: maxLength(254), + email, + }, + }, +}; + +interface ResetAccount { + email: string | null; +} + +export default defineComponent({ + name: 'ResetPasswordInit', + validations, + setup() { + const error: Ref = ref(null); + const success: Ref = ref(false); + const resetAccount: Ref = ref({ + email: null, + }); + + return { + error, + success, + resetAccount, + v$: useVuelidate(), + t$: useI18n().t, + }; + }, + methods: { + async requestReset(): Promise { + this.error = null; + this.success = false; + await axios + .post('api/account/reset-password/init', this.resetAccount.email, { + headers: { + 'content-type': 'text/plain', + }, + }) + .then(() => { + this.success = true; + }) + .catch(() => { + this.success = false; + this.error = 'ERROR'; + }); + }, + }, +}); diff --git a/src/main/webapp/app/account/reset-password/init/reset-password-init.vue b/src/main/webapp/app/account/reset-password/init/reset-password-init.vue new file mode 100644 index 0000000..60a7476 --- /dev/null +++ b/src/main/webapp/app/account/reset-password/init/reset-password-init.vue @@ -0,0 +1,56 @@ + + + diff --git a/src/main/webapp/app/account/settings/settings.component.spec.ts b/src/main/webapp/app/account/settings/settings.component.spec.ts new file mode 100644 index 0000000..93c1823 --- /dev/null +++ b/src/main/webapp/app/account/settings/settings.component.spec.ts @@ -0,0 +1,113 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { createTestingPinia } from '@pinia/testing'; +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import { EMAIL_ALREADY_USED_TYPE } from '@/shared/jhipster/error.constants'; +import { useStore } from '@/store'; + +import Settings from './settings.vue'; + +type SettingsComponentType = InstanceType; + +const pinia = createTestingPinia({ stubActions: false }); + +const store = useStore(); + +const axiosStub = { + get: vi.spyOn(axios, 'get'), + post: vi.spyOn(axios, 'post'), +}; + +describe('Settings Component', () => { + let settings: SettingsComponentType; + const account = { + firstName: 'John', + lastName: 'Doe', + email: 'john.doe@jhipster.org', + }; + + beforeEach(() => { + axiosStub.get.mockResolvedValue({}); + axiosStub.post.mockReset(); + + store.setAuthentication(account); + const wrapper = shallowMount(Settings, { + global: { + plugins: [pinia], + }, + }); + settings = wrapper.vm; + }); + + it('should send the current identity upon save', async () => { + // GIVEN + axiosStub.post.mockResolvedValue({}); + + // WHEN + await settings.save(); + await settings.$nextTick(); + + // THEN + expect(axiosStub.post).toHaveBeenCalledWith('api/account', account); + }); + + it('should notify of success upon successful save', async () => { + // GIVEN + axiosStub.post.mockResolvedValue(account); + + // WHEN + await settings.save(); + await settings.$nextTick(); + + // THEN + expect(settings.error).toBeNull(); + expect(settings.success).toBe('OK'); + }); + + it('should notify of error upon failed save', async () => { + // GIVEN + const error = { response: { status: 417 } }; + axiosStub.post.mockRejectedValue(error); + + // WHEN + await settings.save(); + await settings.$nextTick(); + + // THEN + expect(settings.error).toEqual('ERROR'); + expect(settings.errorEmailExists).toBeNull(); + expect(settings.success).toBeNull(); + }); + + it('should notify of error upon error 400', async () => { + // GIVEN + const error = { response: { status: 400, data: {} } }; + axiosStub.post.mockRejectedValue(error); + + // WHEN + await settings.save(); + await settings.$nextTick(); + + // THEN + expect(settings.error).toEqual('ERROR'); + expect(settings.errorEmailExists).toBeNull(); + expect(settings.success).toBeNull(); + }); + + it('should notify of error upon email already used', async () => { + // GIVEN + const error = { response: { status: 400, data: { type: EMAIL_ALREADY_USED_TYPE } } }; + axiosStub.post.mockRejectedValue(error); + + // WHEN + await settings.save(); + await settings.$nextTick(); + + // THEN + expect(settings.errorEmailExists).toEqual('ERROR'); + expect(settings.error).toBeNull(); + expect(settings.success).toBeNull(); + }); +}); diff --git a/src/main/webapp/app/account/settings/settings.component.ts b/src/main/webapp/app/account/settings/settings.component.ts new file mode 100644 index 0000000..353ef77 --- /dev/null +++ b/src/main/webapp/app/account/settings/settings.component.ts @@ -0,0 +1,78 @@ +import { type ComputedRef, type Ref, computed, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { useVuelidate } from '@vuelidate/core'; +import { email, maxLength, minLength, required } from '@vuelidate/validators'; +import axios from 'axios'; + +import languages from '@/shared/config/languages'; +import { EMAIL_ALREADY_USED_TYPE } from '@/shared/jhipster/error.constants'; +import { useStore } from '@/store'; + +const validations = { + settingsAccount: { + firstName: { + required, + minLength: minLength(1), + maxLength: maxLength(50), + }, + lastName: { + required, + minLength: minLength(1), + maxLength: maxLength(50), + }, + email: { + required, + email, + minLength: minLength(5), + maxLength: maxLength(254), + }, + }, +}; + +export default defineComponent({ + name: 'Settings', + validations, + setup() { + const store = useStore(); + + const success: Ref = ref(null); + const error: Ref = ref(null); + const errorEmailExists: Ref = ref(null); + + const settingsAccount = computed(() => store.account); + const username = inject>('currentUsername', () => computed(() => store.account?.login), true); + + return { + success, + error, + errorEmailExists, + settingsAccount, + username, + v$: useVuelidate(), + languages: languages(), + t$: useI18n().t, + }; + }, + methods: { + save() { + this.error = null; + this.errorEmailExists = null; + return axios + .post('api/account', this.settingsAccount) + .then(() => { + this.error = null; + this.success = 'OK'; + this.errorEmailExists = null; + }) + .catch(ex => { + this.success = null; + this.error = 'ERROR'; + if (ex.response.status === 400 && ex.response.data.type === EMAIL_ALREADY_USED_TYPE) { + this.errorEmailExists = 'ERROR'; + this.error = null; + } + }); + }, + }, +}); diff --git a/src/main/webapp/app/account/settings/settings.vue b/src/main/webapp/app/account/settings/settings.vue new file mode 100644 index 0000000..70dc555 --- /dev/null +++ b/src/main/webapp/app/account/settings/settings.vue @@ -0,0 +1,114 @@ + + + diff --git a/src/main/webapp/app/admin/configuration/configuration.component.spec.ts b/src/main/webapp/app/admin/configuration/configuration.component.spec.ts new file mode 100644 index 0000000..120d867 --- /dev/null +++ b/src/main/webapp/app/admin/configuration/configuration.component.spec.ts @@ -0,0 +1,77 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import Configuration from './configuration.vue'; + +type ConfigurationComponentType = InstanceType; + +const axiosStub = { + get: vi.spyOn(axios, 'get'), +}; + +describe('Configuration Component', () => { + let configuration: ConfigurationComponentType; + + beforeEach(() => { + axiosStub.get.mockReset(); + axiosStub.get.mockResolvedValue({ + data: { contexts: [{ beans: [{ prefix: 'A' }, { prefix: 'B' }] }], propertySources: [{ properties: { key1: { value: 'value' } } }] }, + }); + const wrapper = shallowMount(Configuration, { + global: { + stubs: { + 'jhi-sort-indicator': true, + }, + }, + }); + configuration = wrapper.vm; + }); + + describe('OnRouteEnter', () => { + it('should set all default values correctly', () => { + expect(configuration.configKeys).toEqual([]); + expect(configuration.filtered).toBe(''); + expect(configuration.orderProp).toBe('prefix'); + expect(configuration.reverse).toBe(false); + }); + it('Should call load all on init', async () => { + // WHEN + configuration.init(); + await configuration.$nextTick(); + + // THEN + expect(axiosStub.get).toHaveBeenCalledWith('management/env'); + expect(axiosStub.get).toHaveBeenCalledWith('management/configprops'); + }); + }); + + describe('keys method', () => { + it('should return the keys of an Object', () => { + // GIVEN + const data = { + key1: 'test', + key2: 'test2', + }; + + // THEN + expect(configuration.keys(data)).toEqual(['key1', 'key2']); + expect(configuration.keys(undefined)).toEqual([]); + }); + }); + + describe('changeOrder function', () => { + it('should change order', () => { + // GIVEN + const rev = configuration.reverse; + + // WHEN + configuration.changeOrder('prefix'); + + // THEN + expect(configuration.orderProp).toBe('prefix'); + expect(configuration.reverse).toBe(!rev); + }); + }); +}); diff --git a/src/main/webapp/app/admin/configuration/configuration.component.ts b/src/main/webapp/app/admin/configuration/configuration.component.ts new file mode 100644 index 0000000..fd478ce --- /dev/null +++ b/src/main/webapp/app/admin/configuration/configuration.component.ts @@ -0,0 +1,67 @@ +import { type Ref, computed, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { orderAndFilterBy } from '@/shared/computables'; + +import ConfigurationService from './configuration.service'; + +export default defineComponent({ + name: 'JhiConfiguration', + setup() { + const configurationService = inject('configurationService', () => new ConfigurationService(), true); + + const orderProp = ref('prefix'); + const reverse = ref(false); + const allConfiguration: Ref = ref({}); + const configuration: Ref = ref([]); + const configKeys: Ref = ref([]); + const filtered = ref(''); + + const filteredConfiguration = computed(() => + orderAndFilterBy(configuration.value, { + filterByTerm: filtered.value, + orderByProp: orderProp.value, + reverse: reverse.value, + }), + ); + + return { + configurationService, + orderProp, + reverse, + allConfiguration, + configuration, + configKeys, + filtered, + filteredConfiguration, + t$: useI18n().t, + }; + }, + mounted() { + this.init(); + }, + methods: { + init(): void { + this.configurationService.loadConfiguration().then(res => { + this.configuration = res; + + for (const config of this.configuration) { + if (config.properties !== undefined) { + this.configKeys.push(Object.keys(config.properties)); + } + } + }); + + this.configurationService.loadEnvConfiguration().then(res => { + this.allConfiguration = res; + }); + }, + changeOrder(prop: string): void { + this.orderProp = prop; + this.reverse = !this.reverse; + }, + keys(dict: any): string[] { + return dict === undefined ? [] : Object.keys(dict); + }, + }, +}); diff --git a/src/main/webapp/app/admin/configuration/configuration.service.ts b/src/main/webapp/app/admin/configuration/configuration.service.ts new file mode 100644 index 0000000..14a3424 --- /dev/null +++ b/src/main/webapp/app/admin/configuration/configuration.service.ts @@ -0,0 +1,55 @@ +import axios from 'axios'; + +export default class ConfigurationService { + async loadConfiguration(): Promise { + const res = await axios.get('management/configprops'); + const properties = []; + const propertiesObject = this.getConfigPropertiesObjects(res.data); + for (const key in propertiesObject) { + if (Object.hasOwn(propertiesObject, key)) { + properties.push(propertiesObject[key]); + } + } + + properties.sort((propertyA, propertyB) => { + const comparePrefix = propertyA.prefix < propertyB.prefix ? -1 : 1; + return propertyA.prefix === propertyB.prefix ? 0 : comparePrefix; + }); + return properties; + } + + async loadEnvConfiguration(): Promise { + const res = await axios.get('management/env'); + const properties = {}; + const { propertySources } = res.data; + + for (const propertyObject of propertySources) { + const { name } = propertyObject; + const detailProperties = propertyObject.properties; + const vals = []; + for (const keyDetail in detailProperties) { + if (Object.hasOwn(detailProperties, keyDetail)) { + vals.push({ key: keyDetail, val: detailProperties[keyDetail].value }); + } + } + properties[name] = vals; + } + return properties; + } + + private getConfigPropertiesObjects(res): any { + // This code is for Spring Boot 2 + if (res.contexts !== undefined) { + for (const key in res.contexts) { + // If the key is not bootstrap, it will be the ApplicationContext Id + // For default app, it is baseName + // For microservice, it is baseName-1 + if (!key.startsWith('bootstrap')) { + return res.contexts[key].beans; + } + } + } + // by default, use the default ApplicationContext Id + return res.contexts.questionBank.beans; + } +} diff --git a/src/main/webapp/app/admin/configuration/configuration.vue b/src/main/webapp/app/admin/configuration/configuration.vue new file mode 100644 index 0000000..5bd4d2a --- /dev/null +++ b/src/main/webapp/app/admin/configuration/configuration.vue @@ -0,0 +1,62 @@ + + + diff --git a/src/main/webapp/app/admin/docs/docs.component.ts b/src/main/webapp/app/admin/docs/docs.component.ts new file mode 100644 index 0000000..d8c2d10 --- /dev/null +++ b/src/main/webapp/app/admin/docs/docs.component.ts @@ -0,0 +1,5 @@ +import { defineComponent } from 'vue'; + +export default defineComponent({ + name: 'JhiDocs', +}); diff --git a/src/main/webapp/app/admin/docs/docs.vue b/src/main/webapp/app/admin/docs/docs.vue new file mode 100644 index 0000000..d8fbc4d --- /dev/null +++ b/src/main/webapp/app/admin/docs/docs.vue @@ -0,0 +1,13 @@ + + + diff --git a/src/main/webapp/app/admin/health/health-modal.component.spec.ts b/src/main/webapp/app/admin/health/health-modal.component.spec.ts new file mode 100644 index 0000000..e32c724 --- /dev/null +++ b/src/main/webapp/app/admin/health/health-modal.component.spec.ts @@ -0,0 +1,90 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { shallowMount } from '@vue/test-utils'; + +import HealthModal from './health-modal.vue'; + +type HealthModalComponentType = InstanceType; + +const healthService = { getBaseName: vi.fn(), getSubSystemName: vi.fn() }; + +describe('Health Modal Component', () => { + let healthModal: HealthModalComponentType; + + beforeEach(() => { + const wrapper = shallowMount(HealthModal, { + propsData: { + currentHealth: {}, + }, + global: { + stubs: { + 'font-awesome-icon': true, + }, + provide: { + healthService, + }, + }, + }); + healthModal = wrapper.vm; + }); + + describe('baseName and subSystemName', () => { + it('should use healthService to get base name', () => { + healthModal.baseName('base'); + + expect(healthService.getBaseName).toHaveBeenCalled(); + }); + + it('should use healthService to get sub system name', () => { + healthModal.subSystemName('base'); + + expect(healthService.getSubSystemName).toHaveBeenCalled(); + }); + }); + + describe('readableValue should transform data', () => { + it('to string when is an object', () => { + const result = healthModal.readableValue({ data: 1000 }); + + expect(result).toBe('{"data":1000}'); + }); + + it('to string when is a string', () => { + const result = healthModal.readableValue('data'); + + expect(result).toBe('data'); + }); + }); +}); + +describe('Health Modal Component for diskSpace', () => { + let healthModal: HealthModalComponentType; + + beforeEach(() => { + const wrapper = shallowMount(HealthModal, { + propsData: { + currentHealth: { name: 'diskSpace' }, + }, + global: { + provide: { + healthService, + }, + }, + }); + healthModal = wrapper.vm; + }); + + describe('readableValue should transform data', () => { + it('to GB when needed', () => { + const result = healthModal.readableValue(2147483648); + + expect(result).toBe('2.00 GB'); + }); + + it('to MB when needed', () => { + const result = healthModal.readableValue(214748); + + expect(result).toBe('0.20 MB'); + }); + }); +}); diff --git a/src/main/webapp/app/admin/health/health-modal.component.ts b/src/main/webapp/app/admin/health/health-modal.component.ts new file mode 100644 index 0000000..1db1e64 --- /dev/null +++ b/src/main/webapp/app/admin/health/health-modal.component.ts @@ -0,0 +1,46 @@ +import { defineComponent, inject } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import HealthService from './health.service'; + +export default defineComponent({ + name: 'JhiHealthModal', + props: { + currentHealth: { + type: Object, + default: () => ({}), + }, + }, + setup() { + const healthService = inject('healthService', () => new HealthService(), true); + + return { + healthService, + t$: useI18n().t, + }; + }, + methods: { + baseName(name: string): any { + return this.healthService.getBaseName(name); + }, + subSystemName(name: string): any { + return this.healthService.getSubSystemName(name); + }, + readableValue(value: any): string { + if (this.currentHealth.name === 'diskSpace') { + // Should display storage space in a human readable unit + const val = value / 1073741824; + if (val > 1) { + // Value + return `${val.toFixed(2)} GB`; + } + return `${(value / 1048576).toFixed(2)} MB`; + } + + if (typeof value === 'object') { + return JSON.stringify(value); + } + return value.toString(); + }, + }, +}); diff --git a/src/main/webapp/app/admin/health/health-modal.vue b/src/main/webapp/app/admin/health/health-modal.vue new file mode 100644 index 0000000..333377f --- /dev/null +++ b/src/main/webapp/app/admin/health/health-modal.vue @@ -0,0 +1,29 @@ + + + diff --git a/src/main/webapp/app/admin/health/health.component.spec.ts b/src/main/webapp/app/admin/health/health.component.spec.ts new file mode 100644 index 0000000..9842c6c --- /dev/null +++ b/src/main/webapp/app/admin/health/health.component.spec.ts @@ -0,0 +1,93 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import HealthService from './health.service'; +import Health from './health.vue'; + +type HealthComponentType = InstanceType; + +const axiosStub = { + get: vi.spyOn(axios, 'get'), +}; + +describe('Health Component', () => { + let health: HealthComponentType; + + beforeEach(() => { + axiosStub.get.mockResolvedValue({}); + const wrapper = shallowMount(Health, { + global: { + stubs: { + bModal: true, + 'font-awesome-icon': true, + 'health-modal': true, + }, + directives: { + 'b-modal': {}, + }, + provide: { + healthService: new HealthService(), + }, + }, + }); + health = wrapper.vm; + }); + + describe('baseName and subSystemName', () => { + it('should return the basename when it has no sub system', () => { + expect(health.baseName('base')).toBe('base'); + }); + + it('should return the basename when it has sub systems', () => { + expect(health.baseName('base.subsystem.system')).toBe('base'); + }); + + it('should return the sub system name', () => { + expect(health.subSystemName('subsystem')).toBe(''); + }); + + it('should return the subsystem when it has multiple keys', () => { + expect(health.subSystemName('subsystem.subsystem.system')).toBe(' - subsystem.system'); + }); + }); + + describe('getBadgeClass', () => { + it('should get badge class', () => { + const upBadgeClass = health.getBadgeClass('UP'); + const downBadgeClass = health.getBadgeClass('DOWN'); + expect(upBadgeClass).toEqual('bg-success'); + expect(downBadgeClass).toEqual('bg-danger'); + }); + }); + + describe('refresh', () => { + it('should call refresh on init', async () => { + // GIVEN + axiosStub.get.mockResolvedValue({}); + + // WHEN + health.refresh(); + await health.$nextTick(); + + // THEN + expect(axiosStub.get).toHaveBeenCalledWith('management/health'); + await health.$nextTick(); + expect(health.updatingHealth).toEqual(false); + }); + it('should handle a 503 on refreshing health data', async () => { + // GIVEN + axiosStub.get.mockRejectedValue({}); + + // WHEN + health.refresh(); + await health.$nextTick(); + + // THEN + expect(axiosStub.get).toHaveBeenCalledWith('management/health'); + await health.$nextTick(); + expect(health.updatingHealth).toEqual(false); + }); + }); +}); diff --git a/src/main/webapp/app/admin/health/health.component.ts b/src/main/webapp/app/admin/health/health.component.ts new file mode 100644 index 0000000..1b0a08f --- /dev/null +++ b/src/main/webapp/app/admin/health/health.component.ts @@ -0,0 +1,63 @@ +import { type Ref, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import JhiHealthModal from './health-modal.vue'; +import HealthService from './health.service'; + +export default defineComponent({ + name: 'JhiHealth', + components: { + 'health-modal': JhiHealthModal, + }, + setup() { + const healthService = inject('healthService', () => new HealthService(), true); + + const healthData: Ref = ref(null); + const currentHealth: Ref = ref(null); + const updatingHealth = ref(false); + + return { + healthService, + healthData, + currentHealth, + updatingHealth, + t$: useI18n().t, + }; + }, + mounted(): void { + this.refresh(); + }, + methods: { + baseName(name: any): any { + return this.healthService.getBaseName(name); + }, + getBadgeClass(statusState: any): string { + if (statusState === 'UP') { + return 'bg-success'; + } + return 'bg-danger'; + }, + refresh(): void { + this.updatingHealth = true; + this.healthService + .checkHealth() + .then(res => { + this.healthData = this.healthService.transformHealthData(res.data); + this.updatingHealth = false; + }) + .catch(error => { + if (error.status === 503) { + this.healthData = this.healthService.transformHealthData(error.error); + } + this.updatingHealth = false; + }); + }, + showHealth(health: any): void { + this.currentHealth = health; + (this.$refs.healthModal as any).show(); + }, + subSystemName(name: string): string { + return this.healthService.getSubSystemName(name); + }, + }, +}); diff --git a/src/main/webapp/app/admin/health/health.service.spec.ts b/src/main/webapp/app/admin/health/health.service.spec.ts new file mode 100644 index 0000000..b5544fc --- /dev/null +++ b/src/main/webapp/app/admin/health/health.service.spec.ts @@ -0,0 +1,246 @@ +import { beforeEach, describe, expect, it } from 'vitest'; + +import HealthService from './health.service'; + +describe('Health Service', () => { + let healthService: HealthService; + + beforeEach(() => { + healthService = new HealthService(); + }); + + describe('transformHealthData', () => { + it('should flatten empty health data', () => { + const data = {}; + const expected = []; + expect(healthService.transformHealthData(data)).toEqual(expected); + }); + + it('should flatten health data with no subsystems', () => { + const data = { + components: { + status: 'UP', + db: { + status: 'UP', + database: 'H2', + hello: '1', + }, + mail: { + status: 'UP', + error: 'mail.a.b.c', + }, + }, + }; + const expected = [ + { + name: 'db', + status: 'UP', + details: { + database: 'H2', + hello: '1', + }, + }, + { + name: 'mail', + error: 'mail.a.b.c', + status: 'UP', + }, + ]; + expect(healthService.transformHealthData(data)).toEqual(expected); + }); + + it('should flatten health data with subsystems at level 1, main system has no additional information', () => { + const data = { + components: { + status: 'UP', + db: { + status: 'UP', + database: 'H2', + hello: '1', + }, + mail: { + status: 'UP', + error: 'mail.a.b.c', + }, + system: { + status: 'DOWN', + subsystem1: { + status: 'UP', + property1: 'system.subsystem1.property1', + }, + subsystem2: { + status: 'DOWN', + error: 'system.subsystem1.error', + property2: 'system.subsystem2.property2', + }, + }, + }, + }; + const expected = [ + { + name: 'db', + status: 'UP', + details: { + database: 'H2', + hello: '1', + }, + }, + { + name: 'mail', + error: 'mail.a.b.c', + status: 'UP', + }, + { + name: 'system.subsystem1', + status: 'UP', + details: { + property1: 'system.subsystem1.property1', + }, + }, + { + name: 'system.subsystem2', + error: 'system.subsystem1.error', + status: 'DOWN', + details: { + property2: 'system.subsystem2.property2', + }, + }, + ]; + expect(healthService.transformHealthData(data)).toEqual(expected); + }); + + it('should flatten health data with subsystems at level 1, main system has additional information', () => { + const data = { + components: { + status: 'UP', + db: { + status: 'UP', + database: 'H2', + hello: '1', + }, + mail: { + status: 'UP', + error: 'mail.a.b.c', + }, + system: { + status: 'DOWN', + property1: 'system.property1', + subsystem1: { + status: 'UP', + property1: 'system.subsystem1.property1', + }, + subsystem2: { + status: 'DOWN', + error: 'system.subsystem1.error', + property2: 'system.subsystem2.property2', + }, + }, + }, + }; + const expected = [ + { + name: 'db', + status: 'UP', + details: { + database: 'H2', + hello: '1', + }, + }, + { + name: 'mail', + error: 'mail.a.b.c', + status: 'UP', + }, + { + name: 'system', + status: 'DOWN', + details: { + property1: 'system.property1', + }, + }, + { + name: 'system.subsystem1', + status: 'UP', + details: { + property1: 'system.subsystem1.property1', + }, + }, + { + name: 'system.subsystem2', + error: 'system.subsystem1.error', + status: 'DOWN', + details: { + property2: 'system.subsystem2.property2', + }, + }, + ]; + expect(healthService.transformHealthData(data)).toEqual(expected); + }); + + it('should flatten health data with subsystems at level 1, main system has additional error', () => { + const data = { + components: { + status: 'UP', + db: { + status: 'UP', + database: 'H2', + hello: '1', + }, + mail: { + status: 'UP', + error: 'mail.a.b.c', + }, + system: { + status: 'DOWN', + error: 'show me', + subsystem1: { + status: 'UP', + property1: 'system.subsystem1.property1', + }, + subsystem2: { + status: 'DOWN', + error: 'system.subsystem1.error', + property2: 'system.subsystem2.property2', + }, + }, + }, + }; + const expected = [ + { + name: 'db', + status: 'UP', + details: { + database: 'H2', + hello: '1', + }, + }, + { + name: 'mail', + error: 'mail.a.b.c', + status: 'UP', + }, + { + name: 'system', + error: 'show me', + status: 'DOWN', + }, + { + name: 'system.subsystem1', + status: 'UP', + details: { + property1: 'system.subsystem1.property1', + }, + }, + { + name: 'system.subsystem2', + error: 'system.subsystem1.error', + status: 'DOWN', + details: { + property2: 'system.subsystem2.property2', + }, + }, + ]; + expect(healthService.transformHealthData(data)).toEqual(expected); + }); + }); +}); diff --git a/src/main/webapp/app/admin/health/health.service.ts b/src/main/webapp/app/admin/health/health.service.ts new file mode 100644 index 0000000..9781578 --- /dev/null +++ b/src/main/webapp/app/admin/health/health.service.ts @@ -0,0 +1,118 @@ +import axios, { type AxiosPromise } from 'axios'; + +export default class HealthService { + separator = '.'; + + checkHealth(): AxiosPromise { + return axios.get('management/health'); + } + + transformHealthData(data: any): any { + const response = []; + this.flattenHealthData(response, null, data.components); + return response; + } + + getBaseName(name: string): string { + if (name) { + const split = name.split('.'); + return split[0]; + } + } + + getSubSystemName(name: string): string { + if (name) { + const split = name.split('.'); + split.splice(0, 1); + const remainder = split.join('.'); + return remainder ? ` - ${remainder}` : ''; + } + } + + addHealthObject(result: any, isLeaf: boolean, healthObject: any, name: string) { + const healthData = { + name, + details: undefined, + error: undefined, + }; + + const details = {}; + let hasDetails = false; + + for (const key in healthObject) { + if (Object.hasOwn(healthObject, key)) { + const value = healthObject[key]; + if (key === 'status' || key === 'error') { + healthData[key] = value; + } else if (!this.isHealthObject(value)) { + details[key] = value; + hasDetails = true; + } + } + } + + // Add the details + if (hasDetails) { + healthData.details = details; + } + + // Only add nodes if they provide additional information + if (isLeaf || hasDetails || healthData.error) { + result.push(healthData); + } + return healthData; + } + + flattenHealthData(result: any, path: any, data: any): any { + for (const key in data) { + if (Object.hasOwn(data, key)) { + const value = data[key]; + if (this.isHealthObject(value)) { + if (this.hasSubSystem(value)) { + this.addHealthObject(result, false, value, this.getModuleName(path, key)); + this.flattenHealthData(result, this.getModuleName(path, key), value); + } else { + this.addHealthObject(result, true, value, this.getModuleName(path, key)); + } + } + } + } + return result; + } + + getModuleName(path: any, name: string) { + if (path && name) { + return path + this.separator + name; + } else if (path) { + return path; + } else if (name) { + return name; + } + return ''; + } + + hasSubSystem(healthObject: any): any { + let result = false; + + for (const key in healthObject) { + if (Object.hasOwn(healthObject, key)) { + const value = healthObject[key]; + if (value?.status) { + result = true; + } + } + } + return result; + } + + isHealthObject(healthObject: any): any { + let result = false; + + for (const key in healthObject) { + if (Object.hasOwn(healthObject, key) && key === 'status') { + result = true; + } + } + return result; + } +} diff --git a/src/main/webapp/app/admin/health/health.vue b/src/main/webapp/app/admin/health/health.vue new file mode 100644 index 0000000..7e525a7 --- /dev/null +++ b/src/main/webapp/app/admin/health/health.vue @@ -0,0 +1,45 @@ + + + diff --git a/src/main/webapp/app/admin/logs/logs.component.spec.ts b/src/main/webapp/app/admin/logs/logs.component.spec.ts new file mode 100644 index 0000000..ebcc54b --- /dev/null +++ b/src/main/webapp/app/admin/logs/logs.component.spec.ts @@ -0,0 +1,73 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import Logs from './logs.vue'; + +type LogsComponentType = InstanceType; + +const axiosStub = { + get: vi.spyOn(axios, 'get'), + post: vi.spyOn(axios, 'post'), +}; + +describe('Logs Component', () => { + let logs: LogsComponentType; + + beforeEach(() => { + axiosStub.get.mockResolvedValue({}); + const wrapper = shallowMount(Logs, { + global: { + stubs: { + 'jhi-sort-indicator': true, + BButton: true, + BButtonGroup: true, + }, + }, + }); + logs = wrapper.vm; + }); + + describe('OnInit', () => { + it('should set all default values correctly', () => { + expect(logs.filtered).toBe(''); + expect(logs.orderProp).toBe('name'); + expect(logs.reverse).toBe(false); + }); + + it('Should call load all on init', async () => { + // WHEN + logs.init(); + await logs.$nextTick(); + + // THEN + expect(axiosStub.get).toHaveBeenCalledWith('management/loggers'); + }); + }); + + describe('change log level', () => { + it('should change log level correctly', async () => { + axiosStub.post.mockResolvedValue({}); + + // WHEN + logs.updateLevel('main', 'ERROR'); + await logs.$nextTick(); + + // THEN + expect(axiosStub.post).toHaveBeenCalledWith('management/loggers/main', { configuredLevel: 'ERROR' }); + expect(axiosStub.get).toHaveBeenCalledWith('management/loggers'); + }); + }); + + describe('change order', () => { + it('should change order and invert reverse', () => { + // WHEN + logs.changeOrder('dummy-order'); + + // THEN + expect(logs.orderProp).toEqual('dummy-order'); + expect(logs.reverse).toBe(true); + }); + }); +}); diff --git a/src/main/webapp/app/admin/logs/logs.component.ts b/src/main/webapp/app/admin/logs/logs.component.ts new file mode 100644 index 0000000..aed5cd5 --- /dev/null +++ b/src/main/webapp/app/admin/logs/logs.component.ts @@ -0,0 +1,63 @@ +import { type Ref, computed, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { orderAndFilterBy } from '@/shared/computables'; + +import LogsService from './logs.service'; + +export default defineComponent({ + name: 'JhiLogs', + setup() { + const logsService = inject('logsService', () => new LogsService(), true); + + const loggers: Ref = ref([]); + const filtered = ref(''); + const orderProp = ref('name'); + const reverse = ref(false); + const filteredLoggers = computed(() => + orderAndFilterBy(loggers.value, { + filterByTerm: filtered.value, + orderByProp: orderProp.value, + reverse: reverse.value, + }), + ); + + return { + logsService, + loggers, + filtered, + orderProp, + reverse, + filteredLoggers, + t$: useI18n().t, + }; + }, + mounted() { + this.init(); + }, + methods: { + init(): void { + this.logsService.findAll().then(response => { + this.extractLoggers(response); + }); + }, + updateLevel(name: string, level: string): void { + this.logsService.changeLevel(name, level).then(() => { + this.init(); + }); + }, + changeOrder(orderProp: string): void { + this.orderProp = orderProp; + this.reverse = !this.reverse; + }, + extractLoggers(response) { + this.loggers = []; + if (response.data) { + for (const key of Object.keys(response.data.loggers)) { + const logger = response.data.loggers[key]; + this.loggers.push({ name: key, level: logger.effectiveLevel }); + } + } + }, + }, +}); diff --git a/src/main/webapp/app/admin/logs/logs.service.ts b/src/main/webapp/app/admin/logs/logs.service.ts new file mode 100644 index 0000000..5f2568f --- /dev/null +++ b/src/main/webapp/app/admin/logs/logs.service.ts @@ -0,0 +1,11 @@ +import axios, { type AxiosPromise } from 'axios'; + +export default class LogsService { + changeLevel(name: string, configuredLevel: string): AxiosPromise { + return axios.post(`management/loggers/${name}`, { configuredLevel }); + } + + findAll(): AxiosPromise { + return axios.get('management/loggers'); + } +} diff --git a/src/main/webapp/app/admin/logs/logs.vue b/src/main/webapp/app/admin/logs/logs.vue new file mode 100644 index 0000000..0121be2 --- /dev/null +++ b/src/main/webapp/app/admin/logs/logs.vue @@ -0,0 +1,57 @@ + + + diff --git a/src/main/webapp/app/admin/metrics/metrics-modal.component.spec.ts b/src/main/webapp/app/admin/metrics/metrics-modal.component.spec.ts new file mode 100644 index 0000000..1eab453 --- /dev/null +++ b/src/main/webapp/app/admin/metrics/metrics-modal.component.spec.ts @@ -0,0 +1,59 @@ +import { beforeEach, describe, expect, it } from 'vitest'; + +import { shallowMount } from '@vue/test-utils'; + +import MetricsModal from './metrics-modal.vue'; + +type MetricsModalComponentType = InstanceType; + +describe('MetricsModal', () => { + let metricsModal: MetricsModalComponentType; + + beforeEach(() => { + const wrapper = shallowMount(MetricsModal, { + propsData: { + threadDump: [ + { name: 'test1', threadState: 'RUNNABLE' }, + { name: 'test2', threadState: 'WAITING' }, + { name: 'test3', threadState: 'TIMED_WAITING' }, + { name: 'test4', threadState: 'BLOCKED' }, + { name: 'test5', threadState: 'BLOCKED' }, + { name: 'test5', threadState: 'NONE' }, + ], + }, + }); + metricsModal = wrapper.vm; + }); + + describe('init', () => { + it('should count the numbers of each thread type', () => { + expect(metricsModal.threadDumpData.threadDumpRunnable).toBe(1); + expect(metricsModal.threadDumpData.threadDumpWaiting).toBe(1); + expect(metricsModal.threadDumpData.threadDumpTimedWaiting).toBe(1); + expect(metricsModal.threadDumpData.threadDumpBlocked).toBe(2); + expect(metricsModal.threadDumpData.threadDumpAll).toBe(5); + }); + }); + + describe('getBadgeClass', () => { + it('should return bg-success for RUNNABLE', () => { + expect(metricsModal.getBadgeClass('RUNNABLE')).toBe('bg-success'); + }); + + it('should return bg-info for WAITING', () => { + expect(metricsModal.getBadgeClass('WAITING')).toBe('bg-info'); + }); + + it('should return bg-warning for TIMED_WAITING', () => { + expect(metricsModal.getBadgeClass('TIMED_WAITING')).toBe('bg-warning'); + }); + + it('should return bg-danger for BLOCKED', () => { + expect(metricsModal.getBadgeClass('BLOCKED')).toBe('bg-danger'); + }); + + it('should return an empty string for anything else', () => { + expect(metricsModal.getBadgeClass('')).toBe(''); + }); + }); +}); diff --git a/src/main/webapp/app/admin/metrics/metrics-modal.component.ts b/src/main/webapp/app/admin/metrics/metrics-modal.component.ts new file mode 100644 index 0000000..4f50a3d --- /dev/null +++ b/src/main/webapp/app/admin/metrics/metrics-modal.component.ts @@ -0,0 +1,64 @@ +import { type PropType, type Ref, computed, defineComponent, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { filterBy } from '@/shared/computables'; + +export default defineComponent({ + name: 'JhiMetricsModal', + props: { + threadDump: { + type: Array as PropType, + default: () => [], + }, + }, + setup(props) { + const threadDumpFilter: Ref = ref(''); + const filteredThreadDump = computed(() => filterBy(props.threadDump, { filterByTerm: threadDumpFilter.value })); + + const threadDumpData = computed(() => { + const data = { + threadDumpAll: 0, + threadDumpBlocked: 0, + threadDumpRunnable: 0, + threadDumpTimedWaiting: 0, + threadDumpWaiting: 0, + }; + if (props.threadDump) { + props.threadDump.forEach(value => { + if (value.threadState === 'RUNNABLE') { + data.threadDumpRunnable += 1; + } else if (value.threadState === 'WAITING') { + data.threadDumpWaiting += 1; + } else if (value.threadState === 'TIMED_WAITING') { + data.threadDumpTimedWaiting += 1; + } else if (value.threadState === 'BLOCKED') { + data.threadDumpBlocked += 1; + } + }); + data.threadDumpAll = data.threadDumpRunnable + data.threadDumpWaiting + data.threadDumpTimedWaiting + data.threadDumpBlocked; + } + return data; + }); + + return { + threadDumpFilter, + threadDumpData, + filteredThreadDump, + t$: useI18n().t, + }; + }, + methods: { + getBadgeClass(threadState: string): string { + if (threadState === 'RUNNABLE') { + return 'bg-success'; + } else if (threadState === 'WAITING') { + return 'bg-info'; + } else if (threadState === 'TIMED_WAITING') { + return 'bg-warning'; + } else if (threadState === 'BLOCKED') { + return 'bg-danger'; + } + return ''; + }, + }, +}); diff --git a/src/main/webapp/app/admin/metrics/metrics-modal.vue b/src/main/webapp/app/admin/metrics/metrics-modal.vue new file mode 100644 index 0000000..bc7bc36 --- /dev/null +++ b/src/main/webapp/app/admin/metrics/metrics-modal.vue @@ -0,0 +1,75 @@ + + + diff --git a/src/main/webapp/app/admin/metrics/metrics.component.spec.ts b/src/main/webapp/app/admin/metrics/metrics.component.spec.ts new file mode 100644 index 0000000..70f2bcb --- /dev/null +++ b/src/main/webapp/app/admin/metrics/metrics.component.spec.ts @@ -0,0 +1,272 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import MetricsService from './metrics.service'; +import Metrics from './metrics.vue'; + +type MetricsComponentType = InstanceType; + +const axiosStub = { + get: vi.spyOn(axios, 'get'), +}; + +describe('Metrics Component', () => { + let metricsComponent: MetricsComponentType; + const response = { + jvm: { + 'PS Eden Space': { + committed: 5.57842432e8, + max: 6.49592832e8, + used: 4.20828184e8, + }, + 'Code Cache': { + committed: 2.3461888e7, + max: 2.5165824e8, + used: 2.2594368e7, + }, + 'Compressed Class Space': { + committed: 1.2320768e7, + max: 1.073741824e9, + used: 1.1514008e7, + }, + 'PS Survivor Space': { + committed: 1.5204352e7, + max: 1.5204352e7, + used: 1.2244376e7, + }, + 'PS Old Gen': { + committed: 1.10624768e8, + max: 1.37887744e9, + used: 4.1390776e7, + }, + Metaspace: { + committed: 9.170944e7, + max: -1.0, + used: 8.7377552e7, + }, + }, + databases: { + min: { + value: 10.0, + }, + max: { + value: 10.0, + }, + idle: { + value: 10.0, + }, + usage: { + '0.0': 0.0, + '1.0': 0.0, + max: 0.0, + totalTime: 4210.0, + mean: 701.6666666666666, + '0.5': 0.0, + count: 6, + '0.99': 0.0, + '0.75': 0.0, + '0.95': 0.0, + }, + pending: { + value: 0.0, + }, + active: { + value: 0.0, + }, + acquire: { + '0.0': 0.0, + '1.0': 0.0, + max: 0.0, + totalTime: 0.884426, + mean: 0.14740433333333333, + '0.5': 0.0, + count: 6, + '0.99': 0.0, + '0.75': 0.0, + '0.95': 0.0, + }, + creation: { + '0.0': 0.0, + '1.0': 0.0, + max: 0.0, + totalTime: 27.0, + mean: 3.0, + '0.5': 0.0, + count: 9, + '0.99': 0.0, + '0.75': 0.0, + '0.95': 0.0, + }, + connections: { + value: 10.0, + }, + }, + 'http.server.requests': { + all: { + count: 5, + }, + percode: { + '200': { + max: 0.0, + mean: 298.9012628, + count: 5, + }, + }, + }, + cache: { + usersByEmail: { + 'cache.gets.miss': 0.0, + 'cache.puts': 0.0, + 'cache.gets.hit': 0.0, + 'cache.removals': 0.0, + 'cache.evictions': 0.0, + }, + usersByLogin: { + 'cache.gets.miss': 1.0, + 'cache.puts': 1.0, + 'cache.gets.hit': 1.0, + 'cache.removals': 0.0, + 'cache.evictions': 0.0, + }, + 'tech.jhipster.domain.Authority': { + 'cache.gets.miss': 0.0, + 'cache.puts': 2.0, + 'cache.gets.hit': 0.0, + 'cache.removals': 0.0, + 'cache.evictions': 0.0, + }, + 'tech.jhipster.domain.User.authorities': { + 'cache.gets.miss': 0.0, + 'cache.puts': 1.0, + 'cache.gets.hit': 0.0, + 'cache.removals': 0.0, + 'cache.evictions': 0.0, + }, + 'tech.jhipster.domain.User': { + 'cache.gets.miss': 0.0, + 'cache.puts': 1.0, + 'cache.gets.hit': 0.0, + 'cache.removals': 0.0, + 'cache.evictions': 0.0, + }, + }, + garbageCollector: { + 'jvm.gc.max.data.size': 1.37887744e9, + 'jvm.gc.pause': { + '0.0': 0.0, + '1.0': 0.0, + max: 0.0, + totalTime: 242.0, + mean: 242.0, + '0.5': 0.0, + count: 1, + '0.99': 0.0, + '0.75': 0.0, + '0.95': 0.0, + }, + 'jvm.gc.memory.promoted': 2.992732e7, + 'jvm.gc.memory.allocated': 1.26362872e9, + classesLoaded: 17393.0, + 'jvm.gc.live.data.size': 3.1554408e7, + classesUnloaded: 0.0, + }, + services: { + '/management/info': { + GET: { + max: 0.0, + mean: 104.952893, + count: 1, + }, + }, + '/api/authenticate': { + POST: { + max: 0.0, + mean: 909.53003, + count: 1, + }, + }, + '/api/account': { + GET: { + max: 0.0, + mean: 141.209628, + count: 1, + }, + }, + '/**': { + GET: { + max: 0.0, + mean: 169.4068815, + count: 2, + }, + }, + }, + processMetrics: { + 'system.load.average.1m': 3.63, + 'system.cpu.usage': 0.5724934148485453, + 'system.cpu.count': 4.0, + 'process.start.time': 1.548140811306e12, + 'process.files.open': 205.0, + 'process.cpu.usage': 0.003456347568026252, + 'process.uptime': 88404.0, + 'process.files.max': 1048576.0, + }, + threads: [{ name: 'test1', threadState: 'RUNNABLE' }], + }; + + beforeEach(() => { + axiosStub.get.mockResolvedValue({ data: { timers: [], gauges: [] } }); + const wrapper = shallowMount(Metrics, { + global: { + stubs: { + bModal: true, + bProgress: true, + bProgressBar: true, + 'font-awesome-icon': true, + 'metrics-modal': true, + }, + directives: { + 'b-modal': {}, + 'b-progress': {}, + 'b-progress-bar': {}, + }, + provide: { + metricsService: new MetricsService(), + }, + }, + }); + metricsComponent = wrapper.vm; + }); + + describe('refresh', () => { + it('should call refresh on init', async () => { + // GIVEN + axiosStub.get.mockResolvedValue({ data: response }); + + // WHEN + await metricsComponent.refresh(); + await metricsComponent.$nextTick(); + + // THEN + expect(axiosStub.get).toHaveBeenCalledWith('management/jhimetrics'); + expect(axiosStub.get).toHaveBeenCalledWith('management/threaddump'); + expect(metricsComponent.metrics).toHaveProperty('jvm'); + expect(metricsComponent.metrics).toEqual(response); + expect(metricsComponent.threadStats).toEqual({ + threadDumpRunnable: 1, + threadDumpWaiting: 0, + threadDumpTimedWaiting: 0, + threadDumpBlocked: 0, + threadDumpAll: 1, + }); + }); + }); + + describe('isNan', () => { + it('should return if a variable is NaN', () => { + expect(metricsComponent.filterNaN(1)).toBe(1); + expect(metricsComponent.filterNaN('test')).toBe(0); + }); + }); +}); diff --git a/src/main/webapp/app/admin/metrics/metrics.component.ts b/src/main/webapp/app/admin/metrics/metrics.component.ts new file mode 100644 index 0000000..af94cd4 --- /dev/null +++ b/src/main/webapp/app/admin/metrics/metrics.component.ts @@ -0,0 +1,131 @@ +import { type Ref, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { useDateFormat } from '@/shared/composables'; + +import JhiMetricsModal from './metrics-modal.vue'; +import MetricsService from './metrics.service'; + +export default defineComponent({ + name: 'JhiMetrics', + components: { + 'metrics-modal': JhiMetricsModal, + }, + setup() { + const { formatDate } = useDateFormat(); + const metricsService = inject('metricsService', () => new MetricsService(), true); + + const metrics: Ref = ref({}); + const threadData: Ref = ref(null); + const threadStats: Ref = ref({}); + const updatingMetrics = ref(true); + + return { + metricsService, + metrics, + threadData, + threadStats, + updatingMetrics, + formatDate, + t$: useI18n().t, + }; + }, + mounted(): void { + this.refresh(); + }, + methods: { + refresh() { + return this.metricsService + .getMetrics() + .then(resultsMetrics => { + this.metrics = resultsMetrics.data; + this.metricsService + .retrieveThreadDump() + .then(res => { + this.updatingMetrics = true; + this.threadData = res.data.threads; + + this.threadStats = { + threadDumpRunnable: 0, + threadDumpWaiting: 0, + threadDumpTimedWaiting: 0, + threadDumpBlocked: 0, + threadDumpAll: 0, + }; + + this.threadData.forEach(value => { + if (value.threadState === 'RUNNABLE') { + this.threadStats.threadDumpRunnable += 1; + } else if (value.threadState === 'WAITING') { + this.threadStats.threadDumpWaiting += 1; + } else if (value.threadState === 'TIMED_WAITING') { + this.threadStats.threadDumpTimedWaiting += 1; + } else if (value.threadState === 'BLOCKED') { + this.threadStats.threadDumpBlocked += 1; + } + }); + + this.threadStats.threadDumpAll = + this.threadStats.threadDumpRunnable + + this.threadStats.threadDumpWaiting + + this.threadStats.threadDumpTimedWaiting + + this.threadStats.threadDumpBlocked; + + this.updatingMetrics = false; + }) + .catch(() => { + this.updatingMetrics = true; + }); + }) + .catch(() => { + this.updatingMetrics = true; + }); + }, + openModal(): void { + if ((this.$refs.metricsModal as any).show) { + (this.$refs.metricsModal as any).show(); + } + }, + filterNaN(input: any): any { + if (isNaN(input)) { + return 0; + } + return input; + }, + formatNumber1(value: any): any { + return new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 }).format(value); + }, + formatNumber2(value: any): any { + return new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(value); + }, + convertMillisecondsToDuration(ms) { + const times = { + year: 31557600000, + month: 2629746000, + day: 86400000, + hour: 3600000, + minute: 60000, + second: 1000, + }; + let time_string = ''; + const plural = ''; + for (const key in times) { + if (Math.floor(ms / times[key]) > 0) { + let plural = ''; + if (Math.floor(ms / times[key]) > 1) { + plural = 's'; + } + time_string += `${Math.floor(ms / times[key])} ${key}${plural} `; + ms = ms - times[key] * Math.floor(ms / times[key]); + } + } + return time_string; + }, + isObjectExisting(metrics: any, key: string): boolean { + return metrics?.[key]; + }, + isObjectExistingAndNotEmpty(metrics: any, key: string): boolean { + return this.isObjectExisting(metrics, key) && JSON.stringify(metrics[key]) !== '{}'; + }, + }, +}); diff --git a/src/main/webapp/app/admin/metrics/metrics.service.ts b/src/main/webapp/app/admin/metrics/metrics.service.ts new file mode 100644 index 0000000..c1d3d5b --- /dev/null +++ b/src/main/webapp/app/admin/metrics/metrics.service.ts @@ -0,0 +1,11 @@ +import axios, { type AxiosPromise } from 'axios'; + +export default class MetricsService { + getMetrics(): AxiosPromise { + return axios.get('management/jhimetrics'); + } + + retrieveThreadDump(): AxiosPromise { + return axios.get('management/threaddump'); + } +} diff --git a/src/main/webapp/app/admin/metrics/metrics.vue b/src/main/webapp/app/admin/metrics/metrics.vue new file mode 100644 index 0000000..889055c --- /dev/null +++ b/src/main/webapp/app/admin/metrics/metrics.vue @@ -0,0 +1,371 @@ + + + diff --git a/src/main/webapp/app/admin/user-management/user-management-edit.component.spec.ts b/src/main/webapp/app/admin/user-management/user-management-edit.component.spec.ts new file mode 100644 index 0000000..11cc5ed --- /dev/null +++ b/src/main/webapp/app/admin/user-management/user-management-edit.component.spec.ts @@ -0,0 +1,161 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { type RouteLocation } from 'vue-router'; + +import { type MountingOptions, shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import AlertService from '@/shared/alert/alert.service'; +import { MESSAGE_ALERT_HEADER_NAME, MESSAGE_PARAM_HEADER_NAME } from '@/shared/jhipster/constants'; + +import UserManagementEdit from './user-management-edit.vue'; + +type UserManagementEditComponentType = InstanceType; + +let route: Partial; +const routerGoMock = vi.fn(); + +vi.mock('vue-router', () => ({ + useRoute: () => route, + useRouter: () => ({ go: routerGoMock }), +})); + +describe('UserManagementEdit Component', () => { + const axiosStub = { + get: vi.spyOn(axios, 'get'), + post: vi.spyOn(axios, 'post'), + put: vi.spyOn(axios, 'put'), + }; + let mountOptions: MountingOptions['global']; + let alertService: AlertService; + + beforeEach(() => { + route = {}; + alertService = new AlertService({ + i18n: { t: vi.fn() } as any, + toast: { + create: vi.fn(), + } as any, + }); + + mountOptions = { + stubs: { + 'font-awesome-icon': true, + }, + provide: { + alertService, + }, + }; + + axiosStub.get.mockReset(); + axiosStub.post.mockReset(); + axiosStub.put.mockReset(); + }); + + describe('init', () => { + it('Should load user', async () => { + // GIVEN + axiosStub.get.mockImplementation((url?: string) => { + if (url === `api/admin/users/${123}`) return Promise.resolve({}); + if (url === 'api/authorities') return Promise.resolve({ data: [] }); + return Promise.resolve({}); + }); + route = { + params: { + userId: `${123}`, + }, + }; + const wrapper = shallowMount(UserManagementEdit, { global: mountOptions }); + const userManagementEdit: UserManagementEditComponentType = wrapper.vm; + + // WHEN + await userManagementEdit.$nextTick(); + + // THEN + expect(axiosStub.get).toHaveBeenCalledWith('api/authorities'); + expect(axiosStub.get).toHaveBeenCalledWith(`api/admin/users/${123}`); + }); + it('Should open create user', async () => { + // GIVEN + axiosStub.get.mockImplementation((url?: string) => { + if (url === 'api/authorities') return Promise.resolve({ data: [] }); + return Promise.resolve({}); + }); + route = { + params: {}, + }; + const wrapper = shallowMount(UserManagementEdit, { global: mountOptions }); + const userManagementEdit: UserManagementEditComponentType = wrapper.vm; + + // WHEN + await userManagementEdit.$nextTick(); + + // THEN + expect(axiosStub.get).toHaveBeenCalledWith('api/authorities'); + expect(axiosStub.get).toHaveBeenCalledTimes(1); + }); + }); + + describe('save', () => { + it('Should call update service on save for existing user', async () => { + // GIVEN + axiosStub.put.mockResolvedValue({ + headers: { + [MESSAGE_ALERT_HEADER_NAME]: '', + [MESSAGE_PARAM_HEADER_NAME]: '', + }, + }); + axiosStub.get.mockImplementation((url?: string) => { + if (url === `api/admin/users/${123}`) return Promise.resolve({ data: { id: 123, authorities: [] } }); + if (url === 'api/authorities') return Promise.resolve({ data: [] }); + return Promise.resolve({}); + }); + route = { + params: { + userId: `${123}`, + }, + }; + const wrapper = shallowMount(UserManagementEdit, { global: mountOptions }); + const userManagementEdit: UserManagementEditComponentType = wrapper.vm; + await userManagementEdit.$nextTick(); + + // WHEN + userManagementEdit.save(); + await userManagementEdit.$nextTick(); + + // THEN + expect(axiosStub.put).toHaveBeenCalledWith('api/admin/users', { id: 123, authorities: [] }); + expect(userManagementEdit.isSaving).toEqual(false); + }); + + it('Should call create service on save for new user', async () => { + // GIVEN + axiosStub.post.mockResolvedValue({ + headers: { + [MESSAGE_ALERT_HEADER_NAME]: '', + [MESSAGE_PARAM_HEADER_NAME]: '', + }, + }); + axiosStub.get.mockImplementation((url?: string) => { + if (url === 'api/authorities') return Promise.resolve({ data: [] }); + return Promise.resolve({}); + }); + route = { + params: {}, + }; + const wrapper = shallowMount(UserManagementEdit, { global: mountOptions }); + const userManagementEdit: UserManagementEditComponentType = wrapper.vm; + await userManagementEdit.$nextTick(); + userManagementEdit.userAccount = { authorities: [] }; + + // WHEN + userManagementEdit.save(); + await userManagementEdit.$nextTick(); + + // THEN + expect(axiosStub.post).toHaveBeenCalledWith('api/admin/users', { + authorities: [], + }); + expect(userManagementEdit.isSaving).toEqual(false); + }); + }); +}); diff --git a/src/main/webapp/app/admin/user-management/user-management-edit.component.ts b/src/main/webapp/app/admin/user-management/user-management-edit.component.ts new file mode 100644 index 0000000..0eda160 --- /dev/null +++ b/src/main/webapp/app/admin/user-management/user-management-edit.component.ts @@ -0,0 +1,125 @@ +import { type Ref, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; +import { useRoute, useRouter } from 'vue-router'; + +import { useVuelidate } from '@vuelidate/core'; +import { email, maxLength, minLength, required } from '@vuelidate/validators'; + +import { useAlertService } from '@/shared/alert/alert.service'; +import languages from '@/shared/config/languages'; +import { getMessageFromHeaders } from '@/shared/jhipster/headers'; +import { type IUser, User } from '@/shared/model/user.model'; + +import UserManagementService from './user-management.service'; + +const loginValidator = (value: string) => { + if (!value) { + return true; + } + return /^[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$|^[_.@A-Za-z0-9-]+$/.test(value); +}; + +const validations: any = { + userAccount: { + login: { + required, + maxLength: maxLength(254), + pattern: loginValidator, + }, + firstName: { + maxLength: maxLength(50), + }, + lastName: { + maxLength: maxLength(50), + }, + email: { + required, + email, + minLength: minLength(5), + maxLength: maxLength(50), + }, + }, +}; + +export default defineComponent({ + name: 'JhiUserManagementEdit', + validations, + setup() { + const route = useRoute(); + const router = useRouter(); + + const alertService = inject('alertService', () => useAlertService(), true); + const userManagementService = inject('userManagementService', () => new UserManagementService(), true); + const previousState = () => router.go(-1); + + const userAccount: Ref = ref({ ...new User(), activated: true, authorities: [] }); + const isSaving: Ref = ref(false); + const authorities: Ref = ref([]); + + const initAuthorities = async () => { + const response = await userManagementService.retrieveAuthorities(); + authorities.value = response.data; + }; + + const loadUser = async (userId: string) => { + const response = await userManagementService.get(userId); + userAccount.value = response.data; + }; + + initAuthorities(); + const userId = route.params?.userId; + if (userId) { + loadUser(userId); + } + + return { + alertService, + userAccount, + isSaving, + authorities, + userManagementService, + previousState, + v$: useVuelidate(), + languages: languages(), + t$: useI18n().t, + }; + }, + methods: { + save(): void { + this.isSaving = true; + if (this.userAccount.id) { + this.userManagementService + .update(this.userAccount) + .then(res => { + this.returnToList(); + this.alertService.showInfo(this.getToastMessageFromHeader(res)); + }) + .catch(error => { + this.isSaving = true; + this.alertService.showHttpError(error.response); + }); + } else { + this.userManagementService + .create(this.userAccount) + .then(res => { + this.returnToList(); + this.alertService.showSuccess(this.getToastMessageFromHeader(res)); + }) + .catch(error => { + this.isSaving = true; + this.alertService.showHttpError(error.response); + }); + } + }, + + returnToList(): void { + this.isSaving = false; + this.previousState(); + }, + + getToastMessageFromHeader(res: any): string { + const message = getMessageFromHeaders(res.headers); + return message.alertKey ? this.t$(message.alertKey, { param: message.param }) : message.alertMessage; + }, + }, +}); diff --git a/src/main/webapp/app/admin/user-management/user-management-edit.vue b/src/main/webapp/app/admin/user-management/user-management-edit.vue new file mode 100644 index 0000000..e425a82 --- /dev/null +++ b/src/main/webapp/app/admin/user-management/user-management-edit.vue @@ -0,0 +1,143 @@ + + + diff --git a/src/main/webapp/app/admin/user-management/user-management-view.component.spec.ts b/src/main/webapp/app/admin/user-management/user-management-view.component.spec.ts new file mode 100644 index 0000000..ed59f42 --- /dev/null +++ b/src/main/webapp/app/admin/user-management/user-management-view.component.spec.ts @@ -0,0 +1,83 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { type RouteLocation } from 'vue-router'; + +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import AlertService from '@/shared/alert/alert.service'; +import { Authority } from '@/shared/jhipster/constants'; + +import UserManagementView from './user-management-view.vue'; + +let route: Partial; + +vi.mock('vue-router', () => ({ + useRoute: () => route, +})); + +const axiosStub = { + get: vi.spyOn(axios, 'get'), +}; + +describe('UserManagementView Component', () => { + let alertService: AlertService; + + beforeEach(() => { + route = {}; + alertService = new AlertService({ + i18n: { t: vi.fn() } as any, + toast: { + create: vi.fn(), + } as any, + }); + }); + + describe('OnInit', () => { + it('Should call load all on init', async () => { + // GIVEN + const userData = { + id: 1, + login: 'user', + firstName: 'first', + lastName: 'last', + email: 'first@last.com', + activated: true, + langKey: 'en', + authorities: [Authority.USER], + createdBy: 'admin', + createdDate: null, + lastModifiedBy: null, + lastModifiedDate: null, + password: null, + }; + axiosStub.get.mockResolvedValue({ data: userData }); + + route = { + params: { + userId: `${123}`, + }, + }; + + const wrapper = shallowMount(UserManagementView, { + global: { + stubs: { + 'b-badge': true, + 'router-link': true, + 'font-awesome-icon': true, + }, + provide: { + alertService, + }, + }, + }); + const userManagementView = wrapper.vm; + + // WHEN + await userManagementView.$nextTick(); + + // THEN + expect(axiosStub.get).toHaveBeenCalledWith(`api/admin/users/${123}`); + expect(userManagementView.user).toEqual(userData); + }); + }); +}); diff --git a/src/main/webapp/app/admin/user-management/user-management-view.component.ts b/src/main/webapp/app/admin/user-management/user-management-view.component.ts new file mode 100644 index 0000000..5acb1a0 --- /dev/null +++ b/src/main/webapp/app/admin/user-management/user-management-view.component.ts @@ -0,0 +1,40 @@ +import { type Ref, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; +import { useRoute } from 'vue-router'; + +import { useAlertService } from '@/shared/alert/alert.service'; +import { useDateFormat } from '@/shared/composables'; + +import UserManagementService from './user-management.service'; + +export default defineComponent({ + name: 'JhiUserManagementView', + setup() { + const route = useRoute(); + const { formatDateLong: formatDate } = useDateFormat(); + + const alertService = inject('alertService', () => useAlertService(), true); + const userManagementService = inject('userManagementService', () => new UserManagementService(), true); + + const user: Ref = ref(null); + + async function loadUser(userId: string) { + try { + const response = await userManagementService.get(userId); + user.value = response.data; + } catch (error) { + alertService.showHttpError(error.response); + } + } + + loadUser(route.params?.userId); + + return { + formatDate, + alertService, + userManagementService, + user, + t$: useI18n().t, + }; + }, +}); diff --git a/src/main/webapp/app/admin/user-management/user-management-view.vue b/src/main/webapp/app/admin/user-management/user-management-view.vue new file mode 100644 index 0000000..5432eba --- /dev/null +++ b/src/main/webapp/app/admin/user-management/user-management-view.vue @@ -0,0 +1,80 @@ + + + diff --git a/src/main/webapp/app/admin/user-management/user-management.component.spec.ts b/src/main/webapp/app/admin/user-management/user-management.component.spec.ts new file mode 100644 index 0000000..f4e442a --- /dev/null +++ b/src/main/webapp/app/admin/user-management/user-management.component.spec.ts @@ -0,0 +1,116 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ref } from 'vue'; + +import { shallowMount } from '@vue/test-utils'; +import axios from 'axios'; + +import AlertService from '@/shared/alert/alert.service'; +import { MESSAGE_ALERT_HEADER_NAME, MESSAGE_PARAM_HEADER_NAME } from '@/shared/jhipster/constants'; + +import UserManagement from './user-management.vue'; + +type UserManagementComponentType = InstanceType; + +const axiosStub = { + delete: vi.spyOn(axios, 'delete'), + get: vi.spyOn(axios, 'get'), + put: vi.spyOn(axios, 'put'), +}; + +describe('UserManagement Component', () => { + let userManagement: UserManagementComponentType; + let alertService: AlertService; + + beforeEach(() => { + axiosStub.put.mockReset(); + axiosStub.get.mockReset(); + axiosStub.get.mockResolvedValue({ headers: {} }); + + alertService = new AlertService({ + i18n: { t: vi.fn() } as any, + toast: { + create: vi.fn(), + } as any, + }); + + const wrapper = shallowMount(UserManagement, { + global: { + stubs: { + bPagination: true, + jhiItemCount: true, + bModal: true, + 'router-link': true, + 'jhi-sort-indicator': true, + 'font-awesome-icon': true, + 'b-button': true, + }, + directives: { + 'b-modal': {}, + }, + provide: { + alertService, + currentUsername: ref(''), + }, + }, + }); + userManagement = wrapper.vm; + }); + + describe('OnInit', () => { + it('Should call load all on init', async () => { + // WHEN + userManagement.loadAll(); + await userManagement.$nextTick(); + + // THEN + expect(axiosStub.get).toHaveBeenCalledWith(`api/admin/users?sort=id,asc&page=0&size=20`); + }); + }); + + describe('setActive', () => { + it('Should update user and call load all', async () => { + // GIVEN + axiosStub.put.mockResolvedValue({}); + + // WHEN + userManagement.setActive({ id: 123 }, true); + await userManagement.$nextTick(); + + // THEN + expect(axiosStub.put).toHaveBeenCalledWith(`api/admin/users`, { id: 123, activated: true }); + expect(axiosStub.get).toHaveBeenCalledWith(`api/admin/users?sort=id,asc&page=0&size=20`); + }); + }); + + describe('confirmDelete', () => { + it('Should call delete service on confirmDelete', async () => { + // GIVEN + axiosStub.delete.mockResolvedValue({ + headers: { + [MESSAGE_ALERT_HEADER_NAME]: '', + [MESSAGE_PARAM_HEADER_NAME]: '', + }, + }); + + // WHEN + userManagement.prepareRemove({ login: 123 }); + userManagement.deleteUser(); + await userManagement.$nextTick(); + + // THEN + expect(axiosStub.delete).toHaveBeenCalledWith(`api/admin/users/${123}`); + expect(axiosStub.get).toHaveBeenCalledWith(`api/admin/users?sort=id,asc&page=0&size=20`); + }); + }); + + describe('change order', () => { + it('should change order and invert reverse', () => { + // WHEN + userManagement.changeOrder('dummy-order'); + + // THEN + expect(userManagement.propOrder).toEqual('dummy-order'); + expect(userManagement.reverse).toBe(true); + }); + }); +}); diff --git a/src/main/webapp/app/admin/user-management/user-management.component.ts b/src/main/webapp/app/admin/user-management/user-management.component.ts new file mode 100644 index 0000000..e037564 --- /dev/null +++ b/src/main/webapp/app/admin/user-management/user-management.component.ts @@ -0,0 +1,141 @@ +import { type ComputedRef, type Ref, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { useAlertService } from '@/shared/alert/alert.service'; +import { useDateFormat } from '@/shared/composables'; +import { getMessageFromHeaders } from '@/shared/jhipster/headers'; + +import UserManagementService from './user-management.service'; + +export default defineComponent({ + name: 'JhiUserManagementComponent', + setup() { + const alertService = inject('alertService', () => useAlertService(), true); + const { formatDateShort: formatDate } = useDateFormat(); + const userManagementService = inject('userManagementService', () => new UserManagementService(), true); + const username = inject>('currentUsername'); + + const error = ref(''); + const success = ref(''); + const itemsPerPage = ref(20); + const page = ref(1); + const previousPage = ref(1); + const propOrder = ref('id'); + const reverse = ref(false); + const isLoading = ref(false); + const removeId: Ref = ref(null); + const users: Ref = ref([]); + const totalItems = ref(0); + const queryCount: Ref = ref(null); + + return { + formatDate, + userManagementService, + alertService, + error, + success, + itemsPerPage, + page, + previousPage, + propOrder, + reverse, + isLoading, + removeId, + users, + username, + totalItems, + queryCount, + t$: useI18n().t, + }; + }, + mounted(): void { + this.loadAll(); + }, + methods: { + setActive(user, isActivated): void { + user.activated = isActivated; + this.userManagementService + .update(user) + .then(() => { + this.error = null; + this.success = 'OK'; + this.loadAll(); + }) + .catch(() => { + this.success = null; + this.error = 'ERROR'; + user.activated = false; + }); + }, + loadAll(): void { + this.isLoading = true; + + this.userManagementService + .retrieve({ + sort: this.sort(), + page: this.page - 1, + size: this.itemsPerPage, + }) + .then(res => { + this.isLoading = false; + this.users = res.data; + this.totalItems = Number(res.headers['x-total-count']); + this.queryCount = this.totalItems; + }) + .catch(() => { + this.isLoading = false; + }); + }, + handleSyncList(): void { + this.loadAll(); + }, + sort(): any { + const result = [`${this.propOrder},${this.reverse ? 'desc' : 'asc'}`]; + if (this.propOrder !== 'id') { + result.push('id'); + } + return result; + }, + loadPage(page: number): void { + if (page !== this.previousPage) { + this.previousPage = page; + this.transition(); + } + }, + transition(): void { + this.loadAll(); + }, + changeOrder(propOrder: string): void { + this.propOrder = propOrder; + this.reverse = !this.reverse; + this.transition(); + }, + deleteUser(): void { + this.userManagementService + .remove(this.removeId) + .then(res => { + const message = getMessageFromHeaders(res.headers); + this.alertService.showInfo(message.alertKey ? this.t$(message.alertKey, { param: message.param }) : message.alertMessage, { + variant: 'danger', + }); + this.removeId = null; + this.loadAll(); + this.closeDialog(); + }) + .catch(error => { + this.alertService.showHttpError(error.response); + }); + }, + prepareRemove(instance): void { + this.removeId = instance.login; + if (this.$refs.removeUser as any) { + (this.$refs.removeUser as any).show(); + } + }, + closeDialog(): void { + if (this.$refs.removeUser as any) { + (this.$refs.removeUser as any).hide(); + } + }, + }, +}); diff --git a/src/main/webapp/app/admin/user-management/user-management.service.ts b/src/main/webapp/app/admin/user-management/user-management.service.ts new file mode 100644 index 0000000..b26cb8f --- /dev/null +++ b/src/main/webapp/app/admin/user-management/user-management.service.ts @@ -0,0 +1,33 @@ +import axios from 'axios'; + +import { type IUser } from '@/shared/model/user.model'; +import buildPaginationQueryOpts from '@/shared/sort/sorts'; + +export default class UserManagementService { + get(userId: string): Promise { + return axios.get(`api/admin/users/${userId}`); + } + + create(user: IUser): Promise { + return axios.post('api/admin/users', user); + } + + update(user: IUser): Promise { + return axios.put('api/admin/users', user); + } + + remove(userId: number): Promise { + return axios.delete(`api/admin/users/${userId}`); + } + + retrieve(req?: any): Promise { + return axios.get(`api/admin/users?${buildPaginationQueryOpts(req)}`); + } + + retrieveAuthorities(): Promise { + return axios.get('api/authorities').then(response => { + response.data = response.data.map(authority => authority.name); + return response; + }); + } +} diff --git a/src/main/webapp/app/admin/user-management/user-management.vue b/src/main/webapp/app/admin/user-management/user-management.vue new file mode 100644 index 0000000..77b8e35 --- /dev/null +++ b/src/main/webapp/app/admin/user-management/user-management.vue @@ -0,0 +1,152 @@ + + + diff --git a/src/main/webapp/app/app.component.ts b/src/main/webapp/app/app.component.ts new file mode 100644 index 0000000..d3163e4 --- /dev/null +++ b/src/main/webapp/app/app.component.ts @@ -0,0 +1,33 @@ +import { type Component, defineComponent, provide } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { BApp } from 'bootstrap-vue-next'; +import { storeToRefs } from 'pinia'; + +import LoginForm from '@/account/login-form/login-form.vue'; +import { useLoginModal } from '@/account/login-modal'; +import JhiFooter from '@/core/jhi-footer/jhi-footer.vue'; +import JhiNavbar from '@/core/jhi-navbar/jhi-navbar.vue'; +import Ribbon from '@/core/ribbon/ribbon.vue'; +import { useAlertService } from '@/shared/alert/alert.service'; +import '@/shared/config/dayjs'; + +export default defineComponent({ + name: 'App', + components: { + BApp: BApp as Component, + Ribbon, + JhiNavbar, + LoginForm, + JhiFooter, + }, + setup() { + provide('alertService', useAlertService()); + const { loginModalOpen } = storeToRefs(useLoginModal()); + + return { + loginModalOpen, + t$: useI18n().t, + }; + }, +}); diff --git a/src/main/webapp/app/app.vue b/src/main/webapp/app/app.vue new file mode 100644 index 0000000..54a90de --- /dev/null +++ b/src/main/webapp/app/app.vue @@ -0,0 +1,24 @@ + + + diff --git a/src/main/webapp/app/core/error/error.component.spec.ts b/src/main/webapp/app/core/error/error.component.spec.ts new file mode 100644 index 0000000..cefe4c9 --- /dev/null +++ b/src/main/webapp/app/core/error/error.component.spec.ts @@ -0,0 +1,95 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { type Ref, ref } from 'vue'; +import { type RouteLocation } from 'vue-router'; + +import { createTestingPinia } from '@pinia/testing'; +import { type ComponentMountingOptions, shallowMount } from '@vue/test-utils'; + +import { useLoginModal } from '@/account/login-modal'; + +import Error from './error.vue'; + +type ErrorComponentType = InstanceType; + +let route: Partial; + +vi.mock('vue-router', () => ({ + useRoute: () => route, +})); + +const customErrorMsg = 'An error occurred.'; + +describe('Error component', () => { + let error: ErrorComponentType; + let login: ReturnType; + let authenticated: Ref; + let mountOptions: ComponentMountingOptions; + + beforeEach(() => { + route = {}; + authenticated = ref(false); + mountOptions = { + global: { + plugins: [createTestingPinia()], + provide: { + authenticated, + }, + }, + }; + }); + + it('should have retrieve custom error on routing', () => { + route = { + path: '/custom-error', + name: 'CustomMessage', + meta: { errorMessage: customErrorMsg }, + }; + const wrapper = shallowMount(Error, mountOptions); + error = wrapper.vm; + login = useLoginModal(); + + expect(error.errorMessage).toBe(customErrorMsg); + expect(error.error403).toBeFalsy(); + expect(error.error404).toBeFalsy(); + expect(login.showLogin).not.toHaveBeenCalled(); + }); + + it('should have set forbidden error on routing', () => { + route = { + meta: { error403: true }, + }; + const wrapper = shallowMount(Error, mountOptions); + error = wrapper.vm; + login = useLoginModal(); + + expect(error.errorMessage).toBeNull(); + expect(error.error403).toBeTruthy(); + expect(error.error404).toBeFalsy(); + expect(login.showLogin).toHaveBeenCalled(); + }); + + it('should have set not found error on routing', () => { + route = { + meta: { error404: true }, + }; + const wrapper = shallowMount(Error, mountOptions); + error = wrapper.vm; + login = useLoginModal(); + + expect(error.errorMessage).toBeNull(); + expect(error.error403).toBeFalsy(); + expect(error.error404).toBeTruthy(); + expect(login.showLogin).not.toHaveBeenCalled(); + }); + + it('should have set default on no error', () => { + const wrapper = shallowMount(Error, mountOptions); + error = wrapper.vm; + login = useLoginModal(); + + expect(error.errorMessage).toBeNull(); + expect(error.error403).toBeFalsy(); + expect(error.error404).toBeFalsy(); + expect(login.showLogin).not.toHaveBeenCalled(); + }); +}); diff --git a/src/main/webapp/app/core/error/error.component.ts b/src/main/webapp/app/core/error/error.component.ts new file mode 100644 index 0000000..adcf3d2 --- /dev/null +++ b/src/main/webapp/app/core/error/error.component.ts @@ -0,0 +1,33 @@ +import { type ComputedRef, type Ref, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; +import { useRoute } from 'vue-router'; + +import { useLoginModal } from '@/account/login-modal'; + +export default defineComponent({ + name: 'Error', + setup() { + const { showLogin } = useLoginModal(); + const authenticated = inject>('authenticated'); + const errorMessage: Ref = ref(null); + const error403: Ref = ref(false); + const error404: Ref = ref(false); + const route = useRoute(); + + if (route.meta) { + errorMessage.value = route.meta.errorMessage ?? null; + error403.value = route.meta.error403 ?? false; + error404.value = route.meta.error404 ?? false; + if (!authenticated.value && error403.value) { + showLogin(); + } + } + + return { + errorMessage, + error403, + error404, + t$: useI18n().t, + }; + }, +}); diff --git a/src/main/webapp/app/core/error/error.vue b/src/main/webapp/app/core/error/error.vue new file mode 100644 index 0000000..79fd0dc --- /dev/null +++ b/src/main/webapp/app/core/error/error.vue @@ -0,0 +1,20 @@ + + + diff --git a/src/main/webapp/app/core/home/home.component.spec.ts b/src/main/webapp/app/core/home/home.component.spec.ts new file mode 100644 index 0000000..91f21ab --- /dev/null +++ b/src/main/webapp/app/core/home/home.component.spec.ts @@ -0,0 +1,55 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { ref } from 'vue'; + +import { createTestingPinia } from '@pinia/testing'; +import { shallowMount } from '@vue/test-utils'; + +import { useLoginModal } from '@/account/login-modal'; + +import Home from './home.vue'; + +type HomeComponentType = InstanceType; + +describe('Home', () => { + let home: HomeComponentType; + let authenticated; + let currentUsername; + let login: ReturnType; + + beforeEach(() => { + authenticated = ref(false); + currentUsername = ref(''); + const wrapper = shallowMount(Home, { + global: { + plugins: [createTestingPinia()], + stubs: { + 'router-link': true, + }, + provide: { + authenticated, + currentUsername, + }, + }, + }); + home = wrapper.vm; + login = useLoginModal(); + }); + + it('should not have user data set', () => { + expect(home.authenticated).toBeFalsy(); + expect(home.username).toBe(''); + }); + + it('should have user data set after authentication', () => { + authenticated.value = true; + currentUsername.value = 'test'; + + expect(home.authenticated).toBeTruthy(); + expect(home.username).toBe('test'); + }); + + it('should use login service', () => { + home.showLogin(); + expect(login.showLogin).toHaveBeenCalled(); + }); +}); diff --git a/src/main/webapp/app/core/home/home.component.ts b/src/main/webapp/app/core/home/home.component.ts new file mode 100644 index 0000000..363ea0d --- /dev/null +++ b/src/main/webapp/app/core/home/home.component.ts @@ -0,0 +1,19 @@ +import { type ComputedRef, defineComponent, inject } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { useLoginModal } from '@/account/login-modal'; + +export default defineComponent({ + setup() { + const { showLogin } = useLoginModal(); + const authenticated = inject>('authenticated'); + const username = inject>('currentUsername'); + + return { + authenticated, + username, + showLogin, + t$: useI18n().t, + }; + }, +}); diff --git a/src/main/webapp/app/core/home/home.vue b/src/main/webapp/app/core/home/home.vue new file mode 100644 index 0000000..1eeab6c --- /dev/null +++ b/src/main/webapp/app/core/home/home.vue @@ -0,0 +1,60 @@ + + + diff --git a/src/main/webapp/app/core/jhi-footer/jhi-footer.component.ts b/src/main/webapp/app/core/jhi-footer/jhi-footer.component.ts new file mode 100644 index 0000000..77090d0 --- /dev/null +++ b/src/main/webapp/app/core/jhi-footer/jhi-footer.component.ts @@ -0,0 +1,11 @@ +import { defineComponent } from 'vue'; +import { useI18n } from 'vue-i18n'; + +export default defineComponent({ + name: 'JhiFooter', + setup() { + return { + t$: useI18n().t, + }; + }, +}); diff --git a/src/main/webapp/app/core/jhi-footer/jhi-footer.vue b/src/main/webapp/app/core/jhi-footer/jhi-footer.vue new file mode 100644 index 0000000..78e5ae7 --- /dev/null +++ b/src/main/webapp/app/core/jhi-footer/jhi-footer.vue @@ -0,0 +1,7 @@ + + + diff --git a/src/main/webapp/app/core/jhi-navbar/jhi-navbar.component.spec.ts b/src/main/webapp/app/core/jhi-navbar/jhi-navbar.component.spec.ts new file mode 100644 index 0000000..8d149ed --- /dev/null +++ b/src/main/webapp/app/core/jhi-navbar/jhi-navbar.component.spec.ts @@ -0,0 +1,110 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { computed } from 'vue'; +import { type Router } from 'vue-router'; + +import { createTestingPinia } from '@pinia/testing'; +import { shallowMount } from '@vue/test-utils'; + +import { useLoginModal } from '@/account/login-modal'; +import { createRouter } from '@/router'; +import { useStore } from '@/store'; + +import JhiNavbar from './jhi-navbar.vue'; + +type JhiNavbarComponentType = InstanceType; + +const pinia = createTestingPinia({ stubActions: false }); +const store = useStore(); + +describe('JhiNavbar', () => { + let jhiNavbar: JhiNavbarComponentType; + let login: ReturnType; + const accountService = { hasAnyAuthorityAndCheckAuth: vi.fn().mockImplementation(() => Promise.resolve(true)) }; + const changeLanguage = vi.fn(); + let router: Router; + + beforeEach(() => { + router = createRouter(); + const wrapper = shallowMount(JhiNavbar, { + global: { + plugins: [pinia, router], + stubs: { + 'font-awesome-icon': true, + 'b-navbar': true, + 'b-navbar-nav': true, + 'b-dropdown-item': true, + 'b-collapse': true, + 'b-nav-item': true, + 'b-nav-item-dropdown': true, + 'b-navbar-toggle': true, + 'b-navbar-brand': true, + }, + provide: { + currentLanguage: computed(() => 'foo'), + changeLanguage, + accountService, + }, + }, + }); + jhiNavbar = wrapper.vm; + login = useLoginModal(); + }); + + it('should not have user data set', () => { + expect(jhiNavbar.authenticated).toBeFalsy(); + expect(jhiNavbar.openAPIEnabled).toBeFalsy(); + expect(jhiNavbar.inProduction).toBeFalsy(); + }); + + it('should have user data set after authentication', () => { + store.setAuthentication({ login: 'test' }); + + expect(jhiNavbar.authenticated).toBeTruthy(); + }); + + it('should have profile info set after info retrieved', () => { + store.setActiveProfiles(['prod', 'api-docs']); + + expect(jhiNavbar.openAPIEnabled).toBeTruthy(); + expect(jhiNavbar.inProduction).toBeTruthy(); + }); + + it('should use login service', () => { + jhiNavbar.showLogin(); + + expect(login.showLogin).toHaveBeenCalled(); + }); + + it('should use account service', () => { + jhiNavbar.hasAnyAuthority('auth'); + + expect(accountService.hasAnyAuthorityAndCheckAuth).toHaveBeenCalled(); + }); + + it('logout should clear credentials and return to the home page when no provider URL is returned', async () => { + store.setAuthentication({ login: 'test' }); + + await jhiNavbar.logout(); + + expect(jhiNavbar.authenticated).toBeFalsy(); + }); + + it('should determine active route', async () => { + await router.push('/forbidden'); + + expect(jhiNavbar.subIsActive('/titi')).toBeFalsy(); + expect(jhiNavbar.subIsActive('/forbidden')).toBeTruthy(); + expect(jhiNavbar.subIsActive(['/forbidden', 'forbidden'])).toBeTruthy(); + }); + + it('should call translationService when changing language', () => { + jhiNavbar.changeLanguage('fr'); + + expect(changeLanguage).toHaveBeenCalled(); + }); + + it('should check for correct language', () => { + expect(jhiNavbar.isActiveLanguage('en')).toBeFalsy(); + expect(jhiNavbar.isActiveLanguage('foo')).toBeTruthy(); + }); +}); diff --git a/src/main/webapp/app/core/jhi-navbar/jhi-navbar.component.ts b/src/main/webapp/app/core/jhi-navbar/jhi-navbar.component.ts new file mode 100644 index 0000000..c30ca35 --- /dev/null +++ b/src/main/webapp/app/core/jhi-navbar/jhi-navbar.component.ts @@ -0,0 +1,79 @@ +import { type Ref, computed, defineComponent, inject, ref } from 'vue'; +import { useI18n } from 'vue-i18n'; +import { useRouter } from 'vue-router'; + +import { storeToRefs } from 'pinia'; + +import type AccountService from '@/account/account.service'; +import { useLoginModal } from '@/account/login-modal'; +import EntitiesMenu from '@/entities/entities-menu.vue'; +import languages from '@/shared/config/languages'; +import { AUTHENTICATION_TOKEN_KEY } from '@/shared/jhipster/constants'; +import { useStore } from '@/store'; + +export default defineComponent({ + name: 'JhiNavbar', + components: { + 'entities-menu': EntitiesMenu, + }, + setup() { + const { showLogin } = useLoginModal(); + const accountService = inject('accountService'); + const currentLanguage = inject('currentLanguage', () => computed(() => navigator.language ?? 'en'), true); + const changeLanguage = inject<(string) => Promise>('changeLanguage'); + + const isActiveLanguage = (key: string) => key === currentLanguage.value; + + const router = useRouter(); + const store = useStore(); + + const version = `v${APP_VERSION}`; + const hasAnyAuthorityValues: Ref = ref({}); + + const openAPIEnabled = computed(() => store.activeProfiles.includes('api-docs')); + const inProduction = computed(() => store.activeProfiles.includes('prod')); + const { authenticated } = storeToRefs(store); + + const subIsActive = (input: string | string[]) => { + const paths = Array.isArray(input) ? input : [input]; + // current path starts with this path string + return paths.some(path => router.currentRoute.value.path.startsWith(path)); + }; + + const logout = async () => { + localStorage.removeItem(AUTHENTICATION_TOKEN_KEY); + sessionStorage.removeItem(AUTHENTICATION_TOKEN_KEY); + store.logout(); + if (router.currentRoute.value.path !== '/') { + await router.push('/'); + } + }; + + return { + logout, + subIsActive, + accountService, + showLogin, + changeLanguage, + languages: languages(), + isActiveLanguage, + version, + currentLanguage, + hasAnyAuthorityValues, + openAPIEnabled, + inProduction, + authenticated, + t$: useI18n().t, + }; + }, + methods: { + hasAnyAuthority(authorities: any): boolean { + this.accountService.hasAnyAuthorityAndCheckAuth(authorities).then(value => { + if (this.hasAnyAuthorityValues[authorities] !== value) { + this.hasAnyAuthorityValues = { ...this.hasAnyAuthorityValues, [authorities]: value }; + } + }); + return this.hasAnyAuthorityValues[authorities] ?? false; + }, + }, +}); diff --git a/src/main/webapp/app/core/jhi-navbar/jhi-navbar.vue b/src/main/webapp/app/core/jhi-navbar/jhi-navbar.vue new file mode 100644 index 0000000..4b8dc84 --- /dev/null +++ b/src/main/webapp/app/core/jhi-navbar/jhi-navbar.vue @@ -0,0 +1,193 @@ + + + + + + diff --git a/src/main/webapp/app/core/ribbon/ribbon.component.spec.ts b/src/main/webapp/app/core/ribbon/ribbon.component.spec.ts new file mode 100644 index 0000000..49e2a79 --- /dev/null +++ b/src/main/webapp/app/core/ribbon/ribbon.component.spec.ts @@ -0,0 +1,47 @@ +import { beforeEach, describe, expect, it } from 'vitest'; + +import { createTestingPinia } from '@pinia/testing'; +import { shallowMount } from '@vue/test-utils'; + +import { type AccountStore, useStore } from '@/store'; + +import Ribbon from './ribbon.vue'; + +type RibbonComponentType = InstanceType; + +const pinia = createTestingPinia({ stubActions: false }); + +describe('Ribbon', () => { + let ribbon: RibbonComponentType; + let store: AccountStore; + + beforeEach(async () => { + const wrapper = shallowMount(Ribbon, { + global: { + plugins: [pinia], + }, + }); + ribbon = wrapper.vm; + await ribbon.$nextTick(); + store = useStore(); + store.setRibbonOnProfiles(null); + }); + + it('should not have ribbonEnabled when no data', () => { + expect(ribbon.ribbonEnabled).toBeFalsy(); + }); + + it('should have ribbonEnabled set to value in store', () => { + const profile = 'dev'; + store.setActiveProfiles(['foo', profile, 'bar']); + store.setRibbonOnProfiles(profile); + expect(ribbon.ribbonEnabled).toBeTruthy(); + }); + + it('should not have ribbonEnabled when profile not activated', () => { + const profile = 'dev'; + store.setActiveProfiles(['foo', 'bar']); + store.setRibbonOnProfiles(profile); + expect(ribbon.ribbonEnabled).toBeFalsy(); + }); +}); diff --git a/src/main/webapp/app/core/ribbon/ribbon.component.ts b/src/main/webapp/app/core/ribbon/ribbon.component.ts new file mode 100644 index 0000000..a829c52 --- /dev/null +++ b/src/main/webapp/app/core/ribbon/ribbon.component.ts @@ -0,0 +1,19 @@ +import { computed, defineComponent } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import { useStore } from '@/store'; + +export default defineComponent({ + name: 'Ribbon', + setup() { + const store = useStore(); + const ribbonEnv = computed(() => store.ribbonOnProfiles); + const ribbonEnabled = computed(() => store.ribbonOnProfiles && store.activeProfiles.indexOf(store.ribbonOnProfiles) > -1); + + return { + ribbonEnv, + ribbonEnabled, + t$: useI18n().t, + }; + }, +}); diff --git a/src/main/webapp/app/core/ribbon/ribbon.vue b/src/main/webapp/app/core/ribbon/ribbon.vue new file mode 100644 index 0000000..1d75e35 --- /dev/null +++ b/src/main/webapp/app/core/ribbon/ribbon.vue @@ -0,0 +1,43 @@ + + + + + + diff --git a/src/main/webapp/app/declarations.d.ts b/src/main/webapp/app/declarations.d.ts new file mode 100644 index 0000000..f8306dc --- /dev/null +++ b/src/main/webapp/app/declarations.d.ts @@ -0,0 +1,6 @@ +// These constants are injected via webpack environment variables. +// You can add more variables in webpack.common.js or in profile specific webpack..js files. +// If you change the values in the webpack config files, you need to re run webpack to update the application + +declare const SERVER_API_URL: string; +declare const APP_VERSION: string; diff --git a/src/main/webapp/app/entities/entities-menu.component.ts b/src/main/webapp/app/entities/entities-menu.component.ts new file mode 100644 index 0000000..fab94eb --- /dev/null +++ b/src/main/webapp/app/entities/entities-menu.component.ts @@ -0,0 +1,12 @@ +import { defineComponent } from 'vue'; +import { useI18n } from 'vue-i18n'; + +export default defineComponent({ + name: 'EntitiesMenu', + setup() { + const i18n = useI18n(); + return { + t$: i18n.t, + }; + }, +}); diff --git a/src/main/webapp/app/entities/entities-menu.vue b/src/main/webapp/app/entities/entities-menu.vue new file mode 100644 index 0000000..22b4569 --- /dev/null +++ b/src/main/webapp/app/entities/entities-menu.vue @@ -0,0 +1,7 @@ + + + diff --git a/src/main/webapp/app/entities/entities.component.ts b/src/main/webapp/app/entities/entities.component.ts new file mode 100644 index 0000000..330630b --- /dev/null +++ b/src/main/webapp/app/entities/entities.component.ts @@ -0,0 +1,12 @@ +import { defineComponent, provide } from 'vue'; + +import UserService from '@/entities/user/user.service'; +// jhipster-needle-add-entity-service-to-entities-component-import - JHipster will import entities services here + +export default defineComponent({ + name: 'Entities', + setup() { + provide('userService', () => new UserService()); + // jhipster-needle-add-entity-service-to-entities-component - JHipster will import entities services here + }, +}); diff --git a/src/main/webapp/app/entities/entities.vue b/src/main/webapp/app/entities/entities.vue new file mode 100644 index 0000000..b22f96f --- /dev/null +++ b/src/main/webapp/app/entities/entities.vue @@ -0,0 +1,5 @@ + + + diff --git a/src/main/webapp/app/entities/user/user.service.ts b/src/main/webapp/app/entities/user/user.service.ts new file mode 100644 index 0000000..91736e4 --- /dev/null +++ b/src/main/webapp/app/entities/user/user.service.ts @@ -0,0 +1,9 @@ +import axios from 'axios'; + +const baseApiUrl = 'api/users'; + +export default class UserService { + retrieve(): Promise { + return axios.get(baseApiUrl); + } +} diff --git a/src/main/webapp/app/locale/translation.service.ts b/src/main/webapp/app/locale/translation.service.ts new file mode 100644 index 0000000..a6ed3e3 --- /dev/null +++ b/src/main/webapp/app/locale/translation.service.ts @@ -0,0 +1,40 @@ +import { type Composer } from 'vue-i18n'; + +import axios from 'axios'; +import dayjs from 'dayjs'; + +import languages from '@/shared/config/languages'; + +export default class TranslationService { + private readonly i18n: Composer; + private readonly languages = languages(); + private readonly loadedLanguages: Set = new Set(); + + constructor(i18n: Composer) { + this.i18n = i18n; + } + + async refreshTranslation(newLanguage: string) { + if (this.i18n && !this.loadedLanguages.has(newLanguage)) { + const translations = await import(`../../i18n/${newLanguage}/${newLanguage}.js`); + this.i18n.setLocaleMessage(newLanguage, translations.default); + + this.loadedLanguages.add(newLanguage); + } + } + + setLocale(lang: string) { + dayjs.locale(lang); + this.i18n.locale.value = lang; + axios.defaults.headers.common['Accept-Language'] = lang; + document.querySelector('html').setAttribute('lang', lang); + } + + isLanguageSupported(lang: string) { + return Boolean(this.languages[lang]); + } + + getLocalStoreLanguage(): string | null { + return localStorage.getItem('currentLanguage'); + } +} diff --git a/src/main/webapp/app/main.ts b/src/main/webapp/app/main.ts new file mode 100644 index 0000000..a0d9c1b --- /dev/null +++ b/src/main/webapp/app/main.ts @@ -0,0 +1,132 @@ +// The Vue build version to load with the `import` command +// (runtime-only or standalone) has been set in webpack.common with an alias. +import { computed, createApp, onMounted, provide, watch } from 'vue'; +import { useI18n } from 'vue-i18n'; +import { START_LOCATION } from 'vue-router'; + +import { createPinia, storeToRefs } from 'pinia'; + +import AccountService from '@/account/account.service'; +import { useLoginModal } from '@/account/login-modal'; +import TranslationService from '@/locale/translation.service'; +import { setupAxiosInterceptors } from '@/shared/config/axios-interceptor'; +import { initFortAwesome, initI18N } from '@/shared/config/config'; +import { initBootstrapVue } from '@/shared/config/config-bootstrap-vue'; +import JhiItemCount from '@/shared/jhi-item-count.vue'; +import { AUTHENTICATION_TOKEN_KEY } from '@/shared/jhipster/constants'; +import JhiSortIndicator from '@/shared/sort/jhi-sort-indicator.vue'; +import { useStore, useTranslationStore } from '@/store'; + +import App from './app.vue'; +import router from './router'; + +import '../content/scss/global.scss'; +import '../content/scss/vendor.scss'; + +const pinia = createPinia(); + +// jhipster-needle-add-entity-service-to-main-import - JHipster will import entities services here + +const i18n = initI18N(); + +const app = createApp({ + components: { App }, + setup() { + const { hideLogin, showLogin } = useLoginModal(); + const store = useStore(); + const accountService = new AccountService(store); + const i18n = useI18n(); + const translationStore = useTranslationStore(); + const translationService = new TranslationService(i18n); + + const changeLanguage = async (newLanguage: string) => { + if (newLanguage && i18n.locale.value !== newLanguage) { + await translationService.refreshTranslation(newLanguage); + translationStore.setCurrentLanguage(newLanguage); + } + }; + + provide('currentLanguage', i18n.locale); + provide('changeLanguage', changeLanguage); + + watch( + () => store.account, + async value => { + if (!translationService.getLocalStoreLanguage()) { + await changeLanguage(value?.langKey); + } + }, + ); + + watch( + () => translationStore.currentLanguage, + value => { + translationService.setLocale(value); + }, + ); + + onMounted(async () => { + const lang = [translationService.getLocalStoreLanguage(), store.account?.langKey, navigator.language, 'en'].find( + lang => lang && translationService.isLanguageSupported(lang), + ); + await changeLanguage(lang); + }); + + router.beforeResolve(async (to, from) => { + // Make sure login modal is closed when navigating. + // The initial navigation may resolve after the user opened the login modal, don't close it. + if (from !== START_LOCATION) { + hideLogin(); + } + + if (!store.authenticated) { + await accountService.update(); + } + if (to.meta?.authorities && to.meta.authorities.length > 0) { + const value = await accountService.hasAnyAuthorityAndCheckAuth(to.meta.authorities); + if (!value && from.path !== '/forbidden') { + return { path: '/forbidden' }; + } + } + return true; + }); + + setupAxiosInterceptors( + error => { + const url = error.response?.config?.url; + const status = error.status || error.response?.status; + if (status === 401) { + // Store logged out state. + sessionStorage.removeItem(AUTHENTICATION_TOKEN_KEY); + localStorage.removeItem(AUTHENTICATION_TOKEN_KEY); + store.logout(); + if (!url?.endsWith('api/account') && !url?.endsWith('api/authenticate')) { + // Ask for a new authentication + showLogin(); + return; + } + } + return Promise.reject(error); + }, + error => Promise.reject(error), + ); + + const { authenticated } = storeToRefs(store); + provide('authenticated', authenticated); + provide( + 'currentUsername', + computed(() => store.account?.login), + ); + + provide('translationService', translationService); + provide('accountService', accountService); + // jhipster-needle-add-entity-service-to-main - JHipster will import entities services here + }, + template: '', +}); + +initFortAwesome(app); + +initBootstrapVue(app); + +app.component('JhiItemCount', JhiItemCount).component('JhiSortIndicator', JhiSortIndicator).use(router).use(pinia).use(i18n).mount('#app'); diff --git a/src/main/webapp/app/router/account.ts b/src/main/webapp/app/router/account.ts new file mode 100644 index 0000000..903d187 --- /dev/null +++ b/src/main/webapp/app/router/account.ts @@ -0,0 +1,43 @@ +import { Authority } from '@/shared/jhipster/constants'; + +const Register = () => import('@/account/register/register.vue'); +const Activate = () => import('@/account/activate/activate.vue'); +const ResetPasswordInit = () => import('@/account/reset-password/init/reset-password-init.vue'); +const ResetPasswordFinish = () => import('@/account/reset-password/finish/reset-password-finish.vue'); +const ChangePassword = () => import('@/account/change-password/change-password.vue'); +const Settings = () => import('@/account/settings/settings.vue'); + +export default [ + { + path: '/register', + name: 'Register', + component: Register, + }, + { + path: '/account/activate', + name: 'Activate', + component: Activate, + }, + { + path: '/account/reset/request', + name: 'ResetPasswordInit', + component: ResetPasswordInit, + }, + { + path: '/account/reset/finish', + name: 'ResetPasswordFinish', + component: ResetPasswordFinish, + }, + { + path: '/account/password', + name: 'ChangePassword', + component: ChangePassword, + meta: { authorities: [Authority.USER] }, + }, + { + path: '/account/settings', + name: 'Settings', + component: Settings, + meta: { authorities: [Authority.USER] }, + }, +]; diff --git a/src/main/webapp/app/router/admin.ts b/src/main/webapp/app/router/admin.ts new file mode 100644 index 0000000..5af2259 --- /dev/null +++ b/src/main/webapp/app/router/admin.ts @@ -0,0 +1,67 @@ +import { Authority } from '@/shared/jhipster/constants'; + +const JhiUserManagementComponent = () => import('@/admin/user-management/user-management.vue'); +const JhiUserManagementViewComponent = () => import('@/admin/user-management/user-management-view.vue'); +const JhiUserManagementEditComponent = () => import('@/admin/user-management/user-management-edit.vue'); +const JhiDocsComponent = () => import('@/admin/docs/docs.vue'); +const JhiConfigurationComponent = () => import('@/admin/configuration/configuration.vue'); +const JhiHealthComponent = () => import('@/admin/health/health.vue'); +const JhiLogsComponent = () => import('@/admin/logs/logs.vue'); +const JhiMetricsComponent = () => import('@/admin/metrics/metrics.vue'); + +export default [ + { + path: '/admin/user-management', + name: 'JhiUser', + component: JhiUserManagementComponent, + meta: { authorities: [Authority.ADMIN] }, + }, + { + path: '/admin/user-management/new', + name: 'JhiUserCreate', + component: JhiUserManagementEditComponent, + meta: { authorities: [Authority.ADMIN] }, + }, + { + path: '/admin/user-management/:userId/edit', + name: 'JhiUserEdit', + component: JhiUserManagementEditComponent, + meta: { authorities: [Authority.ADMIN] }, + }, + { + path: '/admin/user-management/:userId/view', + name: 'JhiUserView', + component: JhiUserManagementViewComponent, + meta: { authorities: [Authority.ADMIN] }, + }, + { + path: '/admin/docs', + name: 'JhiDocsComponent', + component: JhiDocsComponent, + meta: { authorities: [Authority.ADMIN] }, + }, + { + path: '/admin/health', + name: 'JhiHealthComponent', + component: JhiHealthComponent, + meta: { authorities: [Authority.ADMIN] }, + }, + { + path: '/admin/logs', + name: 'JhiLogsComponent', + component: JhiLogsComponent, + meta: { authorities: [Authority.ADMIN] }, + }, + { + path: '/admin/metrics', + name: 'JhiMetricsComponent', + component: JhiMetricsComponent, + meta: { authorities: [Authority.ADMIN] }, + }, + { + path: '/admin/configuration', + name: 'JhiConfigurationComponent', + component: JhiConfigurationComponent, + meta: { authorities: [Authority.ADMIN] }, + }, +]; diff --git a/src/main/webapp/app/router/entities.ts b/src/main/webapp/app/router/entities.ts new file mode 100644 index 0000000..451fe99 --- /dev/null +++ b/src/main/webapp/app/router/entities.ts @@ -0,0 +1,11 @@ +const Entities = () => import('@/entities/entities.vue'); + +// jhipster-needle-add-entity-to-router-import - JHipster will import entities to the router here + +export default { + path: '/', + component: Entities, + children: [ + // jhipster-needle-add-entity-to-router - JHipster will add entities to the router here + ], +}; diff --git a/src/main/webapp/app/router/index.ts b/src/main/webapp/app/router/index.ts new file mode 100644 index 0000000..9979b1a --- /dev/null +++ b/src/main/webapp/app/router/index.ts @@ -0,0 +1,47 @@ +import { createRouter as createVueRouter, createWebHistory } from 'vue-router'; + +const Home = () => import('@/core/home/home.vue'); +const Error = () => import('@/core/error/error.vue'); +import account from '@/router/account'; +import admin from '@/router/admin'; +import entities from '@/router/entities'; +import pages from '@/router/pages'; + +export const createRouter = () => + createVueRouter({ + history: createWebHistory(), + routes: [ + { + path: '/', + name: 'Home', + component: Home, + }, + { + path: '/forbidden', + name: 'Forbidden', + component: Error, + meta: { error403: true }, + }, + { + path: '/not-found', + name: 'NotFound', + component: Error, + meta: { error404: true }, + }, + ...account, + ...admin, + entities, + ...pages, + ], + }); + +const router = createRouter(); + +router.beforeResolve(async to => { + if (!to.matched.length) { + return { path: '/not-found' }; + } + return true; +}); + +export default router; diff --git a/src/main/webapp/app/router/pages.ts b/src/main/webapp/app/router/pages.ts new file mode 100644 index 0000000..80c2e55 --- /dev/null +++ b/src/main/webapp/app/router/pages.ts @@ -0,0 +1,5 @@ +// jhipster-needle-add-entity-to-router-import - JHipster will import entities to the router here + +export default [ + // jhipster-needle-add-entity-to-router - JHipster will add entities to the router here +]; diff --git a/src/main/webapp/app/shared/alert/alert.service.spec.ts b/src/main/webapp/app/shared/alert/alert.service.spec.ts new file mode 100644 index 0000000..b4eed2d --- /dev/null +++ b/src/main/webapp/app/shared/alert/alert.service.spec.ts @@ -0,0 +1,188 @@ +import { type Mock, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { MESSAGE_ERROR_HEADER_NAME, MESSAGE_PARAM_HEADER_NAME } from '@/shared/jhipster/constants'; + +import AlertService from './alert.service'; + +describe('Alert Service test suite', () => { + let translationStub: Mock; + let toastStub: Mock; + let alertService: AlertService; + + beforeEach(() => { + translationStub = vi.fn(); + toastStub = vi.fn(); + alertService = new AlertService({ + i18n: { t: translationStub } as any, + toast: { + create: toastStub, + } as any, + }); + }); + + it('should show error toast with translation/message', () => { + const message = 'translatedMessage'; + + // WHEN + alertService.showError(message); + + // THEN + expect(toastStub).toHaveBeenCalledExactlyOnceWith({ + body: message, + modelValue: 5000, + position: 'top-end', + title: 'Error', + variant: 'danger', + solid: true, + }); + }); + + it('should show not reachable toast when http status = 0', () => { + const translationKey = 'error.server.not.reachable'; + const message = 'Server not reachable'; + const httpErrorResponse = { + status: 0, + }; + // GIVEN + translationStub.mockReturnValueOnce(message); + + // WHEN + alertService.showHttpError(httpErrorResponse); + + // THEN + expect(translationStub).toHaveBeenCalledExactlyOnceWith(translationKey); + expect(toastStub).toHaveBeenCalledExactlyOnceWith({ + body: expect.any(String), + modelValue: 5000, + position: 'top-end', + solid: true, + title: 'Error', + variant: 'danger', + }); + }); + + it('should show parameterized error toast when http status = 400 and entity headers', () => { + const translationKey = 'error.update'; + const message = 'Updation Error'; + const httpErrorResponse = { + status: 400, + headers: { + [MESSAGE_ERROR_HEADER_NAME]: translationKey, + [MESSAGE_PARAM_HEADER_NAME]: 'dummyEntity', + }, + }; + // GIVEN + translationStub.mockImplementation(key => { + if (key === translationKey) { + return message; + } + if (key === 'global.menu.entities.dummyEntity') { + return 'DummyEntity'; + } + throw new Error(); + }); + + // WHEN + alertService.showHttpError(httpErrorResponse); + + // THEN + expect(translationStub).toHaveBeenCalledTimes(2); + expect(translationStub).toHaveBeenCalledWith(translationKey, { entityName: 'DummyEntity' }); + expect(translationStub).toHaveBeenCalledWith('global.menu.entities.dummyEntity'); + expect(toastStub).toHaveBeenCalledWith({ + body: expect.any(String), + modelValue: 5000, + position: 'top-end', + solid: true, + title: 'Error', + variant: 'danger', + }); + }); + + it('should show error toast with data.message when http status = 400 and entity headers', () => { + const message = 'Validation error'; + const httpErrorResponse = { + status: 400, + headers: { + [`${MESSAGE_ERROR_HEADER_NAME}400`]: 'error', + [`${MESSAGE_PARAM_HEADER_NAME}400`]: 'dummyEntity', + }, + data: { + message, + fieldErrors: { + field1: 'error1', + }, + }, + }; + + // GIVEN + translationStub.mockReturnValueOnce('DummyEntity'); + translationStub.mockReturnValueOnce(message); + + // WHEN + alertService.showHttpError(httpErrorResponse); + + // THEN + expect(translationStub).toHaveBeenCalledExactlyOnceWith(message); + expect(toastStub).toHaveBeenCalledExactlyOnceWith({ + body: expect.any(String), + modelValue: 5000, + position: 'top-end', + solid: true, + title: 'Error', + variant: 'danger', + }); + }); + + it('should show error toast when http status = 404', () => { + const translationKey = 'error.http.404'; + const message = 'The page does not exist.'; + const httpErrorResponse = { + status: 404, + }; + + // GIVEN + translationStub.mockReturnValueOnce(message); + + // WHEN + alertService.showHttpError(httpErrorResponse); + + // THEN + expect(translationStub).toHaveBeenCalledExactlyOnceWith(translationKey); + expect(toastStub).toHaveBeenCalledExactlyOnceWith({ + body: expect.any(String), + modelValue: 5000, + position: 'top-end', + solid: true, + title: 'Error', + variant: 'danger', + }); + }); + + it('should show error toast when http status != 400,404', () => { + const message = 'Error 500'; + const httpErrorResponse = { + status: 500, + data: { + message, + }, + }; + + // GIVEN + translationStub.mockReturnValueOnce(message); + + // WHEN + alertService.showHttpError(httpErrorResponse); + + // THEN + expect(translationStub).toHaveBeenCalledExactlyOnceWith(message); + expect(toastStub).toHaveBeenCalledExactlyOnceWith({ + body: expect.any(String), + modelValue: 5000, + position: 'top-end', + solid: true, + title: 'Error', + variant: 'danger', + }); + }); +}); diff --git a/src/main/webapp/app/shared/alert/alert.service.ts b/src/main/webapp/app/shared/alert/alert.service.ts new file mode 100644 index 0000000..e370fb7 --- /dev/null +++ b/src/main/webapp/app/shared/alert/alert.service.ts @@ -0,0 +1,86 @@ +import { type Composer, useI18n } from 'vue-i18n'; + +import { type BToastProps, useToast } from 'bootstrap-vue-next'; + +import { getMessageFromHeaders } from '@/shared/jhipster/headers'; + +export const useAlertService = () => { + const toast = useToast(); + if (!toast) { + throw new Error('BootstrapVue toast component was not found'); + } + const i18n = useI18n(); + return new AlertService({ + toast, + i18n, + }); +}; + +export default class AlertService { + private readonly toast: ReturnType; + private readonly i18n: Composer; + + constructor({ toast, i18n }: { toast: ReturnType; i18n: Composer }) { + this.toast = toast; + this.i18n = i18n; + } + + showInfo(toastMessage: string, props: BToastProps = {}) { + this.toast.create({ + modelValue: 5000, + position: 'top-end', + title: 'Info', + variant: 'info', + solid: true, + body: toastMessage, + ...props, + }); + } + + showSuccess(toastMessage: string) { + this.showInfo(toastMessage, { + title: 'Success', + variant: 'success', + }); + } + + showError(toastMessage: string) { + this.showInfo(toastMessage, { + title: 'Error', + variant: 'danger', + }); + } + + showHttpError({ data, status, headers }: any) { + let errorMessage: string | null = null; + switch (status) { + case 0: + errorMessage = this.i18n.t('error.server.not.reachable').toString(); + break; + + case 400: { + const message = getMessageFromHeaders(headers); + if (message.errorKey && message.param) { + errorMessage = this.i18n.t(message.errorKey, { entityName: this.i18n.t(`global.menu.entities.${message.param}`) }).toString(); + } else if (message.errorKey) { + errorMessage = this.i18n.t(message.errorKey).toString(); + } else if (message.errorMessage) { + errorMessage = message.errorMessage; + } else if (data.message) { + errorMessage = this.i18n.t(data.message).toString(); + } else if (data?.fieldErrors) { + errorMessage = 'Validation error'; + } + break; + } + + case 404: + errorMessage = this.i18n.t('error.http.404').toString(); + break; + + default: + errorMessage = this.i18n.t(data.message).toString(); + } + this.showError(errorMessage!); + } +} diff --git a/src/main/webapp/app/shared/composables/date-format.ts b/src/main/webapp/app/shared/composables/date-format.ts new file mode 100644 index 0000000..860c2f9 --- /dev/null +++ b/src/main/webapp/app/shared/composables/date-format.ts @@ -0,0 +1,51 @@ +import { type Ref } from 'vue'; +import { useI18n } from 'vue-i18n'; + +import dayjs from 'dayjs'; + +export const DATE_FORMAT = 'YYYY-MM-DD'; +export const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm'; + +export const DATE_TIME_LONG_FORMAT = 'YYYY-MM-DDTHH:mm'; + +export const useDateFormat = ({ entityRef }: { entityRef?: Ref> } = {}) => { + const formatDate = value => (value ? dayjs(value).format(DATE_TIME_FORMAT) : ''); + const dateFormatUtils = { + convertDateTimeFromServer: (date: Date): string => (date && dayjs(date).isValid() ? dayjs(date).format(DATE_TIME_LONG_FORMAT) : null), + formatDate, + formatDuration: value => (value ? (dayjs.duration(value).humanize() ?? value) : ''), + }; + const entityUtils = entityRef + ? { + ...dateFormatUtils, + updateInstantField: (field: string, event: any) => { + if (event.target?.value) { + entityRef.value[field] = dayjs(event.target.value, DATE_TIME_LONG_FORMAT); + } else { + entityRef.value[field] = null; + } + }, + updateZonedDateTimeField: (field: string, event: any) => { + if (event.target?.value) { + entityRef.value[field] = dayjs(event.target.value, DATE_TIME_LONG_FORMAT); + } else { + entityRef.value[field] = null; + } + }, + } + : {}; + + const i18n = useI18n(); + const formatDateI18N = (date, format = 'short') => (date ? i18n.d(Date.parse(date), format) : null); + const i18nUtils = { + formatDateI18N, + formatDateLong: date => formatDateI18N(date, 'long'), + formatDateShort: date => formatDateI18N(date, 'short'), + }; + + return { + ...dateFormatUtils, + ...entityUtils, + ...i18nUtils, + }; +}; diff --git a/src/main/webapp/app/shared/composables/index.ts b/src/main/webapp/app/shared/composables/index.ts new file mode 100644 index 0000000..3040a56 --- /dev/null +++ b/src/main/webapp/app/shared/composables/index.ts @@ -0,0 +1,2 @@ +export { useDateFormat } from './date-format'; +export { useValidation } from './validation'; diff --git a/src/main/webapp/app/shared/composables/validation.ts b/src/main/webapp/app/shared/composables/validation.ts new file mode 100644 index 0000000..76f2048 --- /dev/null +++ b/src/main/webapp/app/shared/composables/validation.ts @@ -0,0 +1,14 @@ +import { decimal, helpers, integer, maxLength, maxValue, minLength, minValue, required, sameAs } from '@vuelidate/validators'; + +export const useValidation = () => { + return { + required: (message: string) => helpers.withMessage(message, required), + decimal: (message: string) => helpers.withMessage(message, decimal), + integer: (message: string) => helpers.withMessage(message, integer), + sameAs: (message: string, ...args: Parameters) => helpers.withMessage(message, sameAs(...args)), + minLength: (message: string, ...args: Parameters) => helpers.withMessage(message, minLength(...args)), + maxLength: (message: string, ...args: Parameters) => helpers.withMessage(message, maxLength(...args)), + minValue: (message: string, ...args: Parameters) => helpers.withMessage(message, minValue(...args)), + maxValue: (message: string, ...args: Parameters) => helpers.withMessage(message, maxValue(...args)), + }; +}; diff --git a/src/main/webapp/app/shared/computables/arrays.ts b/src/main/webapp/app/shared/computables/arrays.ts new file mode 100644 index 0000000..45e3a3c --- /dev/null +++ b/src/main/webapp/app/shared/computables/arrays.ts @@ -0,0 +1,58 @@ +const compareString = (a: string, b: string): number => { + if (b == null) return 1; + if (a == null) return -1; + + return a.localeCompare(b); +}; + +const asString = (val): string => (typeof val === 'string' ? val : `${val}`); + +const compareAny = (a, b): number => { + if (b == null) return 1; + if (a == null) return -1; + + return a - b; +}; + +export type OrderByOptions = { orderByProp: string; reverse?: boolean }; + +export const orderBy = (array: any[], opts: OrderByOptions) => { + if (!Array.isArray(array)) return array; + + const { orderByProp, reverse = false } = opts; + let sorted: any[]; + if (array.some(el => typeof el[orderByProp] === 'string')) { + sorted = array.sort((a, b) => compareString(asString(a), asString(b))); + } else { + sorted = array.sort((a, b) => compareAny(a, b)); + } + if (reverse) { + return sorted.slice().reverse(); + } + return sorted; +}; + +export type FilterByOptions = { filterByTerm: string; filterMaxDepth?: number }; + +const filterObject = (val: any, opts: FilterByOptions): boolean => { + const { filterByTerm, filterMaxDepth = 2 } = opts; + if (typeof val === 'string') { + return val.toLocaleLowerCase().startsWith(filterByTerm); + } + if (typeof val === 'object') { + if (filterMaxDepth < 0) return false; + for (const value of Object.values(val)) { + if (filterObject(value, { filterByTerm, filterMaxDepth: filterMaxDepth - 1 })) return true; + } + return false; + } + return `${val}`.toLocaleLowerCase().startsWith(filterByTerm); +}; + +export const filterBy = (array: any, opts: FilterByOptions) => { + return Array.isArray(array) && opts.filterByTerm + ? array.filter(el => filterObject(el, { ...opts, filterByTerm: opts.filterByTerm.toLocaleLowerCase() })) + : array; +}; + +export const orderAndFilterBy = (array: any, opts: FilterByOptions & OrderByOptions) => orderBy(filterBy(array, opts), opts); diff --git a/src/main/webapp/app/shared/computables/index.ts b/src/main/webapp/app/shared/computables/index.ts new file mode 100644 index 0000000..4bcce8e --- /dev/null +++ b/src/main/webapp/app/shared/computables/index.ts @@ -0,0 +1 @@ +export * from './arrays'; diff --git a/src/main/webapp/app/shared/config/axios-interceptor.spec.ts b/src/main/webapp/app/shared/config/axios-interceptor.spec.ts new file mode 100644 index 0000000..576c4c9 --- /dev/null +++ b/src/main/webapp/app/shared/config/axios-interceptor.spec.ts @@ -0,0 +1,72 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import axios from 'axios'; +import MockAdapter from 'axios-mock-adapter'; + +import { AUTHENTICATION_TOKEN_KEY } from '@/shared/jhipster/constants'; + +import * as setupAxiosConfig from './axios-interceptor'; + +const mock = new MockAdapter(axios); + +describe('Axios interceptor', () => { + beforeEach(() => { + axios.interceptors.request.clear(); + axios.interceptors.response.clear(); + }); + + it('should use localStorage to provide bearer', () => { + localStorage.setItem(AUTHENTICATION_TOKEN_KEY, 'auth'); + const result = setupAxiosConfig.onRequestSuccess(() => console.log('A problem occurred')); + + expect(result.headers.Authorization).toBe('Bearer auth'); + expect(result.url.indexOf(SERVER_API_URL)).toBeGreaterThan(-1); + }); + + it('should use sessionStorage to provide bearer', () => { + sessionStorage.setItem(AUTHENTICATION_TOKEN_KEY, 'auth'); + const result = setupAxiosConfig.onRequestSuccess(() => console.log('A problem occurred')); + + expect(result.headers.Authorization).toBe('Bearer auth'); + expect(result.url.indexOf(SERVER_API_URL)).toBeGreaterThan(-1); + }); +}); + +describe('Axios errors interceptor', () => { + it('should use callback on 401, 403 errors', async () => { + const callback = vi.fn(); + + setupAxiosConfig.setupAxiosInterceptors(callback, () => {}); + + try { + mock.onGet().reply(401); + await axios('/api/test'); + } catch { + expect(callback).toHaveBeenCalled(); + } + }); + it('should use callback on 50x errors', async () => { + const callback = vi.fn(); + + setupAxiosConfig.setupAxiosInterceptors(() => {}, callback); + + try { + mock.onGet().reply(500); + await axios('/api/test'); + } catch { + expect(callback).toHaveBeenCalled(); + } + }); + it('should not use callback for errors different 50x, 401, 403', async () => { + const callback = vi.fn(); + + setupAxiosConfig.setupAxiosInterceptors(() => {}, callback); + + try { + mock.onGet().reply(402); + await axios('/api/test'); + } catch { + expect(callback).not.toHaveBeenCalled(); + } + }); +}); diff --git a/src/main/webapp/app/shared/config/axios-interceptor.ts b/src/main/webapp/app/shared/config/axios-interceptor.ts new file mode 100644 index 0000000..caa3708 --- /dev/null +++ b/src/main/webapp/app/shared/config/axios-interceptor.ts @@ -0,0 +1,36 @@ +import axios from 'axios'; + +import { AUTHENTICATION_TOKEN_KEY } from '@/shared/jhipster/constants'; + +const TIMEOUT = 1 * 60 * 1000; +const onRequestSuccess = config => { + const token = localStorage.getItem(AUTHENTICATION_TOKEN_KEY) ?? sessionStorage.getItem(AUTHENTICATION_TOKEN_KEY); + if (token) { + if (!config.headers) { + config.headers = {}; + } + config.headers.Authorization = `Bearer ${token}`; + } + config.timeout = TIMEOUT; + config.url = `${SERVER_API_URL}${config.url}`; + return config; +}; +const setupAxiosInterceptors = (onUnauthenticated, onServerError) => { + const onResponseError = err => { + const status = err.status || err.response?.status; + if (status === 403 || status === 401) { + return onUnauthenticated(err); + } + if (status >= 500) { + return onServerError(err); + } + return Promise.reject(err); + }; + + if (axios.interceptors) { + axios.interceptors.request.use(onRequestSuccess); + axios.interceptors.response.use(res => res, onResponseError); + } +}; + +export { onRequestSuccess, setupAxiosInterceptors }; diff --git a/src/main/webapp/app/shared/config/config-bootstrap-vue.ts b/src/main/webapp/app/shared/config/config-bootstrap-vue.ts new file mode 100644 index 0000000..67ae951 --- /dev/null +++ b/src/main/webapp/app/shared/config/config-bootstrap-vue.ts @@ -0,0 +1,52 @@ +import type { App } from 'vue'; + +import { + BAlert, + BBadge, + BButton, + BCollapse, + BDropdownItem, + BForm, + BFormCheckbox, + BFormGroup, + BFormInput, + BLink, + BModal, + BNavItem, + BNavItemDropdown, + BNavbar, + BNavbarBrand, + BNavbarNav, + BNavbarToggle, + BPagination, + BProgress, + BProgressBar, + createBootstrap, + vBModal, +} from 'bootstrap-vue-next'; + +export function initBootstrapVue(vue: App) { + vue.use(createBootstrap()); + + vue.component('BBadge', BBadge); + vue.component('BDropdownItem', BDropdownItem); + vue.component('BLink', BLink); + vue.component('BAlert', BAlert); + vue.component('BButton', BButton); + vue.component('BNavbar', BNavbar); + vue.component('BNavbarNav', BNavbarNav); + vue.component('BNavbarBrand', BNavbarBrand); + vue.component('BNavbarToggle', BNavbarToggle); + vue.component('BPagination', BPagination); + vue.component('BProgress', BProgress); + vue.component('BProgressBar', BProgressBar); + vue.component('BForm', BForm); + vue.component('BFormInput', BFormInput); + vue.component('BFormGroup', BFormGroup); + vue.component('BFormCheckbox', BFormCheckbox); + vue.component('BCollapse', BCollapse); + vue.component('BNavItem', BNavItem); + vue.component('BNavItemDropdown', BNavItemDropdown); + vue.component('BModal', BModal); + vue.directive('b-modal', vBModal); +} diff --git a/src/main/webapp/app/shared/config/config.ts b/src/main/webapp/app/shared/config/config.ts new file mode 100644 index 0000000..bf16d2c --- /dev/null +++ b/src/main/webapp/app/shared/config/config.ts @@ -0,0 +1,105 @@ +import type { App } from 'vue'; +import { type IntlDateTimeFormats, createI18n } from 'vue-i18n'; + +import { library } from '@fortawesome/fontawesome-svg-core'; +import { faArrowLeft } from '@fortawesome/free-solid-svg-icons/faArrowLeft'; +import { faAsterisk } from '@fortawesome/free-solid-svg-icons/faAsterisk'; +import { faBan } from '@fortawesome/free-solid-svg-icons/faBan'; +import { faBars } from '@fortawesome/free-solid-svg-icons/faBars'; +import { faBell } from '@fortawesome/free-solid-svg-icons/faBell'; +import { faBook } from '@fortawesome/free-solid-svg-icons/faBook'; +import { faCloud } from '@fortawesome/free-solid-svg-icons/faCloud'; +import { faCogs } from '@fortawesome/free-solid-svg-icons/faCogs'; +import { faDatabase } from '@fortawesome/free-solid-svg-icons/faDatabase'; +import { faEye } from '@fortawesome/free-solid-svg-icons/faEye'; +import { faFlag } from '@fortawesome/free-solid-svg-icons/faFlag'; +import { faHeart } from '@fortawesome/free-solid-svg-icons/faHeart'; +import { faHome } from '@fortawesome/free-solid-svg-icons/faHome'; +import { faList } from '@fortawesome/free-solid-svg-icons/faList'; +import { faLock } from '@fortawesome/free-solid-svg-icons/faLock'; +import { faPencilAlt } from '@fortawesome/free-solid-svg-icons/faPencilAlt'; +import { faPlus } from '@fortawesome/free-solid-svg-icons/faPlus'; +import { faRoad } from '@fortawesome/free-solid-svg-icons/faRoad'; +import { faSave } from '@fortawesome/free-solid-svg-icons/faSave'; +import { faSearch } from '@fortawesome/free-solid-svg-icons/faSearch'; +import { faSignInAlt } from '@fortawesome/free-solid-svg-icons/faSignInAlt'; +import { faSignOutAlt } from '@fortawesome/free-solid-svg-icons/faSignOutAlt'; +import { faSort } from '@fortawesome/free-solid-svg-icons/faSort'; +import { faSortDown } from '@fortawesome/free-solid-svg-icons/faSortDown'; +import { faSortUp } from '@fortawesome/free-solid-svg-icons/faSortUp'; +import { faSync } from '@fortawesome/free-solid-svg-icons/faSync'; +import { faTachometerAlt } from '@fortawesome/free-solid-svg-icons/faTachometerAlt'; +import { faTasks } from '@fortawesome/free-solid-svg-icons/faTasks'; +import { faThList } from '@fortawesome/free-solid-svg-icons/faThList'; +import { faTimes } from '@fortawesome/free-solid-svg-icons/faTimes'; +import { faTimesCircle } from '@fortawesome/free-solid-svg-icons/faTimesCircle'; +import { faTrash } from '@fortawesome/free-solid-svg-icons/faTrash'; +import { faUser } from '@fortawesome/free-solid-svg-icons/faUser'; +import { faUserPlus } from '@fortawesome/free-solid-svg-icons/faUserPlus'; +import { faUsers } from '@fortawesome/free-solid-svg-icons/faUsers'; +import { faUsersCog } from '@fortawesome/free-solid-svg-icons/faUsersCog'; +import { faWrench } from '@fortawesome/free-solid-svg-icons/faWrench'; +import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'; + +const datetimeFormats: IntlDateTimeFormats = { + en: { + short: { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric' }, + medium: { year: 'numeric', month: 'short', day: 'numeric', weekday: 'short', hour: 'numeric', minute: 'numeric' }, + long: { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long', hour: 'numeric', minute: 'numeric' }, + }, + // jhipster-needle-i18n-language-date-time-format - JHipster will add/remove format options in this object +}; + +export function initFortAwesome(vue: App) { + vue.component('FontAwesomeIcon', FontAwesomeIcon); + + library.add( + faArrowLeft, + faAsterisk, + faBan, + faBars, + faBell, + faBook, + faCloud, + faCogs, + faDatabase, + faEye, + faFlag, + faHeart, + faHome, + faList, + faLock, + faPencilAlt, + faPlus, + faRoad, + faSave, + faSearch, + faSignInAlt, + faSignOutAlt, + faSort, + faSortDown, + faSortUp, + faSync, + faTachometerAlt, + faTasks, + faThList, + faTimes, + faTimesCircle, + faTrash, + faUser, + faUserPlus, + faUsers, + faUsersCog, + faWrench, + ); +} +export function initI18N(opts: any = {}) { + return createI18n({ + missingWarn: false, + fallbackWarn: false, + legacy: false, + datetimeFormats, + silentTranslationWarn: true, + ...opts, + }); +} diff --git a/src/main/webapp/app/shared/config/dayjs.ts b/src/main/webapp/app/shared/config/dayjs.ts new file mode 100644 index 0000000..3010283 --- /dev/null +++ b/src/main/webapp/app/shared/config/dayjs.ts @@ -0,0 +1,11 @@ +import dayjs from 'dayjs'; +import customParseFormat from 'dayjs/plugin/customParseFormat'; +import duration from 'dayjs/plugin/duration'; +import relativeTime from 'dayjs/plugin/relativeTime'; + +import 'dayjs/locale/en'; +// jhipster-needle-i18n-language-dayjs-imports - JHipster will import languages from dayjs here + +dayjs.extend(customParseFormat); +dayjs.extend(duration); +dayjs.extend(relativeTime); diff --git a/src/main/webapp/app/shared/config/languages.ts b/src/main/webapp/app/shared/config/languages.ts new file mode 100644 index 0000000..598a2d3 --- /dev/null +++ b/src/main/webapp/app/shared/config/languages.ts @@ -0,0 +1,6 @@ +const languages = () => ({ + en: { name: 'English' }, + // jhipster-needle-i18n-language-key-pipe - JHipster will add/remove languages in this object +}); + +export default languages; diff --git a/src/main/webapp/app/shared/config/store/account-store.ts b/src/main/webapp/app/shared/config/store/account-store.ts new file mode 100644 index 0000000..55862bb --- /dev/null +++ b/src/main/webapp/app/shared/config/store/account-store.ts @@ -0,0 +1,59 @@ +import { computed, ref } from 'vue'; + +import { defineStore } from 'pinia'; + +export const useAccountStore = defineStore('main', () => { + const userIdentity = ref(null); + const logon = ref(null); + const profilesLoaded = ref(false); + const activeProfiles = ref(''); + const ribbonOnProfiles = ref(''); + + const account = computed(() => userIdentity.value); + const authenticated = computed(() => !!userIdentity.value); + + function authenticate(promise) { + logon.value = promise; + } + + function setAuthentication(identity) { + userIdentity.value = identity; + logon.value = null; + } + + function logout() { + userIdentity.value = null; + logon.value = null; + } + + function setProfilesLoaded() { + profilesLoaded.value = true; + } + + function setActiveProfiles(profile) { + activeProfiles.value = profile; + } + + function setRibbonOnProfiles(ribbon) { + ribbonOnProfiles.value = ribbon; + } + + return { + // State + userIdentity, + logon, + profilesLoaded, + activeProfiles, + ribbonOnProfiles, + // Getters + account, + authenticated, + // Actions + authenticate, + setAuthentication, + logout, + setProfilesLoaded, + setActiveProfiles, + setRibbonOnProfiles, + }; +}); diff --git a/src/main/webapp/app/shared/config/store/translation-store.ts b/src/main/webapp/app/shared/config/store/translation-store.ts new file mode 100644 index 0000000..8a8555f --- /dev/null +++ b/src/main/webapp/app/shared/config/store/translation-store.ts @@ -0,0 +1,17 @@ +import { defineStore } from 'pinia'; + +interface TranslationState { + currentLanguage: string; +} + +export const useTranslationStore = defineStore('translationStore', { + state: (): TranslationState => ({ + currentLanguage: undefined, + }), + actions: { + setCurrentLanguage(newLanguage) { + this.currentLanguage = newLanguage; + localStorage.setItem('currentLanguage', newLanguage); + }, + }, +}); diff --git a/src/main/webapp/app/shared/data/data-utils.service.spec.ts b/src/main/webapp/app/shared/data/data-utils.service.spec.ts new file mode 100644 index 0000000..1d5dc2b --- /dev/null +++ b/src/main/webapp/app/shared/data/data-utils.service.spec.ts @@ -0,0 +1,120 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { endsWith, paddingSize } from '@/shared/jhipster/data-utils'; + +import useDataUtils from './data-utils.service'; + +describe('DataUtils Service', () => { + let dataUtilsService: ReturnType; + + beforeEach(() => { + dataUtilsService = useDataUtils(); + }); + + it('should not abbreviate text shorter than 30 characters', () => { + const result = dataUtilsService.abbreviate('JHipster JHipster'); + + expect(result).toBe('JHipster JHipster'); + }); + + it('should abbreviate text longer than 30 characters', () => { + const result = dataUtilsService.abbreviate('JHipster JHipster JHipster JHipster JHipster'); + + expect(result).toBe('JHipster JHipst...r JHipster'); + }); + + it('should retrieve byteSize', () => { + const result = dataUtilsService.byteSize('JHipster rocks!'); + + expect(result).toBe('11.25 bytes'); + }); + + it('should clear input entity', () => { + const entity = { field: 'key', value: 'value' }; + dataUtilsService.clearInputImage(entity, null, 'field', 'value', 1); + + expect(entity.field).toBeNull(); + expect(entity.value).toBeNull(); + }); + + it('should open file', () => { + window.open = vi.fn().mockReturnValue({}); + const objectURL = 'blob:http://localhost:9000/xxx'; + URL.createObjectURL = vi.fn().mockImplementationOnce(() => { + return objectURL; + }); + + dataUtilsService.openFile('text', 'data'); + + expect(window.open).toHaveBeenCalledWith(objectURL); + }); + + it('should check text ends with suffix', () => { + const result = endsWith('rocky', 'JHipster rocks!'); + + expect(result).toBe(false); + }); + + it('should paddingSize to 0', () => { + const result = paddingSize('toto'); + + expect(result).toBe(0); + }); + + it('should paddingSize to 1', () => { + const result = paddingSize('toto='); + + expect(result).toBe(1); + }); + + it('should paddingSize to 2', () => { + const result = paddingSize('toto=='); + + expect(result).toBe(2); + }); + + it('should parse links', () => { + const result = dataUtilsService.parseLinks( + '; rel="next",; rel="last",; rel="first"', + ); + + expect(result.last).toBe(2); + }); + + it('should return empty JSON object for empty string', () => { + const result = dataUtilsService.parseLinks(''); + + expect(result).toStrictEqual({}); + }); + + it('should return empty JSON object for text with no link header', () => { + const result = dataUtilsService.parseLinks('JHipster rocks!'); + + expect(result).toStrictEqual({}); + }); + + it('should return empty JSON object for text without >;', () => { + const result = dataUtilsService.parseLinks( + ' rel="next", rel="last", rel="first"', + ); + + expect(result).toStrictEqual({}); + }); + + it('should return empty JSON object for text with no comma separated link header', () => { + const result = dataUtilsService.parseLinks( + '; rel="next"; rel="last"; rel="first"', + ); + + expect(result).toStrictEqual({}); + }); +}); diff --git a/src/main/webapp/app/shared/data/data-utils.service.ts b/src/main/webapp/app/shared/data/data-utils.service.ts new file mode 100644 index 0000000..e7bfefd --- /dev/null +++ b/src/main/webapp/app/shared/data/data-utils.service.ts @@ -0,0 +1,94 @@ +import { byteSize, openFile, toBase64 } from '@/shared/jhipster/data-utils'; +import { getPageNumberFromLinkHeader } from '@/shared/jhipster/link-header'; + +/** + * A composable utility for data. + */ +const useDataUtils = () => ({ + /** + * Method to abbreviate the text given + */ + abbreviate(text, append = '...') { + if (text.length < 30) { + return text; + } + return text ? text.substring(0, 15) + append + text.slice(-10) : ''; + }, + + /** + * Method to find the byte size of the string provides + */ + byteSize(base64String) { + return byteSize(base64String); + }, + + /** + * Method to open file + */ + openFile(contentType, data) { + openFile(data, contentType); + }, + + /** + * Method to clear the input + */ + clearInputImage(entity, elementRef, field, fieldContentType, idInput) { + if (entity && field && fieldContentType) { + if (Object.hasOwn(entity, field)) { + entity[field] = null; + } + if (Object.hasOwn(entity, fieldContentType)) { + entity[fieldContentType] = null; + } + if (elementRef && idInput && elementRef.nativeElement.querySelector(`#${idInput}`)) { + elementRef.nativeElement.querySelector(`#${idInput}`).value = null; + } + } + }, + + setFileData(event, entity, field, isImage) { + if (event?.target.files?.[0]) { + const file = event.target.files[0]; + if (isImage && !file.type.startsWith('image/')) { + return; + } + toBase64(file, base64Data => { + entity[field] = base64Data; + entity[`${field}ContentType`] = file.type; + }); + } + }, + + /** + * Method to download file + */ + downloadFile(contentType, data, fileName) { + const byteCharacters = atob(data); + const byteNumbers = new Array(byteCharacters.length); + for (let i = 0; i < byteCharacters.length; i++) { + byteNumbers[i] = byteCharacters.charCodeAt(i); + } + const byteArray = new Uint8Array(byteNumbers); + const blob = new Blob([byteArray], { + type: contentType, + }); + const tempLink = document.createElement('a'); + tempLink.href = window.URL.createObjectURL(blob); + tempLink.download = fileName; + tempLink.target = '_blank'; + tempLink.click(); + }, + + /** + * Method to parse header links + */ + parseLinks(header) { + try { + return getPageNumberFromLinkHeader(header); + } catch { + return {}; + } + }, +}); + +export default useDataUtils; diff --git a/src/main/webapp/app/shared/jhi-item-count.component.ts b/src/main/webapp/app/shared/jhi-item-count.component.ts new file mode 100644 index 0000000..aa423ca --- /dev/null +++ b/src/main/webapp/app/shared/jhi-item-count.component.ts @@ -0,0 +1,29 @@ +import { computed, defineComponent } from 'vue'; +import { useI18n } from 'vue-i18n'; + +export default defineComponent({ + props: { + page: { + type: Number, + default: 1, + }, + total: { + type: Number, + default: 0, + }, + itemsPerPage: { + type: Number, + default: 20, + }, + }, + setup(props) { + const first = computed(() => ((props.page - 1) * props.itemsPerPage === 0 ? 1 : (props.page - 1) * props.itemsPerPage + 1)); + const second = computed(() => Math.min(props.page * props.itemsPerPage, props.total)); + + return { + first, + second, + t$: useI18n().t, + }; + }, +}); diff --git a/src/main/webapp/app/shared/jhi-item-count.vue b/src/main/webapp/app/shared/jhi-item-count.vue new file mode 100644 index 0000000..7b8b9a0 --- /dev/null +++ b/src/main/webapp/app/shared/jhi-item-count.vue @@ -0,0 +1,7 @@ + + + diff --git a/src/main/webapp/app/shared/jhipster/constants.ts b/src/main/webapp/app/shared/jhipster/constants.ts new file mode 100644 index 0000000..6ad5071 --- /dev/null +++ b/src/main/webapp/app/shared/jhipster/constants.ts @@ -0,0 +1,10 @@ +export const MESSAGE_ALERT_HEADER_NAME = 'x-questionbankapp-alert'; +export const MESSAGE_ERROR_HEADER_NAME = 'x-questionbankapp-error'; +export const MESSAGE_PARAM_HEADER_NAME = 'x-questionbankapp-params'; + +export const AUTHENTICATION_TOKEN_KEY = 'jhi-authenticationToken'; + +export enum Authority { + ADMIN = 'ROLE_ADMIN', + USER = 'ROLE_USER', +} diff --git a/src/main/webapp/app/shared/jhipster/data-utils.ts b/src/main/webapp/app/shared/jhipster/data-utils.ts new file mode 100644 index 0000000..e7530d4 --- /dev/null +++ b/src/main/webapp/app/shared/jhipster/data-utils.ts @@ -0,0 +1,47 @@ +const formatAsBytes = (size: number): string => `${size.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ')} bytes`; // NOSONAR + +export const endsWith = (suffix: string, str: string): boolean => str.includes(suffix, str.length - suffix.length); + +export const paddingSize = (value: string): number => { + if (endsWith('==', value)) { + return 2; + } + if (endsWith('=', value)) { + return 1; + } + return 0; +}; + +const size = (value: string): number => (value.length / 4) * 3 - paddingSize(value); + +export const toBase64 = (file: File, callback: (base64Data: string) => void): void => { + const fileReader: FileReader = new FileReader(); + fileReader.onload = (e: ProgressEvent) => { + if (typeof e.target?.result === 'string') { + const base64Data: string = e.target.result.substring(e.target.result.indexOf('base64,') + 'base64,'.length); + callback(base64Data); + } + }; + fileReader.readAsDataURL(file); +}; + +export const openFile = (data: string, contentType: string | null | undefined): void => { + contentType ??= ''; + + const byteCharacters = atob(data); + const byteNumbers = new Array(byteCharacters.length); + for (let i = 0; i < byteCharacters.length; i++) { + byteNumbers[i] = byteCharacters.codePointAt(i); + } + const byteArray = new Uint8Array(byteNumbers); + const blob = new Blob([byteArray], { + type: contentType, + }); + const fileURL = globalThis.URL.createObjectURL(blob); + const win = globalThis.open(fileURL); + if (win) { + win.onload = () => URL.revokeObjectURL(fileURL); + } +}; + +export const byteSize = (base64String: string): string => formatAsBytes(size(base64String)); diff --git a/src/main/webapp/app/shared/jhipster/error.constants.ts b/src/main/webapp/app/shared/jhipster/error.constants.ts new file mode 100644 index 0000000..e335293 --- /dev/null +++ b/src/main/webapp/app/shared/jhipster/error.constants.ts @@ -0,0 +1,4 @@ +export const PROBLEM_BASE_URL = 'https://www.jhipster.tech/problem'; +export const EMAIL_ALREADY_USED_TYPE = `${PROBLEM_BASE_URL}/email-already-used`; +export const LOGIN_ALREADY_USED_TYPE = `${PROBLEM_BASE_URL}/login-already-used`; +export const INVALID_PASSWORD_TYPE = `${PROBLEM_BASE_URL}/invalid-password`; diff --git a/src/main/webapp/app/shared/jhipster/headers.ts b/src/main/webapp/app/shared/jhipster/headers.ts new file mode 100644 index 0000000..8fb5572 --- /dev/null +++ b/src/main/webapp/app/shared/jhipster/headers.ts @@ -0,0 +1,62 @@ +import { MESSAGE_ALERT_HEADER_NAME, MESSAGE_ERROR_HEADER_NAME, MESSAGE_PARAM_HEADER_NAME } from './constants'; + +export type HeaderMessage = { + /** Success translation key or message */ + alert?: string; + /** Success translation key */ + alertKey?: string; + /** Success message */ + alertMessage?: string; + + /** Error translation key or message */ + error?: string; + /** Error translation key */ + errorKey?: string; + /** Error message */ + errorMessage?: string; + /** Entity id for success messages. Entity name for error messages. */ + param?: string; +}; + +const headerToString = (headerValue: any): string | undefined => { + if (headerValue === undefined) { + return undefined; + } + if (Array.isArray(headerValue)) { + if (headerValue.length > 1) { + throw new TypeError('Multiple header values found'); + } + headerValue = headerValue[0]; + } + if (typeof headerValue !== 'string') { + throw new TypeError('Header value is not a string'); + } + return headerValue; +}; + +const decodeHeaderValue = (headerValue?: string): string | undefined => + headerValue ? decodeURIComponent(headerValue.replaceAll('+', ' ')) : headerValue; + +export const getMessageFromHeaders = (headers: Record): HeaderMessage => { + const alertHeader = headerToString(headers[MESSAGE_ALERT_HEADER_NAME]); + // Try to determine if the alertHeader is a key or a message + const alertIsKey = /^[A-Za-z0-9](?:[A-Za-z0-9.]*[A-Za-z0-9])?$/.test(alertHeader ?? ''); + const alertKey = alertIsKey ? alertHeader : undefined; + const alertMessage = alertIsKey ? undefined : alertHeader; + + const errorHeader = headerToString(headers[MESSAGE_ERROR_HEADER_NAME]); + // Try to determine if the errorHeader is a key or a message + const errorIsKey = /^[A-Za-z0-9](?:[A-Za-z0-9.]*[A-Za-z0-9])?$/.test(errorHeader ?? ''); + const errorKey = errorIsKey ? errorHeader : undefined; + const errorMessage = errorIsKey ? undefined : errorHeader; + + return { + alert: alertHeader, + alertKey, + alertMessage, + error: errorHeader, + errorKey, + errorMessage, + param: decodeHeaderValue(headerToString(headers[MESSAGE_PARAM_HEADER_NAME])), + }; +}; diff --git a/src/main/webapp/app/shared/jhipster/link-header.ts b/src/main/webapp/app/shared/jhipster/link-header.ts new file mode 100644 index 0000000..f4b49e4 --- /dev/null +++ b/src/main/webapp/app/shared/jhipster/link-header.ts @@ -0,0 +1,55 @@ +/** + * Method to parse the link header into an object + * @example + * link: ; rel="last",; rel="first" + * will return { last: { page: '0', size: '20' }, first: { page: '0', size: '20' } } + */ +export function parseLinkHeader(header: string): Record | undefined> { + if (header.length === 0) { + throw new Error('input must not be of zero length'); + } + + // Split parts by comma + const parts: string[] = header.split(','); + + // Parse each part into a named link + return Object.fromEntries( + parts.map(p => { + const section: string[] = p.split(';'); + + if (section.length !== 2) { + throw new Error('section could not be split on ";"'); + } + + const url: string = section[0].replace(/<(.*)>/, '$1').trim(); // NOSONAR + const queryString: Record = {}; + + url.replaceAll(/([^?=&]+)(=([^&]*))?/g, (_$0: string, $1: string | undefined, _$2: string | undefined, $3: string | undefined) => { + if ($1 !== undefined && $3 !== undefined) { + queryString[$1] = decodeURIComponent($3); + } + return $3 ?? ''; + }); + + const name: string = section[1].replace(/rel="(.*)"/, '$1').trim(); + return [name, queryString]; + }), + ); +} + +/** + * Method to parse the link header + * @example + * link: ; rel="last",; rel="first" + * will return { last: 0, first: 0 } + */ +export function getPageNumberFromLinkHeader(header: string): Record { + const sections = parseLinkHeader(header); + const pages: Record = {}; + for (const [name, queryParams] of Object.entries(sections)) { + if (queryParams?.page !== undefined) { + pages[name] = Number.parseInt(queryParams.page, 10); + } + } + return pages; +} diff --git a/src/main/webapp/app/shared/jhipster/problem-details.ts b/src/main/webapp/app/shared/jhipster/problem-details.ts new file mode 100644 index 0000000..06bb5c2 --- /dev/null +++ b/src/main/webapp/app/shared/jhipster/problem-details.ts @@ -0,0 +1,35 @@ +/** + * Problem details defined in RFC 7807. + * @see https://datatracker.ietf.org/doc/html/rfc7807#section-3.1 + */ +export type ProblemDetails = { + /** A URI reference that identifies the problem type */ + type: string; + /** A short, human-readable summary of the problem type */ + title: string; + /** The HTTP status code */ + status: number; + /** A human-readable explanation specific to this occurrence of the problem */ + detail: string; + /** A URI reference that identifies the specific occurrence of the problem */ + instance: string; +}; + +export const ProblemWithMessageType = 'https://www.jhipster.tech/problem/problem-with-message'; + +export type FieldErrorVM = { message: string; objectName: string; field: string }; + +export type ProblemWithMessage = ProblemDetails & { + type: typeof ProblemWithMessageType; + + /** Translation message key */ + message?: string; + /** Translation message parameter */ + params?: string; + /** Request path */ + path?: string; + /** Field errors */ + fieldErrors?: FieldErrorVM[]; +}; + +export const isProblemWithMessage = (data: any): data is ProblemWithMessage => data?.type === ProblemWithMessageType; diff --git a/src/main/webapp/app/shared/model/user.model.ts b/src/main/webapp/app/shared/model/user.model.ts new file mode 100644 index 0000000..e7a786f --- /dev/null +++ b/src/main/webapp/app/shared/model/user.model.ts @@ -0,0 +1,33 @@ +export interface IUser { + id?: any; + login?: string; + firstName?: string; + lastName?: string; + email?: string; + activated?: boolean; + langKey?: string; + authorities?: any[]; + createdBy?: string; + createdDate?: Date; + lastModifiedBy?: string; + lastModifiedDate?: Date; + password?: string; +} + +export class User implements IUser { + constructor( + public id?: any, + public login?: string, + public firstName?: string, + public lastName?: string, + public email?: string, + public activated?: boolean, + public langKey?: string, + public authorities?: any[], + public createdBy?: string, + public createdDate?: Date, + public lastModifiedBy?: string, + public lastModifiedDate?: Date, + public password?: string, + ) {} +} diff --git a/src/main/webapp/app/shared/sort/jhi-sort-indicator.component.ts b/src/main/webapp/app/shared/sort/jhi-sort-indicator.component.ts new file mode 100644 index 0000000..59994d3 --- /dev/null +++ b/src/main/webapp/app/shared/sort/jhi-sort-indicator.component.ts @@ -0,0 +1,16 @@ +import { defineComponent } from 'vue'; + +export default defineComponent({ + name: 'JhiSortIndicatorComponent', + props: { + currentOrder: { + type: String, + default: '', + }, + fieldName: { + type: String, + default: '', + }, + reverse: Boolean, + }, +}); diff --git a/src/main/webapp/app/shared/sort/jhi-sort-indicator.vue b/src/main/webapp/app/shared/sort/jhi-sort-indicator.vue new file mode 100644 index 0000000..b136dd4 --- /dev/null +++ b/src/main/webapp/app/shared/sort/jhi-sort-indicator.vue @@ -0,0 +1,5 @@ + + + diff --git a/src/main/webapp/app/shared/sort/sorts.spec.ts b/src/main/webapp/app/shared/sort/sorts.spec.ts new file mode 100644 index 0000000..bfdf676 --- /dev/null +++ b/src/main/webapp/app/shared/sort/sorts.spec.ts @@ -0,0 +1,11 @@ +import { describe, expect, it } from 'vitest'; + +import buildPaginationQueryOpts from './sorts'; + +describe('Sort', () => { + it('should return an empty string if there is no pagination', () => { + const result = buildPaginationQueryOpts(undefined); + + expect(result).toBe(''); + }); +}); diff --git a/src/main/webapp/app/shared/sort/sorts.ts b/src/main/webapp/app/shared/sort/sorts.ts new file mode 100644 index 0000000..0753c7f --- /dev/null +++ b/src/main/webapp/app/shared/sort/sorts.ts @@ -0,0 +1,13 @@ +export default function buildPaginationQueryOpts(paginationQuery) { + if (paginationQuery) { + return Object.entries(paginationQuery) + .map(([paramName, paramValue]) => { + if (Array.isArray(paramValue)) { + return paramValue.map(eachValue => `${paramName}=${eachValue}`).join('&'); + } + return `${paramName}=${paramValue}`; + }) + .join('&'); + } + return ''; +} diff --git a/src/main/webapp/app/shims-vue.d.ts b/src/main/webapp/app/shims-vue.d.ts new file mode 100644 index 0000000..5e264cc --- /dev/null +++ b/src/main/webapp/app/shims-vue.d.ts @@ -0,0 +1,5 @@ +declare module '*.vue' { + import { type DefineComponent } from 'vue'; + const component: DefineComponent & any; + export default component; +} diff --git a/src/main/webapp/app/store.ts b/src/main/webapp/app/store.ts new file mode 100644 index 0000000..2c584eb --- /dev/null +++ b/src/main/webapp/app/store.ts @@ -0,0 +1,5 @@ +import { useAccountStore as useStore } from '@/shared/config/store/account-store'; +export type AccountStore = ReturnType; +export { useStore }; + +export { useTranslationStore } from '@/shared/config/store/translation-store'; diff --git a/src/main/webapp/app/test-setup.ts b/src/main/webapp/app/test-setup.ts new file mode 100644 index 0000000..1e07607 --- /dev/null +++ b/src/main/webapp/app/test-setup.ts @@ -0,0 +1,22 @@ +import { beforeAll } from 'vitest'; +import { createI18n } from 'vue-i18n'; + +import { config } from '@vue/test-utils'; +import axios from 'axios'; + +beforeAll(() => { + globalThis.location.href = 'https://jhipster.tech/'; + + // Make sure axios is never executed. + axios.interceptors.request.use(request => { + throw new Error(`Error axios should be mocked ${request.url}`); + }); + + config.global.plugins.push( + createI18n({ + legacy: false, + missingWarn: false, + fallbackWarn: false, + }), + ); +}); diff --git a/src/main/webapp/content/css/loading.css b/src/main/webapp/content/css/loading.css new file mode 100644 index 0000000..fa99866 --- /dev/null +++ b/src/main/webapp/content/css/loading.css @@ -0,0 +1,152 @@ +@keyframes lds-pacman-1 { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + 50% { + -webkit-transform: rotate(-45deg); + transform: rotate(-45deg); + } + 100% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } +} +@-webkit-keyframes lds-pacman-1 { + 0% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } + 50% { + -webkit-transform: rotate(-45deg); + transform: rotate(-45deg); + } + 100% { + -webkit-transform: rotate(0deg); + transform: rotate(0deg); + } +} +@keyframes lds-pacman-2 { + 0% { + -webkit-transform: rotate(180deg); + transform: rotate(180deg); + } + 50% { + -webkit-transform: rotate(225deg); + transform: rotate(225deg); + } + 100% { + -webkit-transform: rotate(180deg); + transform: rotate(180deg); + } +} +@-webkit-keyframes lds-pacman-2 { + 0% { + -webkit-transform: rotate(180deg); + transform: rotate(180deg); + } + 50% { + -webkit-transform: rotate(225deg); + transform: rotate(225deg); + } + 100% { + -webkit-transform: rotate(180deg); + transform: rotate(180deg); + } +} +@keyframes lds-pacman-3 { + 0% { + -webkit-transform: translate(190px, 0); + transform: translate(190px, 0); + opacity: 0; + } + 20% { + opacity: 1; + } + 100% { + -webkit-transform: translate(70px, 0); + transform: translate(70px, 0); + opacity: 1; + } +} +@-webkit-keyframes lds-pacman-3 { + 0% { + -webkit-transform: translate(190px, 0); + transform: translate(190px, 0); + opacity: 0; + } + 20% { + opacity: 1; + } + 100% { + -webkit-transform: translate(70px, 0); + transform: translate(70px, 0); + opacity: 1; + } +} + +.app-loading { + font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; + position: relative; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + top: 10em; +} +.app-loading p { + display: block; + font-size: 1.17em; + margin-inline-start: 0; + margin-inline-end: 0; + font-weight: normal; +} + +.app-loading .lds-pacman { + position: relative; + margin: auto; + width: 200px !important; + height: 200px !important; + -webkit-transform: translate(-100px, -100px) scale(1) translate(100px, 100px); + transform: translate(-100px, -100px) scale(1) translate(100px, 100px); +} +.app-loading .lds-pacman > div:nth-child(2) div { + position: absolute; + top: 40px; + left: 40px; + width: 120px; + height: 60px; + border-radius: 120px 120px 0 0; + background: #bbcedd; + -webkit-animation: lds-pacman-1 1s linear infinite; + animation: lds-pacman-1 1s linear infinite; + -webkit-transform-origin: 60px 60px; + transform-origin: 60px 60px; +} +.app-loading .lds-pacman > div:nth-child(2) div:nth-child(2) { + -webkit-animation: lds-pacman-2 1s linear infinite; + animation: lds-pacman-2 1s linear infinite; +} +.app-loading .lds-pacman > div:nth-child(1) div { + position: absolute; + top: 97px; + left: -8px; + width: 24px; + height: 10px; + background-image: url('/content/images/logo-jhipster.png'); + background-size: contain; + -webkit-animation: lds-pacman-3 1s linear infinite; + animation: lds-pacman-3 1.5s linear infinite; +} +.app-loading .lds-pacman > div:nth-child(1) div:nth-child(1) { + -webkit-animation-delay: -0.67s; + animation-delay: -1s; +} +.app-loading .lds-pacman > div:nth-child(1) div:nth-child(2) { + -webkit-animation-delay: -0.33s; + animation-delay: -0.5s; +} +.app-loading .lds-pacman > div:nth-child(1) div:nth-child(3) { + -webkit-animation-delay: 0s; + animation-delay: 0s; +} diff --git a/src/main/webapp/content/images/jhipster_family_member_0.svg b/src/main/webapp/content/images/jhipster_family_member_0.svg new file mode 100644 index 0000000..d6df83c --- /dev/null +++ b/src/main/webapp/content/images/jhipster_family_member_0.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/main/webapp/content/images/jhipster_family_member_0_head-192.png b/src/main/webapp/content/images/jhipster_family_member_0_head-192.png new file mode 100644 index 0000000..6d90ab3 Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_0_head-192.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_0_head-256.png b/src/main/webapp/content/images/jhipster_family_member_0_head-256.png new file mode 100644 index 0000000..8e99bfe Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_0_head-256.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_0_head-384.png b/src/main/webapp/content/images/jhipster_family_member_0_head-384.png new file mode 100644 index 0000000..c7ca460 Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_0_head-384.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_0_head-512.png b/src/main/webapp/content/images/jhipster_family_member_0_head-512.png new file mode 100644 index 0000000..7e0b843 Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_0_head-512.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_1.svg b/src/main/webapp/content/images/jhipster_family_member_1.svg new file mode 100644 index 0000000..e3a0f3d --- /dev/null +++ b/src/main/webapp/content/images/jhipster_family_member_1.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/main/webapp/content/images/jhipster_family_member_1_head-192.png b/src/main/webapp/content/images/jhipster_family_member_1_head-192.png new file mode 100644 index 0000000..ac5f2a0 Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_1_head-192.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_1_head-256.png b/src/main/webapp/content/images/jhipster_family_member_1_head-256.png new file mode 100644 index 0000000..443822e Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_1_head-256.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_1_head-384.png b/src/main/webapp/content/images/jhipster_family_member_1_head-384.png new file mode 100644 index 0000000..4a5e9fe Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_1_head-384.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_1_head-512.png b/src/main/webapp/content/images/jhipster_family_member_1_head-512.png new file mode 100644 index 0000000..66c625c Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_1_head-512.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_2.svg b/src/main/webapp/content/images/jhipster_family_member_2.svg new file mode 100644 index 0000000..51c6a5a --- /dev/null +++ b/src/main/webapp/content/images/jhipster_family_member_2.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/main/webapp/content/images/jhipster_family_member_2_head-192.png b/src/main/webapp/content/images/jhipster_family_member_2_head-192.png new file mode 100644 index 0000000..24baf78 Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_2_head-192.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_2_head-256.png b/src/main/webapp/content/images/jhipster_family_member_2_head-256.png new file mode 100644 index 0000000..7b25f52 Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_2_head-256.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_2_head-384.png b/src/main/webapp/content/images/jhipster_family_member_2_head-384.png new file mode 100644 index 0000000..e89e120 Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_2_head-384.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_2_head-512.png b/src/main/webapp/content/images/jhipster_family_member_2_head-512.png new file mode 100644 index 0000000..3c0e6cb Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_2_head-512.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_3.svg b/src/main/webapp/content/images/jhipster_family_member_3.svg new file mode 100644 index 0000000..cc0d01f --- /dev/null +++ b/src/main/webapp/content/images/jhipster_family_member_3.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/main/webapp/content/images/jhipster_family_member_3_head-192.png b/src/main/webapp/content/images/jhipster_family_member_3_head-192.png new file mode 100644 index 0000000..b1e4fb3 Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_3_head-192.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_3_head-256.png b/src/main/webapp/content/images/jhipster_family_member_3_head-256.png new file mode 100644 index 0000000..aa058c7 Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_3_head-256.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_3_head-384.png b/src/main/webapp/content/images/jhipster_family_member_3_head-384.png new file mode 100644 index 0000000..1d10bd5 Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_3_head-384.png differ diff --git a/src/main/webapp/content/images/jhipster_family_member_3_head-512.png b/src/main/webapp/content/images/jhipster_family_member_3_head-512.png new file mode 100644 index 0000000..e719f1d Binary files /dev/null and b/src/main/webapp/content/images/jhipster_family_member_3_head-512.png differ diff --git a/src/main/webapp/content/images/logo-jhipster.png b/src/main/webapp/content/images/logo-jhipster.png new file mode 100644 index 0000000..6a005bf Binary files /dev/null and b/src/main/webapp/content/images/logo-jhipster.png differ diff --git a/src/main/webapp/content/scss/_bootstrap-variables.scss b/src/main/webapp/content/scss/_bootstrap-variables.scss new file mode 100644 index 0000000..fb0b6f9 --- /dev/null +++ b/src/main/webapp/content/scss/_bootstrap-variables.scss @@ -0,0 +1,36 @@ +/* + * Bootstrap overrides https://getbootstrap.com/docs/5.1/customize/sass/ + * All values defined in bootstrap source + * https://github.com/twbs/bootstrap/blob/v5.1.3/scss/_variables.scss can be overwritten here + * Make sure not to add !default to values here + */ + +// Options: +// Quickly modify global styling by enabling or disabling optional features. +$enable-rounded: true; +$enable-shadows: false; +$enable-gradients: false; +$enable-transitions: true; +$enable-hover-media-query: false; +$enable-grid-classes: true; +$enable-print-styles: true; + +// Components: +// Define common padding and border radius sizes and more. + +$border-radius: 0.15rem; +$border-radius-lg: 0.125rem; +$border-radius-sm: 0.1rem; + +// Body: +// Settings for the `` element. + +$body-bg: #ffffff; + +// Typography: +// Font, line-height, and color for body text, headings, and more. + +$font-size-base: 1rem; + +$dropdown-link-hover-color: white; +$dropdown-link-hover-bg: #343a40; diff --git a/src/main/webapp/content/scss/global.scss b/src/main/webapp/content/scss/global.scss new file mode 100644 index 0000000..97e1fd9 --- /dev/null +++ b/src/main/webapp/content/scss/global.scss @@ -0,0 +1,288 @@ +@import 'bootstrap-variables'; +@import 'bootstrap/scss/functions'; +@import 'bootstrap/scss/variables'; +// Import Bootstrap source files from node_modules +@import 'bootstrap/scss/bootstrap'; +@import 'bootstrap-vue-next/dist/bootstrap-vue-next.css'; + +/* Up to bootstrap-vue-next 0.45 the orchestrator mapped a toast position such as `top-end` to the +Bootstrap utilities `top-0 end-0`. Since 0.46 it sets the raw position as the container class, and no +stylesheet defines it, so toast containers are left unpositioned. Drop this once upstream maps them again. */ +.toast-container { + &.top-start { + top: 0; + left: 0; + } + &.top-center { + top: 0; + left: 50%; + transform: translateX(-50%); + } + &.top-end { + top: 0; + right: 0; + } + &.middle-start { + top: 50%; + left: 0; + transform: translateY(-50%); + } + &.middle-center { + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + } + &.middle-end { + top: 50%; + right: 0; + transform: translateY(-50%); + } + &.bottom-start { + bottom: 0; + left: 0; + } + &.bottom-center { + bottom: 0; + left: 50%; + transform: translateX(-50%); + } + &.bottom-end { + bottom: 0; + right: 0; + } +} + +/* ============================================================== +Bootstrap tweaks +===============================================================*/ + +body, +h1, +h2, +h3, +h4 { + font-weight: 300; +} + +/* Increase contrast of links to get 100% on Lighthouse Accessibility Audit. Override this color if you want to change the link color, or use a Bootswatch theme */ +a { + color: #533f03; + font-weight: bold; +} + +/* override hover color for dropdown-item forced by bootstrap to all a:not([href]):not([tabindex]) elements in _reboot.scss */ +a:not([href]):not([tabindex]):hover.dropdown-item { + color: $dropdown-link-hover-color; +} + +/* override .dropdown-item.active background-color on hover */ +.dropdown-item.active:hover { + background-color: mix($dropdown-link-hover-bg, $dropdown-link-active-bg, 50%); +} + +a:hover { + color: #533f03; + /* make sure browsers use the pointer cursor for anchors, even with no href */ + cursor: pointer; +} + +.dropdown-item:hover { + color: $dropdown-link-hover-color; +} + +/* ========================================================================== +Browser Upgrade Prompt +========================================================================== */ +.browserupgrade { + margin: 0.2em 0; + background: #ccc; + color: #000; + padding: 0.2em 0; +} + +/* ========================================================================== +Main page styles +========================================================================== */ + +.hipster.img-fluid { + display: inline-block; + width: 347px; + height: 497px; + background: url('/content/images/jhipster_family_member_2.svg') no-repeat center top; + background-size: contain; +} + +/* wait autoprefixer update to allow simple generation of high pixel density media query */ +@media only screen and (-webkit-min-device-pixel-ratio: 2), + only screen and (min--moz-device-pixel-ratio: 2), + only screen and (-o-min-device-pixel-ratio: 2/1), + only screen and (min-device-pixel-ratio: 2), + only screen and (min-resolution: 192dpi), + only screen and (min-resolution: 2dppx) { + .hipster { + background: url('/content/images/jhipster_family_member_2.svg') no-repeat center top; + background-size: contain; + } +} + +/* ========================================================================== +Generic styles +========================================================================== */ +.jh-card { + padding: 1.5%; + margin-top: 20px; + border: none; +} + +.error { + color: white; + background-color: red; +} + +.pad { + padding: 10px; +} + +.w-40 { + width: 40% !important; +} + +.w-60 { + width: 60% !important; +} + +.break { + white-space: normal; + word-break: break-all; +} + +.form-control { + background-color: #fff; +} + +.readonly { + background-color: #eee; + opacity: 1; +} + +.footer { + border-top: 1px solid rgba(0, 0, 0, 0.125); +} + +.hand, +[jhisortby] { + cursor: pointer; +} + +/* ========================================================================== +Custom alerts for notification +========================================================================== */ +.alerts { + .alert { + text-overflow: ellipsis; + pre { + background: none; + border: none; + font: inherit; + color: inherit; + padding: 0; + margin: 0; + } + .popover pre { + font-size: 10px; + } + } + .jhi-toast { + position: fixed; + width: 100%; + &.left { + left: 5px; + } + &.right { + right: 5px; + } + &.top { + top: 55px; + } + &.bottom { + bottom: 55px; + } + } +} + +@media screen and (min-width: 480px) { + .alerts .jhi-toast { + width: 50%; + } +} + +/* ========================================================================== +entity list page css +========================================================================== */ + +.table-entities thead th .d-flex > * { + margin: auto 0; +} + +/* ========================================================================== +entity detail page css +========================================================================== */ +.row-md.jh-entity-details { + display: grid; + grid-template-columns: auto 1fr; + column-gap: 10px; + line-height: 1.5; +} + +@media screen and (min-width: 768px) { + .row-md.jh-entity-details > { + dt { + float: left; + overflow: hidden; + clear: left; + text-align: right; + text-overflow: ellipsis; + white-space: nowrap; + padding: 0.5em 0; + } + dd { + border-bottom: 1px solid #eee; + padding: 0.5em 0; + margin-left: 0; + } + } +} + +/* ========================================================================== +ui bootstrap tweaks +========================================================================== */ +.nav, +.pagination, +.carousel, +.panel-title a { + cursor: pointer; +} + +.thread-dump-modal-lock { + max-width: 450px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.dropdown-menu { + padding-left: 0; +} + +// Add space between icon and text in dropdowns +.dropdown-menu svg:first-child, +.btn svg:first-child, +.nav-item span svg:first-child { + margin-right: 0.4em; +} + +th svg:last-child { + margin-left: 0.4em; +} + +/* jhipster-needle-scss-add-main JHipster will add new css style */ diff --git a/src/main/webapp/content/scss/vendor.scss b/src/main/webapp/content/scss/vendor.scss new file mode 100644 index 0000000..25e7e88 --- /dev/null +++ b/src/main/webapp/content/scss/vendor.scss @@ -0,0 +1,8 @@ +/* after changing this file run 'npm run webapp:build' */ + +/*************************** +put Sass variables here: +eg $input-color: red; +****************************/ + +/* jhipster-needle-scss-add-vendor JHipster will add new css style */ diff --git a/src/main/webapp/favicon.ico b/src/main/webapp/favicon.ico new file mode 100644 index 0000000..4179874 Binary files /dev/null and b/src/main/webapp/favicon.ico differ diff --git a/src/main/webapp/i18n/en/activate.json b/src/main/webapp/i18n/en/activate.json new file mode 100644 index 0000000..058bd49 --- /dev/null +++ b/src/main/webapp/i18n/en/activate.json @@ -0,0 +1,9 @@ +{ + "activate": { + "title": "Activation", + "messages": { + "success": "Your user account has been activated. Please ", + "error": "Your user could not be activated. Please use the registration form to sign up." + } + } +} diff --git a/src/main/webapp/i18n/en/configuration.json b/src/main/webapp/i18n/en/configuration.json new file mode 100644 index 0000000..09c9a1a --- /dev/null +++ b/src/main/webapp/i18n/en/configuration.json @@ -0,0 +1,10 @@ +{ + "configuration": { + "title": "Configuration", + "filter": "Filter (by prefix)", + "table": { + "prefix": "Prefix", + "properties": "Properties" + } + } +} diff --git a/src/main/webapp/i18n/en/en.js b/src/main/webapp/i18n/en/en.js new file mode 100644 index 0000000..77f1471 --- /dev/null +++ b/src/main/webapp/i18n/en/en.js @@ -0,0 +1,3 @@ +import { all } from 'deepmerge'; + +export default all(Object.values(import.meta.glob('./*.json', { import: 'default', eager: true }))); diff --git a/src/main/webapp/i18n/en/error.json b/src/main/webapp/i18n/en/error.json new file mode 100644 index 0000000..d257563 --- /dev/null +++ b/src/main/webapp/i18n/en/error.json @@ -0,0 +1,14 @@ +{ + "error": { + "title": "Error page!", + "http": { + "400": "Bad request.", + "403": "You are not authorized to access this page.", + "404": "The page does not exist.", + "405": "The HTTP verb you used is not supported for this URL.", + "500": "Internal server error." + }, + "concurrencyFailure": "Another user modified this data at the same time as you. Your changes were rejected.", + "validation": "Validation error on the server." + } +} diff --git a/src/main/webapp/i18n/en/global.json b/src/main/webapp/i18n/en/global.json new file mode 100644 index 0000000..cba121e --- /dev/null +++ b/src/main/webapp/i18n/en/global.json @@ -0,0 +1,147 @@ +{ + "global": { + "title": "QuestionBank", + "browsehappy": "You are using an outdated browser. Please upgrade your browser to improve your experience.", + "menu": { + "home": "Home", + "jhipster-needle-menu-add-element": "JHipster will add additional menu entries here (do not translate!)", + "entities": { + "main": "Entities", + "jhipster-needle-menu-add-entry": "JHipster will add additional entities here (do not translate!)" + }, + "account": { + "main": "Account", + "settings": "Settings", + "password": "Password", + "sessions": "Sessions", + "login": "Sign in", + "logout": "Sign out", + "register": "Register" + }, + "admin": { + "main": "Administration", + "userManagement": "User management", + "tracker": "User tracker", + "metrics": "Metrics", + "health": "Health", + "configuration": "Configuration", + "logs": "Logs", + "apidocs": "API", + "database": "Database", + "jhipster-needle-menu-add-admin-element": "JHipster will add additional menu entries here (do not translate!)" + }, + "language": "Language" + }, + "form": { + "username.label": "Username", + "username.placeholder": "Your username", + "currentpassword.label": "Current password", + "currentpassword.placeholder": "Current password", + "newpassword.label": "New password", + "newpassword.placeholder": "New password", + "confirmpassword.label": "New password confirmation", + "confirmpassword.placeholder": "Confirm the new password", + "email.label": "Email", + "email.placeholder": "Your email" + }, + "messages": { + "info": { + "authenticated": { + "prefix": "If you want to ", + "link": "sign in", + "suffix": ", you can try the default accounts:
- Administrator (login=\"admin\" and password=\"admin\")
- User (login=\"user\" and password=\"user\")." + }, + "register": { + "noaccount": "You don't have an account yet?", + "link": "Register a new account" + } + }, + "error": { + "dontmatch": "The password and its confirmation do not match!" + }, + "validate": { + "newpassword": { + "required": "Your password is required.", + "minlength": "Your password is required to be at least 4 characters.", + "maxlength": "Your password cannot be longer than 50 characters.", + "strength": "Password strength:" + }, + "confirmpassword": { + "required": "Your confirmation password is required.", + "minlength": "Your confirmation password is required to be at least 4 characters.", + "maxlength": "Your confirmation password cannot be longer than 50 characters." + }, + "email": { + "required": "Your email is required.", + "invalid": "Your email is invalid.", + "minlength": "Your email is required to be at least 5 characters.", + "maxlength": "Your email cannot be longer than 50 characters." + } + } + }, + "field": { + "id": "ID" + }, + "ribbon": { + "dev": "Development" + }, + "item-count": "Showing { first } - { second } of { total } items." + }, + "entity": { + "action": { + "addblob": "Add blob", + "addimage": "Add image", + "back": "Back", + "cancel": "Cancel", + "delete": "Delete", + "edit": "Edit", + "open": "Open", + "save": "Save", + "view": "View", + "show": "Show { otherEntity }" + }, + "detail": { + "field": "Field", + "value": "Value" + }, + "delete": { + "title": "Confirm delete operation" + }, + "validation": { + "required": "This field is required.", + "minlength": "This field is required to be at least { min } characters.", + "maxlength": "This field cannot be longer than { max } characters.", + "min": "This field should be at least { min }.", + "max": "This field cannot be more than { max }.", + "minbytes": "This field should be at least { min } bytes.", + "maxbytes": "This field cannot be more than { max } bytes.", + "pattern": "This field should follow pattern for { pattern }.", + "number": "This field should be a number.", + "datetimelocal": "This field should be a date and time.", + "patternLogin": "This field can only contain letters, digits and e-mail addresses." + }, + "filters": { + "set": "Following filters are set", + "clear": "Clear filter", + "clearAll": "Clear all filters" + } + }, + "error": { + "internalServerError": "Internal server error", + "server.not.reachable": "Server not reachable", + "url.not.found": "Not found", + "NotNull": "Field { fieldName } cannot be empty!", + "Size": "Field { fieldName } does not meet min/max size requirements!", + "userexists": "Login name already used!", + "emailexists": "Email is already in use!", + "idexists": "A new { entityName } cannot already have an ID", + "idnull": "Invalid ID", + "idinvalid": "Invalid ID", + "idnotfound": "ID cannot be found", + "file": { + "could.not.extract": "Could not extract file", + "not.image": "File was expected to be an image but was found to be \"{ fileType }\"" + } + }, + "footer": "This is your footer" +} diff --git a/src/main/webapp/i18n/en/health.json b/src/main/webapp/i18n/en/health.json new file mode 100644 index 0000000..0a0a4d4 --- /dev/null +++ b/src/main/webapp/i18n/en/health.json @@ -0,0 +1,32 @@ +{ + "health": { + "title": "Health Checks", + "refresh.button": "Refresh", + "stacktrace": "Stacktrace", + "details": { + "details": "Details", + "properties": "Properties", + "name": "Name", + "value": "Value", + "error": "Error" + }, + "indicator": { + "diskSpace": "Disk space", + "ssl": "SSL", + "mail": "Email", + "livenessState": "Liveness state", + "readinessState": "Readiness state", + "ping": "Application", + "db": "Database" + }, + "table": { + "service": "Service name", + "status": "Status" + }, + "status": { + "UNKNOWN": "UNKNOWN", + "UP": "UP", + "DOWN": "DOWN" + } + } +} diff --git a/src/main/webapp/i18n/en/home.json b/src/main/webapp/i18n/en/home.json new file mode 100644 index 0000000..bcae837 --- /dev/null +++ b/src/main/webapp/i18n/en/home.json @@ -0,0 +1,19 @@ +{ + "home": { + "title": "Welcome, Java Hipster!", + "subtitle": "This is your homepage", + "logged": { + "message": "You are logged in as user \"{ username }\"." + }, + "question": "If you have any questions on JHipster:", + "link": { + "homepage": "JHipster homepage", + "stackoverflow": "JHipster on Stack Overflow", + "bugtracker": "JHipster bug tracker", + "chat": "JHipster public chat room", + "follow": "follow {'@'}jhipster on Twitter" + }, + "like": "If you like JHipster, don't forget to give us a star on", + "github": "GitHub" + } +} diff --git a/src/main/webapp/i18n/en/login.json b/src/main/webapp/i18n/en/login.json new file mode 100644 index 0000000..4667958 --- /dev/null +++ b/src/main/webapp/i18n/en/login.json @@ -0,0 +1,19 @@ +{ + "login": { + "title": "Sign in", + "form": { + "password": "Password", + "password.placeholder": "Your password", + "rememberme": "Remember me", + "button": "Sign in" + }, + "messages": { + "error": { + "authentication": "Failed to sign in! Please check your credentials and try again." + } + }, + "password": { + "forgot": "Did you forget your password?" + } + } +} diff --git a/src/main/webapp/i18n/en/logs.json b/src/main/webapp/i18n/en/logs.json new file mode 100644 index 0000000..638e6d0 --- /dev/null +++ b/src/main/webapp/i18n/en/logs.json @@ -0,0 +1,11 @@ +{ + "logs": { + "title": "Logs", + "nbloggers": "There are { total } loggers.", + "filter": "Filter", + "table": { + "name": "Name", + "level": "Level" + } + } +} diff --git a/src/main/webapp/i18n/en/metrics.json b/src/main/webapp/i18n/en/metrics.json new file mode 100644 index 0000000..e192762 --- /dev/null +++ b/src/main/webapp/i18n/en/metrics.json @@ -0,0 +1,102 @@ +{ + "metrics": { + "title": "Application Metrics", + "refresh.button": "Refresh", + "updating": "Updating...", + "jvm": { + "title": "JVM Metrics", + "memory": { + "title": "Memory", + "total": "Total Memory", + "heap": "Heap Memory", + "nonheap": "Non-Heap Memory" + }, + "threads": { + "title": "Threads", + "all": "All", + "runnable": "Runnable", + "timedwaiting": "Timed waiting", + "waiting": "Waiting", + "blocked": "Blocked", + "dump": { + "title": "Threads dump", + "id": "Id: ", + "blockedtime": "Blocked Time", + "blockedcount": "Blocked Count", + "waitedtime": "Waited Time", + "waitedcount": "Waited Count", + "lockname": "Lock name", + "stacktrace": "Stacktrace", + "show": "Show Stacktrace", + "hide": "Hide Stacktrace" + } + }, + "gc": { + "title": "Garbage collections", + "marksweepcount": "Mark Sweep count", + "marksweeptime": "Mark Sweep time", + "scavengecount": "Scavenge count", + "scavengetime": "Scavenge time" + }, + "http": { + "title": "HTTP requests (time in milliseconds)", + "active": "Active requests:", + "total": "Total requests:", + "table": { + "code": "Code", + "count": "Count", + "mean": "Mean", + "average": "Average", + "max": "Max" + }, + "code": { + "ok": "Ok", + "notfound": "Not found", + "servererror": "Server Error" + } + } + }, + "servicesstats": { + "title": "Services statistics (time in milliseconds)", + "table": { + "name": "Service name", + "count": "Count", + "mean": "Mean", + "min": "Min", + "max": "Max", + "p50": "p50", + "p75": "p75", + "p95": "p95", + "p99": "p99" + } + }, + "cache": { + "title": "Cache statistics", + "cachename": "Cache name", + "hits": "Cache Hits", + "misses": "Cache Misses", + "gets": "Cache Gets", + "puts": "Cache Puts", + "removals": "Cache Removals", + "evictions": "Cache Evictions", + "hitPercent": "Cache Hit %", + "missPercent": "Cache Miss %", + "averageGetTime": "Average get time (µs)", + "averagePutTime": "Average put time (µs)", + "averageRemoveTime": "Average remove time (µs)" + }, + "datasource": { + "usage": "Connection Pool Usage", + "title": "DataSource statistics (time in milliseconds)", + "name": "Pool usage", + "count": "Count", + "mean": "Mean", + "min": "Min", + "max": "Max", + "p50": "p50", + "p75": "p75", + "p95": "p95", + "p99": "p99" + } + } +} diff --git a/src/main/webapp/i18n/en/password.json b/src/main/webapp/i18n/en/password.json new file mode 100644 index 0000000..cc7196a --- /dev/null +++ b/src/main/webapp/i18n/en/password.json @@ -0,0 +1,12 @@ +{ + "password": { + "title": "Password for [{ username }]", + "form": { + "button": "Save" + }, + "messages": { + "error": "An error has occurred! The password could not be changed.", + "success": "Password changed!" + } + } +} diff --git a/src/main/webapp/i18n/en/register.json b/src/main/webapp/i18n/en/register.json new file mode 100644 index 0000000..1a0aeec --- /dev/null +++ b/src/main/webapp/i18n/en/register.json @@ -0,0 +1,24 @@ +{ + "register": { + "title": "Registration", + "form": { + "button": "Register" + }, + "messages": { + "validate": { + "login": { + "required": "Your username is required.", + "minlength": "Your username is required to be at least 1 character.", + "maxlength": "Your username cannot be longer than 50 characters.", + "pattern": "Your username is invalid." + } + }, + "success": "Registration saved! Please check your email for confirmation.", + "error": { + "fail": "Registration failed! Please try again later.", + "userexists": "Login name already registered! Please choose another one.", + "emailexists": "Email is already in use! Please choose another one." + } + } + } +} diff --git a/src/main/webapp/i18n/en/reset.json b/src/main/webapp/i18n/en/reset.json new file mode 100644 index 0000000..062d3e7 --- /dev/null +++ b/src/main/webapp/i18n/en/reset.json @@ -0,0 +1,26 @@ +{ + "reset": { + "request": { + "title": "Reset your password", + "form": { + "button": "Reset password" + }, + "messages": { + "info": "Enter the email address you used to register", + "success": "Check your email for details on how to reset your password." + } + }, + "finish": { + "title": "Reset password", + "form": { + "button": "Validate new password" + }, + "messages": { + "info": "Choose a new password", + "success": "Your password has been reset. Please ", + "keymissing": "The reset key is missing.", + "error": "Your password couldn't be reset. Remember a password request is only valid for 24 hours." + } + } + } +} diff --git a/src/main/webapp/i18n/en/sessions.json b/src/main/webapp/i18n/en/sessions.json new file mode 100644 index 0000000..ff7a284 --- /dev/null +++ b/src/main/webapp/i18n/en/sessions.json @@ -0,0 +1,15 @@ +{ + "sessions": { + "title": "Active sessions for [{ username }]", + "table": { + "ipaddress": "IP address", + "useragent": "User Agent", + "date": "Date", + "button": "Invalidate" + }, + "messages": { + "success": "Session invalidated!", + "error": "An error has occurred! The session could not be invalidated." + } + } +} diff --git a/src/main/webapp/i18n/en/settings.json b/src/main/webapp/i18n/en/settings.json new file mode 100644 index 0000000..c8dd74f --- /dev/null +++ b/src/main/webapp/i18n/en/settings.json @@ -0,0 +1,32 @@ +{ + "settings": { + "title": "User settings for [{ username }]", + "form": { + "firstname": "First Name", + "firstname.placeholder": "Your first name", + "lastname": "Last Name", + "lastname.placeholder": "Your last name", + "language": "Language", + "button": "Save" + }, + "messages": { + "error": { + "fail": "An error has occurred! Settings could not be saved.", + "emailexists": "Email is already in use! Please choose another one." + }, + "success": "Settings saved!", + "validate": { + "firstname": { + "required": "Your first name is required.", + "minlength": "Your first name is required to be at least 1 character", + "maxlength": "Your first name cannot be longer than 50 characters" + }, + "lastname": { + "required": "Your last name is required.", + "minlength": "Your last name is required to be at least 1 character", + "maxlength": "Your last name cannot be longer than 50 characters" + } + } + } + } +} diff --git a/src/main/webapp/i18n/en/user-management.json b/src/main/webapp/i18n/en/user-management.json new file mode 100644 index 0000000..8ea1ea2 --- /dev/null +++ b/src/main/webapp/i18n/en/user-management.json @@ -0,0 +1,34 @@ +{ + "userManagement": { + "home": { + "title": "Users", + "refreshListLabel": "Refresh list", + "createLabel": "Create a new user", + "createOrEditLabel": "Create or edit a user", + "notFound": "No user found" + }, + "created": "A new user is created with identifier { param }", + "updated": "A user is updated with identifier { param }", + "deleted": "A user is deleted with identifier { param }", + "delete": { + "question": "Are you sure you want to delete user { login }?" + }, + "detail": { + "title": "User" + }, + "id": "ID", + "login": "Login", + "firstName": "First name", + "lastName": "Last name", + "email": "Email", + "imageUrl": "Image", + "activated": "Activated", + "deactivated": "Deactivated", + "profiles": "Profiles", + "langKey": "Language", + "createdBy": "Created by", + "createdDate": "Created date", + "lastModifiedBy": "Modified by", + "lastModifiedDate": "Modified date" + } +} diff --git a/src/main/webapp/index.html b/src/main/webapp/index.html new file mode 100644 index 0000000..96ed005 --- /dev/null +++ b/src/main/webapp/index.html @@ -0,0 +1,117 @@ + + + + + questionBank + + + + + + + + + + + + + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+ + + + diff --git a/src/main/webapp/manifest.webapp b/src/main/webapp/manifest.webapp new file mode 100644 index 0000000..2ba3dcf --- /dev/null +++ b/src/main/webapp/manifest.webapp @@ -0,0 +1,31 @@ +{ + "name": "QuestionBank", + "short_name": "QuestionBank", + "icons": [ + { + "src": "./content/images/jhipster_family_member_2_head-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "./content/images/jhipster_family_member_2_head-256.png", + "sizes": "256x256", + "type": "image/png" + }, + { + "src": "./content/images/jhipster_family_member_2_head-384.png", + "sizes": "384x384", + "type": "image/png" + }, + { + "src": "./content/images/jhipster_family_member_2_head-512.png", + "sizes": "512x512", + "type": "image/png" + } + ], + "theme_color": "#000000", + "background_color": "#e0e0e0", + "start_url": ".", + "display": "standalone", + "orientation": "portrait" +} diff --git a/src/main/webapp/robots.txt b/src/main/webapp/robots.txt new file mode 100644 index 0000000..04f669b --- /dev/null +++ b/src/main/webapp/robots.txt @@ -0,0 +1,8 @@ +# robotstxt.org/ + +User-agent: * +Disallow: /api/account +Disallow: /api/logs/ +Disallow: /api/users/ +Disallow: /management/ +Disallow: /v3/api-docs/ diff --git a/src/main/webapp/swagger-ui/index.html b/src/main/webapp/swagger-ui/index.html new file mode 100644 index 0000000..4c84751 --- /dev/null +++ b/src/main/webapp/swagger-ui/index.html @@ -0,0 +1,115 @@ + + + + + questionBank - Swagger UI + + + + + + + +
+ + + + + + + + diff --git a/src/test/java/com/example/questionbank/IntegrationTest.java b/src/test/java/com/example/questionbank/IntegrationTest.java new file mode 100644 index 0000000..61c2a4c --- /dev/null +++ b/src/test/java/com/example/questionbank/IntegrationTest.java @@ -0,0 +1,24 @@ +package com.example.questionbank; + +import com.example.questionbank.config.AsyncSyncConfiguration; +import com.example.questionbank.config.DatabaseTestcontainer; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import org.springframework.boot.test.context.SpringBootTest; + +/** + * Base composite annotation for integration tests. + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@SpringBootTest( + classes = { + QuestionBankApp.class, + AsyncSyncConfiguration.class, + com.example.questionbank.config.JacksonHibernateConfiguration.class, + DatabaseTestcontainer.class, + } +) +public @interface IntegrationTest {} diff --git a/src/test/java/com/example/questionbank/TechnicalStructureTest.java b/src/test/java/com/example/questionbank/TechnicalStructureTest.java new file mode 100644 index 0000000..647d073 --- /dev/null +++ b/src/test/java/com/example/questionbank/TechnicalStructureTest.java @@ -0,0 +1,38 @@ +package com.example.questionbank; + +import static com.tngtech.archunit.base.DescribedPredicate.alwaysTrue; +import static com.tngtech.archunit.core.domain.JavaClass.Predicates.belongToAnyOf; +import static com.tngtech.archunit.library.Architectures.layeredArchitecture; + +import com.tngtech.archunit.core.importer.ImportOption.DoNotIncludeTests; +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; + +@AnalyzeClasses(packagesOf = QuestionBankApp.class, importOptions = DoNotIncludeTests.class) +class TechnicalStructureTest { + + // prettier-ignore + @ArchTest + static final ArchRule respectsTechnicalArchitectureLayers = layeredArchitecture() + .consideringAllDependencies() + .layer("Config").definedBy("..config..") + .layer("Web").definedBy("..web..") + .optionalLayer("Service").definedBy("..service..") + .layer("Security").definedBy("..security..") + .optionalLayer("Persistence").definedBy("..repository..") + .layer("Domain").definedBy("..domain..") + + .whereLayer("Config").mayNotBeAccessedByAnyLayer() + .whereLayer("Web").mayOnlyBeAccessedByLayers("Config") + .whereLayer("Service").mayOnlyBeAccessedByLayers("Web", "Config") + .whereLayer("Security").mayOnlyBeAccessedByLayers("Config", "Service", "Web") + .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service", "Security", "Web", "Config") + .whereLayer("Domain").mayOnlyBeAccessedByLayers("Persistence", "Service", "Security", "Web", "Config") + + .ignoreDependency(belongToAnyOf(QuestionBankApp.class), alwaysTrue()) + .ignoreDependency(alwaysTrue(), belongToAnyOf( + com.example.questionbank.config.Constants.class, + com.example.questionbank.config.ApplicationProperties.class + )); +} diff --git a/src/test/java/com/example/questionbank/aop/logging/LoggingAspectTest.java b/src/test/java/com/example/questionbank/aop/logging/LoggingAspectTest.java new file mode 100644 index 0000000..dea68f8 --- /dev/null +++ b/src/test/java/com/example/questionbank/aop/logging/LoggingAspectTest.java @@ -0,0 +1,102 @@ +package com.example.questionbank.aop.logging; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import java.util.List; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.Signature; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; + +class LoggingAspectTest { + + private static final String DECLARING_TYPE = "com.example.questionbank.service.LoggedService"; + private static final String METHOD = "loggedMethod"; + + private final Environment env = mock(Environment.class); + private final ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class); + private final ListAppender appender = new ListAppender<>(); + private LoggingAspect aspect; + private Logger logger; + + @BeforeEach + void setup() { + Signature signature = mock(Signature.class); + when(signature.getDeclaringTypeName()).thenReturn(DECLARING_TYPE); + when(signature.getName()).thenReturn(METHOD); + when(joinPoint.getSignature()).thenReturn(signature); + when(joinPoint.getArgs()).thenReturn(new Object[] { "arg" }); + when(env.acceptsProfiles(any(Profiles.class))).thenReturn(true); + + logger = (Logger) LoggerFactory.getLogger(DECLARING_TYPE); + logger.setLevel(Level.DEBUG); + appender.start(); + logger.addAppender(appender); + + aspect = new LoggingAspect(env); + } + + @AfterEach + void teardown() { + logger.detachAppender(appender); + logger.setLevel(null); + } + + private List messages() { + return appender.list.stream().map(ILoggingEvent::getFormattedMessage).toList(); + } + + @Test + void logAroundLogsEnterAndExit() throws Throwable { + when(joinPoint.proceed()).thenReturn("result"); + + Object result = aspect.logAround(joinPoint); + + assertThat(result).isEqualTo("result"); + assertThat(messages()).containsExactly( + "Enter: loggedMethod() with argument[s] = [arg]", + "Exit: loggedMethod() with result = result" + ); + } + + @Test + void logAroundRethrowsIllegalArgumentException() throws Throwable { + when(joinPoint.proceed()).thenThrow(new IllegalArgumentException("invalid")); + + assertThatThrownBy(() -> aspect.logAround(joinPoint)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("invalid"); + + assertThat(messages()).contains("Illegal argument: [arg] in loggedMethod()"); + } + + @Test + void logAfterThrowingLogsExceptionWithStackTraceInDevProfile() { + aspect.logAfterThrowing(joinPoint, new IllegalStateException("failed")); + + assertThat(messages()).containsExactly("Exception in loggedMethod() with cause = 'NULL' and exception = 'failed'"); + assertThat(appender.list.get(0).getThrowableProxy()).isNotNull(); + } + + @Test + void logAfterThrowingLogsCauseOnlyOutsideDevProfile() { + when(env.acceptsProfiles(any(Profiles.class))).thenReturn(false); + + aspect.logAfterThrowing(joinPoint, new IllegalStateException("failed", new RuntimeException("root"))); + + assertThat(messages()).containsExactly("Exception in loggedMethod() with cause = java.lang.RuntimeException: root"); + assertThat(appender.list.get(0).getThrowableProxy()).isNull(); + } +} diff --git a/src/test/java/com/example/questionbank/config/AsyncSyncConfiguration.java b/src/test/java/com/example/questionbank/config/AsyncSyncConfiguration.java new file mode 100644 index 0000000..b17b360 --- /dev/null +++ b/src/test/java/com/example/questionbank/config/AsyncSyncConfiguration.java @@ -0,0 +1,15 @@ +package com.example.questionbank.config; + +import java.util.concurrent.Executor; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.core.task.SyncTaskExecutor; + +@TestConfiguration(proxyBeanMethods = false) +public class AsyncSyncConfiguration { + + @Bean(name = "taskExecutor") + public Executor taskExecutor() { + return new SyncTaskExecutor(); + } +} diff --git a/src/test/java/com/example/questionbank/config/CRLFLogConverterTest.java b/src/test/java/com/example/questionbank/config/CRLFLogConverterTest.java new file mode 100644 index 0000000..7ffd7ad --- /dev/null +++ b/src/test/java/com/example/questionbank/config/CRLFLogConverterTest.java @@ -0,0 +1,132 @@ +package com.example.questionbank.config; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; +import org.springframework.boot.ansi.AnsiColor; +import org.springframework.boot.ansi.AnsiElement; + +class CRLFLogConverterTest { + + @Test + void transformShouldReturnInputStringWhenMarkerListIsEmpty() { + ILoggingEvent event = mock(ILoggingEvent.class); + when(event.getMarkerList()).thenReturn(null); + when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger"); + String input = "Test input string"; + CRLFLogConverter converter = new CRLFLogConverter(); + + String result = converter.transform(event, input); + + assertEquals(input, result); + } + + @Test + void transformShouldReturnInputStringWhenMarkersContainCRLFSafeMarker() { + ILoggingEvent event = mock(ILoggingEvent.class); + Marker marker = MarkerFactory.getMarker("CRLF_SAFE"); + List markers = List.of(marker); + when(event.getMarkerList()).thenReturn(markers); + String input = "Test input string"; + CRLFLogConverter converter = new CRLFLogConverter(); + + String result = converter.transform(event, input); + + assertEquals(input, result); + } + + @Test + void transformShouldReturnInputStringWhenMarkersNotContainCRLFSafeMarker() { + ILoggingEvent event = mock(ILoggingEvent.class); + Marker marker = MarkerFactory.getMarker("CRLF_NOT_SAFE"); + List markers = List.of(marker); + when(event.getMarkerList()).thenReturn(markers); + when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger"); + String input = "Test input string"; + CRLFLogConverter converter = new CRLFLogConverter(); + + String result = converter.transform(event, input); + + assertEquals(input, result); + } + + @Test + void transformShouldReturnInputStringWhenLoggerIsSafe() { + ILoggingEvent event = mock(ILoggingEvent.class); + when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger"); + String input = "Test input string"; + CRLFLogConverter converter = new CRLFLogConverter(); + + String result = converter.transform(event, input); + + assertEquals(input, result); + } + + @Test + void transformShouldReplaceNewlinesAndCarriageReturnsWithUnderscoreWhenMarkersDoNotContainCRLFSafeMarkerAndLoggerIsNotSafe() { + ILoggingEvent event = mock(ILoggingEvent.class); + List markers = List.of(); + when(event.getMarkerList()).thenReturn(markers); + when(event.getLoggerName()).thenReturn("com.example.questionbank.example.Logger"); + String input = "Test\ninput\rstring"; + CRLFLogConverter converter = new CRLFLogConverter(); + + String result = converter.transform(event, input); + + assertEquals("Test_input_string", result); + } + + @Test + void transformShouldReplaceNewlinesAndCarriageReturnsWithAnsiStringWhenMarkersDoNotContainCRLFSafeMarkerAndLoggerIsNotSafeAndAnsiElementIsNotNull() { + ILoggingEvent event = mock(ILoggingEvent.class); + List markers = List.of(); + when(event.getMarkerList()).thenReturn(markers); + when(event.getLoggerName()).thenReturn("com.example.questionbank.example.Logger"); + String input = "Test\ninput\rstring"; + CRLFLogConverter converter = new CRLFLogConverter(); + converter.setOptionList(List.of("red")); + + String result = converter.transform(event, input); + + assertEquals("Test_input_string", result); + } + + @Test + void isLoggerSafeShouldReturnTrueWhenLoggerNameStartsWithSafeLogger() { + ILoggingEvent event = mock(ILoggingEvent.class); + when(event.getLoggerName()).thenReturn("org.springframework.boot.autoconfigure.example.Logger"); + CRLFLogConverter converter = new CRLFLogConverter(); + + boolean result = converter.isLoggerSafe(event); + + assertTrue(result); + } + + @Test + void isLoggerSafeShouldReturnFalseWhenLoggerNameDoesNotStartWithSafeLogger() { + ILoggingEvent event = mock(ILoggingEvent.class); + when(event.getLoggerName()).thenReturn("com.example.questionbank.example.Logger"); + CRLFLogConverter converter = new CRLFLogConverter(); + + boolean result = converter.isLoggerSafe(event); + + assertFalse(result); + } + + @Test + void testToAnsiString() { + CRLFLogConverter cut = new CRLFLogConverter(); + AnsiElement ansiElement = AnsiColor.RED; + + String result = cut.toAnsiString("input", ansiElement); + + assertThat(result).isEqualTo("input"); + } +} diff --git a/src/test/java/com/example/questionbank/config/DatabaseTestcontainer.java b/src/test/java/com/example/questionbank/config/DatabaseTestcontainer.java new file mode 100644 index 0000000..624f84e --- /dev/null +++ b/src/test/java/com/example/questionbank/config/DatabaseTestcontainer.java @@ -0,0 +1,24 @@ +package com.example.questionbank.config; + +import org.slf4j.LoggerFactory; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.annotation.Bean; +import org.testcontainers.containers.output.Slf4jLogConsumer; +import org.testcontainers.postgresql.PostgreSQLContainer; + +@TestConfiguration(proxyBeanMethods = false) +public class DatabaseTestcontainer { + + private static final PostgreSQLContainer DATABASE_CONTAINER = new PostgreSQLContainer("postgres:18.6") + .withDatabaseName("questionBank") + + .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger(DatabaseTestcontainer.class))) + .withReuse(true); + + @Bean + @ServiceConnection + PostgreSQLContainer databaseContainer() { + return DATABASE_CONTAINER; + } +} diff --git a/src/test/java/com/example/questionbank/config/SpringBootTestClassOrderer.java b/src/test/java/com/example/questionbank/config/SpringBootTestClassOrderer.java new file mode 100644 index 0000000..656c1db --- /dev/null +++ b/src/test/java/com/example/questionbank/config/SpringBootTestClassOrderer.java @@ -0,0 +1,22 @@ +package com.example.questionbank.config; + +import com.example.questionbank.IntegrationTest; +import java.util.Comparator; +import org.junit.jupiter.api.ClassDescriptor; +import org.junit.jupiter.api.ClassOrderer; +import org.junit.jupiter.api.ClassOrdererContext; + +public class SpringBootTestClassOrderer implements ClassOrderer { + + @Override + public void orderClasses(ClassOrdererContext context) { + context.getClassDescriptors().sort(Comparator.comparingInt(SpringBootTestClassOrderer::getOrder)); + } + + private static int getOrder(ClassDescriptor classDescriptor) { + if (classDescriptor.findAnnotation(IntegrationTest.class).isPresent()) { + return 2; + } + return 1; + } +} diff --git a/src/test/java/com/example/questionbank/config/StaticResourcesWebConfigurerTest.java b/src/test/java/com/example/questionbank/config/StaticResourcesWebConfigurerTest.java new file mode 100644 index 0000000..84beca9 --- /dev/null +++ b/src/test/java/com/example/questionbank/config/StaticResourcesWebConfigurerTest.java @@ -0,0 +1,76 @@ +package com.example.questionbank.config; + +import static com.example.questionbank.config.StaticResourcesWebConfiguration.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; + +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.CacheControl; +import org.springframework.mock.web.MockServletContext; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import tech.jhipster.config.JHipsterDefaults; +import tech.jhipster.config.JHipsterProperties; + +class StaticResourcesWebConfigurerTest { + + public static final int MAX_AGE_TEST = 5; + public StaticResourcesWebConfiguration staticResourcesWebConfiguration; + private ResourceHandlerRegistry resourceHandlerRegistry; + private MockServletContext servletContext; + private WebApplicationContext applicationContext; + private JHipsterProperties props; + + @BeforeEach + void setUp() { + servletContext = spy(new MockServletContext()); + applicationContext = mock(WebApplicationContext.class); + resourceHandlerRegistry = spy(new ResourceHandlerRegistry(applicationContext, servletContext)); + props = new JHipsterProperties(); + staticResourcesWebConfiguration = spy(new StaticResourcesWebConfiguration(props)); + } + + @Test + void shouldAppendResourceHandlerAndInitializeIt() { + staticResourcesWebConfiguration.addResourceHandlers(resourceHandlerRegistry); + + verify(resourceHandlerRegistry, times(1)).addResourceHandler(RESOURCE_PATHS); + verify(staticResourcesWebConfiguration, times(1)).initializeResourceHandler(any(ResourceHandlerRegistration.class)); + for (String testingPath : RESOURCE_PATHS) { + assertThat(resourceHandlerRegistry.hasMappingForPattern(testingPath)).isTrue(); + } + } + + @Test + void shouldInitializeResourceHandlerWithCacheControlAndLocations() { + CacheControl ccExpected = CacheControl.maxAge(5, TimeUnit.DAYS).cachePublic(); + when(staticResourcesWebConfiguration.getCacheControl()).thenReturn(ccExpected); + ResourceHandlerRegistration resourceHandlerRegistration = spy(new ResourceHandlerRegistration(RESOURCE_PATHS)); + + staticResourcesWebConfiguration.initializeResourceHandler(resourceHandlerRegistration); + + verify(staticResourcesWebConfiguration, times(1)).getCacheControl(); + verify(resourceHandlerRegistration, times(1)).setCacheControl(ccExpected); + verify(resourceHandlerRegistration, times(1)).addResourceLocations(RESOURCE_LOCATIONS); + } + + @Test + void shouldCreateCacheControlBasedOnJhipsterDefaultProperties() { + CacheControl cacheExpected = CacheControl.maxAge(JHipsterDefaults.Http.Cache.timeToLiveInDays, TimeUnit.DAYS).cachePublic(); + assertThat(staticResourcesWebConfiguration.getCacheControl()) + .extracting(CacheControl::getHeaderValue) + .isEqualTo(cacheExpected.getHeaderValue()); + } + + @Test + void shouldCreateCacheControlWithSpecificConfigurationInProperties() { + props.getHttp().getCache().setTimeToLiveInDays(MAX_AGE_TEST); + CacheControl cacheExpected = CacheControl.maxAge(MAX_AGE_TEST, TimeUnit.DAYS).cachePublic(); + assertThat(staticResourcesWebConfiguration.getCacheControl()) + .extracting(CacheControl::getHeaderValue) + .isEqualTo(cacheExpected.getHeaderValue()); + } +} diff --git a/src/test/java/com/example/questionbank/config/WebConfigurerTest.java b/src/test/java/com/example/questionbank/config/WebConfigurerTest.java new file mode 100644 index 0000000..36aec7f --- /dev/null +++ b/src/test/java/com/example/questionbank/config/WebConfigurerTest.java @@ -0,0 +1,113 @@ +package com.example.questionbank.config; + +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import jakarta.servlet.*; +import java.util.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.mock.web.MockServletContext; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import tech.jhipster.config.JHipsterProperties; + +/** + * Unit tests for the {@link WebConfigurer} class. + */ +class WebConfigurerTest { + + private WebConfigurer webConfigurer; + + private MockServletContext servletContext; + + private MockEnvironment env; + + private JHipsterProperties props; + + @BeforeEach + void setup() { + servletContext = spy(new MockServletContext()); + doReturn(mock(FilterRegistration.Dynamic.class)).when(servletContext).addFilter(anyString(), any(Filter.class)); + doReturn(mock(ServletRegistration.Dynamic.class)).when(servletContext).addServlet(anyString(), any(Servlet.class)); + + env = new MockEnvironment(); + props = new JHipsterProperties(); + + webConfigurer = new WebConfigurer(env, props); + } + + @Test + void shouldCorsFilterOnApiPath() throws Exception { + props.getCors().setAllowedOrigins(List.of("other.domain.com")); + props.getCors().setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE")); + props.getCors().setAllowedHeaders(List.of("*")); + props.getCors().setMaxAge(1800L); + props.getCors().setAllowCredentials(true); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); + + mockMvc + .perform( + options("/api/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") + ) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) + .andExpect(header().string(HttpHeaders.VARY, "Origin")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); + + mockMvc + .perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); + } + + @Test + void shouldCorsFilterOnOtherPath() throws Exception { + props.getCors().setAllowedOrigins(List.of("*")); + props.getCors().setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE")); + props.getCors().setAllowedHeaders(List.of("*")); + props.getCors().setMaxAge(1800L); + props.getCors().setAllowCredentials(true); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); + + mockMvc + .perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + } + + @Test + void shouldCorsFilterDeactivatedForNullAllowedOrigins() throws Exception { + props.getCors().setAllowedOrigins(null); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); + + mockMvc + .perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + } + + @Test + void shouldCorsFilterDeactivatedForEmptyAllowedOrigins() throws Exception { + props.getCors().setAllowedOrigins(new ArrayList<>()); + + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); + + mockMvc + .perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + } +} diff --git a/src/test/java/com/example/questionbank/config/WebConfigurerTestController.java b/src/test/java/com/example/questionbank/config/WebConfigurerTestController.java new file mode 100644 index 0000000..b9df727 --- /dev/null +++ b/src/test/java/com/example/questionbank/config/WebConfigurerTestController.java @@ -0,0 +1,18 @@ +package com.example.questionbank.config; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class WebConfigurerTestController { + + @GetMapping("/api/test-cors") + public void testCorsOnApiPath() { + // empty method + } + + @GetMapping("/test/test-cors") + public void testCorsOnOtherPath() { + // empty method + } +} diff --git a/src/test/java/com/example/questionbank/config/timezone/HibernateTimeZoneIT.java b/src/test/java/com/example/questionbank/config/timezone/HibernateTimeZoneIT.java new file mode 100644 index 0000000..b91dc83 --- /dev/null +++ b/src/test/java/com/example/questionbank/config/timezone/HibernateTimeZoneIT.java @@ -0,0 +1,171 @@ +package com.example.questionbank.config.timezone; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.example.questionbank.IntegrationTest; +import com.example.questionbank.repository.timezone.DateTimeWrapper; +import com.example.questionbank.repository.timezone.DateTimeWrapperRepository; +import java.time.*; +import java.time.format.DateTimeFormatter; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.support.rowset.SqlRowSet; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integration tests for verifying the behavior of Hibernate in the context of storing various date and time types across different databases. + * The tests focus on ensuring that the stored values are correctly transformed and stored according to the configured timezone. + * Timezone is environment specific, and can be adjusted according to your needs. + * + * For more context, refer to: + * - GitHub Issue: https://github.com/jhipster/generator-jhipster/issues/22579 + * - Pull Request: https://github.com/jhipster/generator-jhipster/pull/22946 + */ +@IntegrationTest +class HibernateTimeZoneIT { + + @Autowired + private DateTimeWrapperRepository dateTimeWrapperRepository; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Value("${spring.jpa.properties.hibernate.jdbc.time_zone:UTC}") + private String zoneId; + + private DateTimeWrapper dateTimeWrapper; + private DateTimeFormatter dateTimeFormatter; + private DateTimeFormatter timeFormatter; + private DateTimeFormatter offsetTimeFormatter; + private DateTimeFormatter dateFormatter; + + @BeforeEach + void setup() { + dateTimeWrapper = new DateTimeWrapper(); + dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:10:00.0Z")); + dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:20:00.0")); + dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z")); + dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:40:00.0Z")); + dateTimeWrapper.setLocalTime(LocalTime.parse("14:50:00")); + dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:00:00+02:00")); + dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10")); + + dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").withZone(ZoneId.of(zoneId)); + timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneId.of(zoneId)); + offsetTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); + dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + } + + @Test + @Transactional + void storeInstantWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("instant", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant()); + + assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); + } + + @Test + @Transactional + void storeLocalDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper.getLocalDateTime().atZone(ZoneId.systemDefault()).format(dateTimeFormatter); + + assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); + } + + @Test + @Transactional + void storeOffsetDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper.getOffsetDateTime().format(dateTimeFormatter); + + assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); + } + + @Test + @Transactional + void storeZoneDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper.getZonedDateTime().format(dateTimeFormatter); + + assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); + } + + @Test + @Transactional + void storeLocalTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZoneAccordingToHis1stJan1970Value() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getLocalTime() + .atDate(LocalDate.of(1970, Month.JANUARY, 1)) + .atZone(ZoneId.systemDefault()) + .format(timeFormatter); + + assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); + } + + @Test + @Transactional + void storeOffsetTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZoneAccordingToHis1stJan1970Value() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("offset_time", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper + .getOffsetTime() + // Convert to configured timezone + .withOffsetSameInstant(ZoneId.of(zoneId).getRules().getOffset(Instant.now())) + // Normalize to System TimeZone. + // this behavior looks a bug, refer to https://github.com/jhipster/generator-jhipster/issues/22579. + .withOffsetSameLocal(OffsetDateTime.ofInstant(Instant.EPOCH, ZoneId.systemDefault()).getOffset()) + // Convert the normalized value to configured timezone + .withOffsetSameInstant(ZoneId.of(zoneId).getRules().getOffset(Instant.EPOCH)) + .format(offsetTimeFormatter); + + assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); + } + + @Test + @Transactional + void storeLocalDateWithZoneIdConfigShouldBeStoredWithoutTransformation() { + dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); + + String request = generateSqlRequest("local_date", dateTimeWrapper.getId()); + SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); + String expectedValue = dateTimeWrapper.getLocalDate().format(dateFormatter); + + assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); + } + + private String generateSqlRequest(String fieldName, long id) { + return "SELECT %s FROM jhi_date_time_wrapper where id=%d".formatted(fieldName, id); + } + + private void assertThatValueFromSqlRowSetIsEqualToExpectedValue(SqlRowSet sqlRowSet, String expectedValue) { + while (sqlRowSet.next()) { + String dbValue = sqlRowSet.getString(1); + + assertThat(dbValue).isNotNull(); + assertThat(dbValue).isEqualTo(expectedValue); + } + } +} diff --git a/src/test/java/com/example/questionbank/domain/AssertUtils.java b/src/test/java/com/example/questionbank/domain/AssertUtils.java new file mode 100644 index 0000000..1f8183c --- /dev/null +++ b/src/test/java/com/example/questionbank/domain/AssertUtils.java @@ -0,0 +1,15 @@ +package com.example.questionbank.domain; + +import java.math.BigDecimal; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Comparator; + +public class AssertUtils { + + public static Comparator zonedDateTimeSameInstant = Comparator.nullsFirst((e1, a2) -> + e1.withZoneSameInstant(ZoneOffset.UTC).compareTo(a2.withZoneSameInstant(ZoneOffset.UTC)) + ); + + public static Comparator bigDecimalCompareTo = Comparator.nullsFirst(BigDecimal::compareTo); +} diff --git a/src/test/java/com/example/questionbank/domain/AuthorityAsserts.java b/src/test/java/com/example/questionbank/domain/AuthorityAsserts.java new file mode 100644 index 0000000..cf54d49 --- /dev/null +++ b/src/test/java/com/example/questionbank/domain/AuthorityAsserts.java @@ -0,0 +1,60 @@ +package com.example.questionbank.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +public class AuthorityAsserts { + + /** + * Asserts that the entity has all properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertAuthorityAllPropertiesEquals(Authority expected, Authority actual) { + assertAuthorityAutoGeneratedPropertiesEquals(expected, actual); + assertAuthorityAllUpdatablePropertiesEquals(expected, actual); + } + + /** + * Asserts that the entity has all updatable properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertAuthorityAllUpdatablePropertiesEquals(Authority expected, Authority actual) { + assertAuthorityUpdatableFieldsEquals(expected, actual); + assertAuthorityUpdatableRelationshipsEquals(expected, actual); + } + + /** + * Asserts that the entity has all the auto generated properties (fields/relationships) set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertAuthorityAutoGeneratedPropertiesEquals(Authority expected, Authority actual) { + // empty method + } + + /** + * Asserts that the entity has all the updatable fields set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertAuthorityUpdatableFieldsEquals(Authority expected, Authority actual) { + assertThat(actual) + .as("Verify Authority relevant properties") + .satisfies(a -> assertThat(a.getName()).as("check name").isEqualTo(expected.getName())); + } + + /** + * Asserts that the entity has all the updatable relationships set. + * + * @param expected the expected entity + * @param actual the actual entity + */ + public static void assertAuthorityUpdatableRelationshipsEquals(Authority expected, Authority actual) { + // empty method + } +} diff --git a/src/test/java/com/example/questionbank/domain/AuthorityTest.java b/src/test/java/com/example/questionbank/domain/AuthorityTest.java new file mode 100644 index 0000000..662dd9a --- /dev/null +++ b/src/test/java/com/example/questionbank/domain/AuthorityTest.java @@ -0,0 +1,34 @@ +package com.example.questionbank.domain; + +import static com.example.questionbank.domain.AuthorityTestSamples.*; +import static org.assertj.core.api.Assertions.assertThat; + +import com.example.questionbank.web.rest.TestUtil; +import org.junit.jupiter.api.Test; + +class AuthorityTest { + + @Test + void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Authority.class); + Authority authority1 = getAuthoritySample1(); + Authority authority2 = new Authority(); + assertThat(authority1).isNotEqualTo(authority2); + + authority2.setName(authority1.getName()); + assertThat(authority1).isEqualTo(authority2); + + authority2 = getAuthoritySample2(); + assertThat(authority1).isNotEqualTo(authority2); + } + + @Test + void hashCodeVerifier() { + Authority authority = new Authority(); + assertThat(authority.hashCode()).isZero(); + + Authority authority1 = getAuthoritySample1(); + authority.setName(authority1.getName()); + assertThat(authority).hasSameHashCodeAs(authority1); + } +} diff --git a/src/test/java/com/example/questionbank/domain/AuthorityTestSamples.java b/src/test/java/com/example/questionbank/domain/AuthorityTestSamples.java new file mode 100644 index 0000000..c37f2d3 --- /dev/null +++ b/src/test/java/com/example/questionbank/domain/AuthorityTestSamples.java @@ -0,0 +1,18 @@ +package com.example.questionbank.domain; + +import java.util.UUID; + +public class AuthorityTestSamples { + + public static Authority getAuthoritySample1() { + return new Authority().name("name1"); + } + + public static Authority getAuthoritySample2() { + return new Authority().name("name2"); + } + + public static Authority getAuthorityRandomSampleGenerator() { + return new Authority().name(UUID.randomUUID().toString()); + } +} diff --git a/src/test/java/com/example/questionbank/management/SecurityMetersServiceTests.java b/src/test/java/com/example/questionbank/management/SecurityMetersServiceTests.java new file mode 100644 index 0000000..23e57c5 --- /dev/null +++ b/src/test/java/com/example/questionbank/management/SecurityMetersServiceTests.java @@ -0,0 +1,70 @@ +package com.example.questionbank.management; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.Collection; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class SecurityMetersServiceTests { + + private static final String INVALID_TOKENS_METER_EXPECTED_NAME = "security.authentication.invalid-tokens"; + + private MeterRegistry meterRegistry; + + private SecurityMetersService securityMetersService; + + @BeforeEach + void setup() { + meterRegistry = new SimpleMeterRegistry(); + + securityMetersService = new SecurityMetersService(meterRegistry); + } + + @Test + void testInvalidTokensCountersByCauseAreCreated() { + meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).counter(); + + meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter(); + + meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter(); + + meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter(); + + meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter(); + + Collection counters = meterRegistry.find(INVALID_TOKENS_METER_EXPECTED_NAME).counters(); + + assertThat(counters).hasSize(4); + } + + @Test + void testCountMethodsShouldBeBoundToCorrectCounters() { + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isZero(); + + securityMetersService.trackTokenExpired(); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isEqualTo(1); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter().count()).isZero(); + + securityMetersService.trackTokenUnsupported(); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter().count()).isEqualTo(1); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isZero(); + + securityMetersService.trackTokenInvalidSignature(); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isEqualTo(1); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isZero(); + + securityMetersService.trackTokenMalformed(); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(1); + } +} diff --git a/src/test/java/com/example/questionbank/repository/timezone/DateTimeWrapper.java b/src/test/java/com/example/questionbank/repository/timezone/DateTimeWrapper.java new file mode 100644 index 0000000..a9727fe --- /dev/null +++ b/src/test/java/com/example/questionbank/repository/timezone/DateTimeWrapper.java @@ -0,0 +1,135 @@ +package com.example.questionbank.repository.timezone; + +import jakarta.persistence.*; +import java.io.Serial; +import java.io.Serializable; +import java.time.*; +import java.util.Objects; + +@Entity +@Table(name = "jhi_date_time_wrapper") +public class DateTimeWrapper implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + private Long id; + + @Column(name = "instant") + private Instant instant; + + @Column(name = "local_date_time") + private LocalDateTime localDateTime; + + @Column(name = "offset_date_time") + private OffsetDateTime offsetDateTime; + + @Column(name = "zoned_date_time") + private ZonedDateTime zonedDateTime; + + @Column(name = "local_time") + private LocalTime localTime; + + @Column(name = "offset_time") + private OffsetTime offsetTime; + + @Column(name = "local_date") + private LocalDate localDate; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Instant getInstant() { + return instant; + } + + public void setInstant(Instant instant) { + this.instant = instant; + } + + public LocalDateTime getLocalDateTime() { + return localDateTime; + } + + public void setLocalDateTime(LocalDateTime localDateTime) { + this.localDateTime = localDateTime; + } + + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } + + public void setOffsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + } + + public ZonedDateTime getZonedDateTime() { + return zonedDateTime; + } + + public void setZonedDateTime(ZonedDateTime zonedDateTime) { + this.zonedDateTime = zonedDateTime; + } + + public LocalTime getLocalTime() { + return localTime; + } + + public void setLocalTime(LocalTime localTime) { + this.localTime = localTime; + } + + public OffsetTime getOffsetTime() { + return offsetTime; + } + + public void setOffsetTime(OffsetTime offsetTime) { + this.offsetTime = offsetTime; + } + + public LocalDate getLocalDate() { + return localDate; + } + + public void setLocalDate(LocalDate localDate) { + this.localDate = localDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + DateTimeWrapper dateTimeWrapper = (DateTimeWrapper) o; + return !(dateTimeWrapper.getId() == null || getId() == null) && Objects.equals(getId(), dateTimeWrapper.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + // prettier-ignore + @Override + public String toString() { + return "TimeZoneTest{" + + "id=" + id + + ", instant=" + instant + + ", localDateTime=" + localDateTime + + ", offsetDateTime=" + offsetDateTime + + ", zonedDateTime=" + zonedDateTime + + '}'; + } +} diff --git a/src/test/java/com/example/questionbank/repository/timezone/DateTimeWrapperRepository.java b/src/test/java/com/example/questionbank/repository/timezone/DateTimeWrapperRepository.java new file mode 100644 index 0000000..2bc73ab --- /dev/null +++ b/src/test/java/com/example/questionbank/repository/timezone/DateTimeWrapperRepository.java @@ -0,0 +1,10 @@ +package com.example.questionbank.repository.timezone; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * Spring Data JPA repository for the {@link DateTimeWrapper} entity. + */ +@Repository +public interface DateTimeWrapperRepository extends JpaRepository {} diff --git a/src/test/java/com/example/questionbank/security/DomainUserDetailsServiceIT.java b/src/test/java/com/example/questionbank/security/DomainUserDetailsServiceIT.java new file mode 100644 index 0000000..3b09a8d --- /dev/null +++ b/src/test/java/com/example/questionbank/security/DomainUserDetailsServiceIT.java @@ -0,0 +1,136 @@ +package com.example.questionbank.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +import com.example.questionbank.IntegrationTest; +import com.example.questionbank.domain.User; +import com.example.questionbank.repository.UserRepository; +import com.example.questionbank.service.UserService; +import java.util.Locale; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integrations tests for {@link DomainUserDetailsService}. + */ +@Transactional +@IntegrationTest +class DomainUserDetailsServiceIT { + + private static final String USER_ONE_LOGIN = "test-user-one"; + private static final String USER_ONE_EMAIL = "test-user-one@localhost"; + private static final String USER_TWO_LOGIN = "test-user-two"; + private static final String USER_TWO_EMAIL = "test-user-two@localhost"; + private static final String USER_THREE_LOGIN = "test-user-three"; + private static final String USER_THREE_EMAIL = "test-user-three@localhost"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserService userService; + + @Autowired + @Qualifier("userDetailsService") + private UserDetailsService domainUserDetailsService; + + public User getUserOne() { + User userOne = new User(); + userOne.setLogin(USER_ONE_LOGIN); + userOne.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + userOne.setActivated(true); + userOne.setEmail(USER_ONE_EMAIL); + userOne.setFirstName("userOne"); + userOne.setLastName("doe"); + userOne.setLangKey("en"); + return userOne; + } + + public User getUserTwo() { + User userTwo = new User(); + userTwo.setLogin(USER_TWO_LOGIN); + userTwo.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + userTwo.setActivated(true); + userTwo.setEmail(USER_TWO_EMAIL); + userTwo.setFirstName("userTwo"); + userTwo.setLastName("doe"); + userTwo.setLangKey("en"); + return userTwo; + } + + public User getUserThree() { + User userThree = new User(); + userThree.setLogin(USER_THREE_LOGIN); + userThree.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + userThree.setActivated(false); + userThree.setEmail(USER_THREE_EMAIL); + userThree.setFirstName("userThree"); + userThree.setLastName("doe"); + userThree.setLangKey("en"); + return userThree; + } + + @BeforeEach + void init() { + userRepository.save(getUserOne()); + userRepository.save(getUserTwo()); + userRepository.save(getUserThree()); + } + + @AfterEach + void cleanup() { + userService.deleteUser(USER_ONE_LOGIN); + userService.deleteUser(USER_TWO_LOGIN); + userService.deleteUser(USER_THREE_LOGIN); + } + + @Test + void assertThatUserCanBeFoundByLogin() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + void assertThatUserCanBeFoundByLoginIgnoreCase() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH)); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + void assertThatUserCanBeFoundByEmail() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN); + } + + @Test + void assertThatUserCanBeFoundByEmailIgnoreCase() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH)); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN); + } + + @Test + void assertThatEmailIsPrioritizedOverLogin() { + UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_EMAIL); + assertThat(userDetails).isNotNull(); + assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN); + } + + @Test + void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() { + assertThatExceptionOfType(UserNotActivatedException.class).isThrownBy(() -> + domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN) + ); + } +} diff --git a/src/test/java/com/example/questionbank/security/SecurityUtilsUnitTest.java b/src/test/java/com/example/questionbank/security/SecurityUtilsUnitTest.java new file mode 100644 index 0000000..19d232d --- /dev/null +++ b/src/test/java/com/example/questionbank/security/SecurityUtilsUnitTest.java @@ -0,0 +1,137 @@ +package com.example.questionbank.security; + +import static com.example.questionbank.security.SecurityUtils.USER_ID_CLAIM; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +/** + * Test class for the {@link SecurityUtils} utility class. + */ +class SecurityUtilsUnitTest { + + @BeforeEach + @AfterEach + void cleanup() { + SecurityContextHolder.clearContext(); + } + + @Test + void testGetCurrentUserLogin() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); + SecurityContextHolder.setContext(securityContext); + Optional login = SecurityUtils.getCurrentUserLogin(); + assertThat(login).contains("admin"); + } + + @Test + void testGetCurrentUserLoginForAnonymousUser() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + var authorities = List.of(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); + securityContext.setAuthentication(new AnonymousAuthenticationToken("key", "anonymousUser", authorities)); + SecurityContextHolder.setContext(securityContext); + Optional login = SecurityUtils.getCurrentUserLogin(); + assertThat(login).isEmpty(); + } + + @Test + void testGetCurrentUserJWT() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token")); + SecurityContextHolder.setContext(securityContext); + Optional jwt = SecurityUtils.getCurrentUserJWT(); + assertThat(jwt).contains("token"); + } + + @Test + void testGetCurrentUserJWTFromJwtCredentials() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + var now = Instant.now(); + var jwt = Jwt.withTokenValue("token").issuedAt(now).expiresAt(now.plusSeconds(60)).header("Test", "test").build(); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", jwt)); + SecurityContextHolder.setContext(securityContext); + Optional currentUserJwt = SecurityUtils.getCurrentUserJWT(); + assertThat(currentUserJwt).contains("token"); + } + + @Test + void testGetCurrentUserId() { + var userId = 1L; + var securityContext = SecurityContextHolder.createEmptyContext(); + var now = Instant.now(); + var jwt = Jwt.withTokenValue("token") + .issuedAt(now) + .expiresAt(now.plusSeconds(60)) + .claim(USER_ID_CLAIM, userId) + .header("Test", "test") + .build(); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(jwt, "token")); + SecurityContextHolder.setContext(securityContext); + var contextUserId = SecurityUtils.getCurrentUserId(); + assertThat(contextUserId.orElse(null)).isEqualTo(userId); + } + + @Test + void testIsAuthenticated() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); + SecurityContextHolder.setContext(securityContext); + boolean isAuthenticated = SecurityUtils.isAuthenticated(); + assertThat(isAuthenticated).isTrue(); + } + + @Test + void testAnonymousIsNotAuthenticated() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + var authorities = List.of(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); + SecurityContextHolder.setContext(securityContext); + boolean isAuthenticated = SecurityUtils.isAuthenticated(); + assertThat(isAuthenticated).isFalse(); + } + + @Test + void testHasCurrentUserThisAuthority() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + var authorities = List.of(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); + SecurityContextHolder.setContext(securityContext); + + assertThat(SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.USER)).isTrue(); + assertThat(SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)).isFalse(); + } + + @Test + void testHasCurrentUserAnyOfAuthorities() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + var authorities = List.of(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); + SecurityContextHolder.setContext(securityContext); + + assertThat(SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)).isTrue(); + assertThat(SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN)).isFalse(); + } + + @Test + void testHasCurrentUserNoneOfAuthorities() { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + var authorities = List.of(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); + securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); + SecurityContextHolder.setContext(securityContext); + + assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)).isFalse(); + assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN)).isTrue(); + } +} diff --git a/src/test/java/com/example/questionbank/security/jwt/AuthenticationIntegrationTest.java b/src/test/java/com/example/questionbank/security/jwt/AuthenticationIntegrationTest.java new file mode 100644 index 0000000..18d7086 --- /dev/null +++ b/src/test/java/com/example/questionbank/security/jwt/AuthenticationIntegrationTest.java @@ -0,0 +1,32 @@ +package com.example.questionbank.security.jwt; + +import com.example.questionbank.config.SecurityConfiguration; +import com.example.questionbank.config.SecurityJwtConfiguration; +import com.example.questionbank.config.WebConfigurer; +import com.example.questionbank.management.SecurityMetersService; +import com.example.questionbank.web.rest.AuthenticateController; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import org.springframework.boot.test.context.SpringBootTest; +import tech.jhipster.config.JHipsterProperties; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@SpringBootTest( + properties = { + "jhipster.security.authentication.jwt.base64-secret=fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8", + "jhipster.security.authentication.jwt.token-validity-in-seconds=60000", + }, + classes = { + JHipsterProperties.class, + WebConfigurer.class, + SecurityConfiguration.class, + SecurityJwtConfiguration.class, + SecurityMetersService.class, + AuthenticateController.class, + JwtAuthenticationTestUtils.class, + } +) +public @interface AuthenticationIntegrationTest {} diff --git a/src/test/java/com/example/questionbank/security/jwt/JwtAuthenticationTestUtils.java b/src/test/java/com/example/questionbank/security/jwt/JwtAuthenticationTestUtils.java new file mode 100644 index 0000000..a4e4940 --- /dev/null +++ b/src/test/java/com/example/questionbank/security/jwt/JwtAuthenticationTestUtils.java @@ -0,0 +1,100 @@ +package com.example.questionbank.security.jwt; + +import static com.example.questionbank.security.AuthoritiesConstants.ADMIN; +import static com.example.questionbank.security.SecurityUtils.AUTHORITIES_CLAIM; +import static com.example.questionbank.security.SecurityUtils.JWT_ALGORITHM; + +import com.nimbusds.jose.jwk.source.ImmutableSecret; +import com.nimbusds.jose.util.Base64; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.time.Instant; +import java.util.List; +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import org.springframework.context.annotation.Bean; +import org.springframework.security.crypto.codec.Hex; +import org.springframework.security.oauth2.jwt.JwsHeader; +import org.springframework.security.oauth2.jwt.JwtClaimsSet; +import org.springframework.security.oauth2.jwt.JwtEncoder; +import org.springframework.security.oauth2.jwt.JwtEncoderParameters; +import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; + +public class JwtAuthenticationTestUtils { + + public static final String BEARER = "Bearer "; + + @Bean + private MeterRegistry meterRegistry() { + return new SimpleMeterRegistry(); + } + + public static String createValidToken(String jwtKey) { + return createValidTokenForUser(jwtKey, "anonymous"); + } + + public static String createValidTokenForUser(String jwtKey, String user) { + JwtEncoder encoder = jwtEncoder(jwtKey); + + var now = Instant.now(); + + JwtClaimsSet claims = JwtClaimsSet.builder() + .issuedAt(now) + .expiresAt(now.plusSeconds(60)) + .subject(user) + .claims(customClaim -> customClaim.put(AUTHORITIES_CLAIM, List.of(ADMIN))) + .build(); + + JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build(); + return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue(); + } + + public static String createTokenWithDifferentSignature() { + JwtEncoder encoder = jwtEncoder("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"); + + var now = Instant.now(); + var past = now.plusSeconds(60); + + JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(now).expiresAt(past).subject("anonymous").build(); + + JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build(); + return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue(); + } + + public static String createExpiredToken(String jwtKey) { + JwtEncoder encoder = jwtEncoder(jwtKey); + + var now = Instant.now(); + var past = now.minusSeconds(600); + + JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(past).expiresAt(past.plusSeconds(1)).subject("anonymous").build(); + + JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build(); + return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue(); + } + + public static String createInvalidToken(String jwtKey) { + return createValidToken(jwtKey).substring(1); + } + + public static String createSignedInvalidJwt(String jwtKey) throws Exception { + return calculateHMAC("foo", jwtKey); + } + + private static JwtEncoder jwtEncoder(String jwtKey) { + return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey(jwtKey))); + } + + private static SecretKey getSecretKey(String jwtKey) { + byte[] keyBytes = Base64.from(jwtKey).decode(); + return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName()); + } + + private static String calculateHMAC(String data, String key) throws Exception { + SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.from(key).decode(), "HmacSHA512"); + Mac mac = Mac.getInstance("HmacSHA512"); + mac.init(secretKeySpec); + return String.copyValueOf(Hex.encode(mac.doFinal(data.getBytes()))); + } +} diff --git a/src/test/java/com/example/questionbank/security/jwt/TokenAuthenticationIT.java b/src/test/java/com/example/questionbank/security/jwt/TokenAuthenticationIT.java new file mode 100644 index 0000000..035620c --- /dev/null +++ b/src/test/java/com/example/questionbank/security/jwt/TokenAuthenticationIT.java @@ -0,0 +1,55 @@ +package com.example.questionbank.security.jwt; + +import static com.example.questionbank.security.jwt.JwtAuthenticationTestUtils.*; +import static org.springframework.http.HttpHeaders.AUTHORIZATION; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +@AutoConfigureMockMvc +@AuthenticationIntegrationTest +class TokenAuthenticationIT { + + @Autowired + private MockMvc mvc; + + @Value("${jhipster.security.authentication.jwt.base64-secret}") + private String jwtKey; + + @Test + void testLoginWithValidToken() throws Exception { + expectOk(createValidToken(jwtKey)); + } + + @Test + void testReturnFalseWhenJWThasInvalidSignature() throws Exception { + expectUnauthorized(createTokenWithDifferentSignature()); + } + + @Test + void testReturnFalseWhenJWTisMalformed() throws Exception { + expectUnauthorized(createSignedInvalidJwt(jwtKey)); + } + + @Test + void testReturnFalseWhenJWTisExpired() throws Exception { + expectUnauthorized(createExpiredToken(jwtKey)); + } + + private void expectOk(String token) throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token)).andExpect( + status().isNoContent() + ); + } + + private void expectUnauthorized(String token) throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token)).andExpect( + status().isUnauthorized() + ); + } +} diff --git a/src/test/java/com/example/questionbank/security/jwt/TokenAuthenticationSecurityMetersIT.java b/src/test/java/com/example/questionbank/security/jwt/TokenAuthenticationSecurityMetersIT.java new file mode 100644 index 0000000..fc8f9e8 --- /dev/null +++ b/src/test/java/com/example/questionbank/security/jwt/TokenAuthenticationSecurityMetersIT.java @@ -0,0 +1,88 @@ +package com.example.questionbank.security.jwt; + +import static com.example.questionbank.security.jwt.JwtAuthenticationTestUtils.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.http.HttpHeaders.AUTHORIZATION; + +import io.micrometer.core.instrument.Counter; +import io.micrometer.core.instrument.MeterRegistry; +import java.util.Collection; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +@AutoConfigureMockMvc +@AuthenticationIntegrationTest +class TokenAuthenticationSecurityMetersIT { + + private static final String INVALID_TOKENS_METER_EXPECTED_NAME = "security.authentication.invalid-tokens"; + + @Autowired + private MockMvc mvc; + + @Value("${jhipster.security.authentication.jwt.base64-secret}") + private String jwtKey; + + @Autowired + private MeterRegistry meterRegistry; + + @Test + void testValidTokenShouldNotCountAnything() throws Exception { + Collection counters = meterRegistry.find(INVALID_TOKENS_METER_EXPECTED_NAME).counters(); + + var count = aggregate(counters); + + tryToAuthenticate(createValidToken(jwtKey)); + + assertThat(aggregate(counters)).isEqualTo(count); + } + + @Test + void testTokenExpiredCount() throws Exception { + var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count(); + + tryToAuthenticate(createExpiredToken(jwtKey)); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isEqualTo(count + 1); + } + + @Test + void testTokenSignatureInvalidCount() throws Exception { + var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count(); + + tryToAuthenticate(createTokenWithDifferentSignature()); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isEqualTo( + count + 1 + ); + } + + @Test + void testTokenMalformedCount() throws Exception { + var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count(); + + tryToAuthenticate(createSignedInvalidJwt(jwtKey)); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(count + 1); + } + + @Test + void testTokenInvalidCount() throws Exception { + var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count(); + + tryToAuthenticate(createInvalidToken(jwtKey)); + + assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(count + 1); + } + + private void tryToAuthenticate(String token) throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token)); + } + + private double aggregate(Collection counters) { + return counters.stream().mapToDouble(Counter::count).sum(); + } +} diff --git a/src/test/java/com/example/questionbank/service/MailServiceIT.java b/src/test/java/com/example/questionbank/service/MailServiceIT.java new file mode 100644 index 0000000..bc70910 --- /dev/null +++ b/src/test/java/com/example/questionbank/service/MailServiceIT.java @@ -0,0 +1,237 @@ +package com.example.questionbank.service; + +import static org.assertj.core.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import com.example.questionbank.IntegrationTest; +import com.example.questionbank.config.Constants; +import com.example.questionbank.domain.User; +import jakarta.mail.Multipart; +import jakarta.mail.Session; +import jakarta.mail.internet.MimeBodyPart; +import jakarta.mail.internet.MimeMessage; +import jakarta.mail.internet.MimeMultipart; +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mail.MailSendException; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import tech.jhipster.config.JHipsterProperties; + +/** + * Integration tests for {@link MailService}. + */ +@ExtendWith(MockitoExtension.class) +@IntegrationTest +class MailServiceIT { + + private static final String[] languages = { + // jhipster-needle-i18n-language-constant-start + "en", + // jhipster-needle-i18n-language-constant - JHipster will add/remove languages in this array + }; + private static final Pattern PATTERN_LOCALE_3 = Pattern.compile("([a-z]{2})-([a-zA-Z]{4})-([a-z]{2})"); + private static final Pattern PATTERN_LOCALE_2 = Pattern.compile("([a-z]{2})-([a-z]{2})"); + + @Autowired + private JHipsterProperties jHipsterProperties; + + @MockitoBean + private JavaMailSender javaMailSender; + + @Captor + private ArgumentCaptor messageCaptor; + + @Autowired + private MailService mailService; + + @BeforeEach + void setup() { + doNothing().when(javaMailSender).send(any(MimeMessage.class)); + when(javaMailSender.createMimeMessage()).thenReturn(new MimeMessage((Session) null)); + } + + @Test + void testSendEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent()).isInstanceOf(String.class); + assertThat(message.getContent()).hasToString("testContent"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); + } + + @Test + void testSendHtmlEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent()).isInstanceOf(String.class); + assertThat(message.getContent()).hasToString("testContent"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + void testSendMultipartEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + MimeMultipart mp = (MimeMultipart) message.getContent(); + MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + part.writeTo(aos); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent()).isInstanceOf(Multipart.class); + assertThat(aos).hasToString("\r\ntestContent"); + assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); + } + + @Test + void testSendMultipartHtmlEmail() throws Exception { + mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + MimeMultipart mp = (MimeMultipart) message.getContent(); + MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + part.writeTo(aos); + assertThat(message.getSubject()).isEqualTo("testSubject"); + assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com"); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent()).isInstanceOf(Multipart.class); + assertThat(aos).hasToString("\r\ntestContent"); + assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + void testSendEmailFromTemplate() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getSubject()).isEqualTo("test title"); + assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail()); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("test title, http://127.0.0.1:8080, john\n"); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + void testSendActivationEmail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendActivationEmail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail()); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + void testCreationEmail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendCreationEmail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail()); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + void testSendPasswordResetMail() throws Exception { + User user = new User(); + user.setLangKey(Constants.DEFAULT_LANGUAGE); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + mailService.sendPasswordResetMail(user); + verify(javaMailSender).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail()); + assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom()); + assertThat(message.getContent().toString()).isNotEmpty(); + assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); + } + + @Test + void testSendEmailWithException() { + doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class)); + assertDoesNotThrow(() -> mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false)); + } + + @Test + void testSendLocalizedEmailForAllSupportedLanguages() throws Exception { + User user = new User(); + user.setLogin("john"); + user.setEmail("john.doe@example.com"); + for (String langKey : languages) { + user.setLangKey(langKey); + mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title"); + verify(javaMailSender, atLeastOnce()).send(messageCaptor.capture()); + MimeMessage message = messageCaptor.getValue(); + + String propertyFilePath = "i18n/messages_" + getMessageSourceSuffixForLanguage(langKey) + ".properties"; + URL resource = this.getClass().getClassLoader().getResource(propertyFilePath); + Path filePath = Path.of(resource.toURI()); + Properties properties = new Properties(); + properties.load(new InputStreamReader(Files.newInputStream(filePath), Charset.forName("UTF-8"))); + + String emailTitle = (String) properties.get("email.test.title"); + assertThat(message.getSubject()).isEqualTo(emailTitle); + assertThat(message.getContent().toString()).isEqualToNormalizingNewlines( + "" + emailTitle + ", http://127.0.0.1:8080, john\n" + ); + } + } + + /** + * Convert a lang key to the Java locale. + */ + private String getMessageSourceSuffixForLanguage(String langKey) { + String javaLangKey = langKey; + Matcher matcher2 = PATTERN_LOCALE_2.matcher(langKey); + if (matcher2.matches()) { + javaLangKey = matcher2.group(1) + "_" + matcher2.group(2).toUpperCase(); + } + Matcher matcher3 = PATTERN_LOCALE_3.matcher(langKey); + if (matcher3.matches()) { + javaLangKey = matcher3.group(1) + "_" + matcher3.group(2) + "_" + matcher3.group(3).toUpperCase(); + } + return javaLangKey; + } +} diff --git a/src/test/java/com/example/questionbank/service/UserServiceIT.java b/src/test/java/com/example/questionbank/service/UserServiceIT.java new file mode 100644 index 0000000..eee49d1 --- /dev/null +++ b/src/test/java/com/example/questionbank/service/UserServiceIT.java @@ -0,0 +1,192 @@ +package com.example.questionbank.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +import com.example.questionbank.IntegrationTest; +import com.example.questionbank.domain.User; +import com.example.questionbank.repository.UserRepository; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Optional; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.auditing.AuditingHandler; +import org.springframework.data.auditing.DateTimeProvider; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.annotation.Transactional; +import tech.jhipster.security.RandomUtil; + +/** + * Integration tests for {@link UserService}. + */ +@IntegrationTest +@Transactional +class UserServiceIT { + + private static final String DEFAULT_LOGIN = "johndoe_service"; + + private static final String DEFAULT_EMAIL = "johndoe_service@localhost"; + + private static final String DEFAULT_FIRSTNAME = "john"; + + private static final String DEFAULT_LASTNAME = "doe"; + + private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; + + private static final String DEFAULT_LANGKEY = "dummy"; + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserService userService; + + @Autowired + private AuditingHandler auditingHandler; + + @MockitoBean + private DateTimeProvider dateTimeProvider; + + private User user; + + private Long numberOfUsers; + + @BeforeEach + void init() { + numberOfUsers = userRepository.count(); + user = new User(); + user.setLogin(DEFAULT_LOGIN); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setActivated(true); + user.setEmail(DEFAULT_EMAIL); + user.setFirstName(DEFAULT_FIRSTNAME); + user.setLastName(DEFAULT_LASTNAME); + user.setImageUrl(DEFAULT_IMAGEURL); + user.setLangKey(DEFAULT_LANGKEY); + + when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now())); + auditingHandler.setDateTimeProvider(dateTimeProvider); + } + + @AfterEach + void cleanupAndCheck() { + userService.deleteUser(DEFAULT_LOGIN); + assertThat(userRepository.count()).isEqualTo(numberOfUsers); + numberOfUsers = null; + } + + @Test + @Transactional + void assertThatUserMustExistToResetPassword() { + userRepository.saveAndFlush(user); + Optional maybeUser = userService.requestPasswordReset("invalid.login@localhost"); + assertThat(maybeUser).isNotPresent(); + + maybeUser = userService.requestPasswordReset(user.getEmail()); + assertThat(maybeUser).isPresent(); + assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail()); + assertThat(maybeUser.orElse(null).getResetDate()).isNotNull(); + assertThat(maybeUser.orElse(null).getResetKey()).isNotNull(); + } + + @Test + @Transactional + void assertThatOnlyActivatedUserCanRequestPasswordReset() { + user.setActivated(false); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.requestPasswordReset(user.getLogin()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + void assertThatResetKeyMustNotBeOlderThan24Hours() { + Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); + String resetKey = RandomUtil.generateResetKey(); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey(resetKey); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + void assertThatResetKeyMustBeValid() { + Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey("1234"); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isNotPresent(); + userRepository.delete(user); + } + + @Test + @Transactional + void assertThatUserCanResetPassword() { + String oldPassword = user.getPassword(); + Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS); + String resetKey = RandomUtil.generateResetKey(); + user.setActivated(true); + user.setResetDate(daysAgo); + user.setResetKey(resetKey); + userRepository.saveAndFlush(user); + + Optional maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()); + assertThat(maybeUser).isPresent(); + assertThat(maybeUser.orElse(null).getResetDate()).isNull(); + assertThat(maybeUser.orElse(null).getResetKey()).isNull(); + assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword); + + userRepository.delete(user); + } + + @Test + @Transactional + void assertThatNotActivatedUsersWithNotNullActivationKeyCreatedBefore3DaysAreDeleted() { + Instant now = Instant.now(); + when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS))); + user.setActivated(false); + user.setActivationKey(RandomStringUtils.insecure().next(20)); + User dbUser = userRepository.saveAndFlush(user); + dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); + userRepository.saveAndFlush(user); + Instant threeDaysAgo = now.minus(3, ChronoUnit.DAYS); + List users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo); + assertThat(users).isNotEmpty(); + userService.removeNotActivatedUsers(); + users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo); + assertThat(users).isEmpty(); + } + + @Test + @Transactional + void assertThatNotActivatedUsersWithNullActivationKeyCreatedBefore3DaysAreNotDeleted() { + Instant now = Instant.now(); + when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS))); + user.setActivated(false); + User dbUser = userRepository.saveAndFlush(user); + dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); + userRepository.saveAndFlush(user); + Instant threeDaysAgo = now.minus(3, ChronoUnit.DAYS); + List users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo); + assertThat(users).isEmpty(); + userService.removeNotActivatedUsers(); + Optional maybeDbUser = userRepository.findById(dbUser.getId()); + assertThat(maybeDbUser).contains(dbUser); + } +} diff --git a/src/test/java/com/example/questionbank/service/mapper/UserMapperTest.java b/src/test/java/com/example/questionbank/service/mapper/UserMapperTest.java new file mode 100644 index 0000000..f0082fa --- /dev/null +++ b/src/test/java/com/example/questionbank/service/mapper/UserMapperTest.java @@ -0,0 +1,180 @@ +package com.example.questionbank.service.mapper; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.example.questionbank.domain.Authority; +import com.example.questionbank.domain.User; +import com.example.questionbank.security.AuthoritiesConstants; +import com.example.questionbank.service.dto.AdminUserDTO; +import com.example.questionbank.service.dto.UserDTO; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for {@link UserMapper}. + */ +class UserMapperTest { + + private static final String DEFAULT_LOGIN = "johndoe"; + private static final Long DEFAULT_ID = 1L; + + private UserMapper userMapper; + private User user; + private AdminUserDTO userDto; + + @BeforeEach + void init() { + userMapper = new UserMapper(); + user = new User(); + user.setLogin(DEFAULT_LOGIN); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setActivated(true); + user.setEmail("johndoe@localhost"); + user.setFirstName("john"); + user.setLastName("doe"); + user.setImageUrl("image_url"); + Instant creationTimestamp = Instant.ofEpochMilli(1792485949603L); + user.setCreatedBy(DEFAULT_LOGIN); + user.setCreatedDate(creationTimestamp); + user.setLastModifiedBy(DEFAULT_LOGIN); + user.setLastModifiedDate(creationTimestamp); + user.setLangKey("en"); + + Set authorities = new HashSet<>(); + Authority authority = new Authority(); + authority.setName(AuthoritiesConstants.USER); + authorities.add(authority); + user.setAuthorities(authorities); + + userDto = new AdminUserDTO(user); + } + + @Test + void testUserToUserDTO() { + AdminUserDTO convertedUserDto = userMapper.userToAdminUserDTO(user); + + assertThat(convertedUserDto.getId()).isEqualTo(user.getId()); + assertThat(convertedUserDto.getLogin()).isEqualTo(user.getLogin()); + assertThat(convertedUserDto.getFirstName()).isEqualTo(user.getFirstName()); + assertThat(convertedUserDto.getLastName()).isEqualTo(user.getLastName()); + assertThat(convertedUserDto.getEmail()).isEqualTo(user.getEmail()); + assertThat(convertedUserDto.isActivated()).isEqualTo(user.isActivated()); + assertThat(convertedUserDto.getImageUrl()).isEqualTo(user.getImageUrl()); + assertThat(convertedUserDto.getCreatedBy()).isEqualTo(user.getCreatedBy()); + assertThat(convertedUserDto.getCreatedDate()).isEqualTo(user.getCreatedDate()); + assertThat(convertedUserDto.getLastModifiedBy()).isEqualTo(user.getLastModifiedBy()); + assertThat(convertedUserDto.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate()); + assertThat(convertedUserDto.getLangKey()).isEqualTo(user.getLangKey()); + assertThat(convertedUserDto.getAuthorities()).containsExactly(AuthoritiesConstants.USER); + } + + @Test + void testUserDTOtoUser() { + User convertedUser = userMapper.userDTOToUser(userDto); + + assertThat(convertedUser.getId()).isEqualTo(userDto.getId()); + assertThat(convertedUser.getLogin()).isEqualTo(userDto.getLogin()); + assertThat(convertedUser.getFirstName()).isEqualTo(userDto.getFirstName()); + assertThat(convertedUser.getLastName()).isEqualTo(userDto.getLastName()); + assertThat(convertedUser.getEmail()).isEqualTo(userDto.getEmail()); + assertThat(convertedUser.isActivated()).isEqualTo(userDto.isActivated()); + assertThat(convertedUser.getImageUrl()).isEqualTo(userDto.getImageUrl()); + assertThat(convertedUser.getLangKey()).isEqualTo(userDto.getLangKey()); + assertThat(convertedUser.getCreatedBy()).isEqualTo(userDto.getCreatedBy()); + assertThat(convertedUser.getCreatedDate()).isEqualTo(userDto.getCreatedDate()); + assertThat(convertedUser.getLastModifiedBy()).isEqualTo(userDto.getLastModifiedBy()); + assertThat(convertedUser.getLastModifiedDate()).isEqualTo(userDto.getLastModifiedDate()); + assertThat(convertedUser.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER); + } + + @Test + void usersToUserDTOsShouldMapOnlyNonNullUsers() { + List users = new ArrayList<>(); + users.add(user); + users.add(null); + + List userDTOS = userMapper.usersToUserDTOs(users); + + assertThat(userDTOS).isNotEmpty().size().isEqualTo(1); + } + + @Test + void userDTOsToUsersShouldMapOnlyNonNullUsers() { + List usersDto = new ArrayList<>(); + usersDto.add(userDto); + usersDto.add(null); + + List users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty().size().isEqualTo(1); + } + + @Test + void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain() { + Set authoritiesAsString = new HashSet<>(); + authoritiesAsString.add("ADMIN"); + userDto.setAuthorities(authoritiesAsString); + + List usersDto = new ArrayList<>(); + usersDto.add(userDto); + + List users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty().size().isEqualTo(1); + assertThat(users.getFirst().getAuthorities()).isNotNull(); + assertThat(users.getFirst().getAuthorities()).isNotEmpty(); + assertThat(users.getFirst().getAuthorities().iterator().next().getName()).isEqualTo("ADMIN"); + } + + @Test + void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { + userDto.setAuthorities(null); + + List usersDto = new ArrayList<>(); + usersDto.add(userDto); + + List users = userMapper.userDTOsToUsers(usersDto); + + assertThat(users).isNotEmpty().size().isEqualTo(1); + assertThat(users.getFirst().getAuthorities()).isNotNull(); + assertThat(users.getFirst().getAuthorities()).isEmpty(); + } + + @Test + void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities() { + User convertedUser = userMapper.userDTOToUser(userDto); + + assertThat(convertedUser).isNotNull(); + assertThat(convertedUser.getAuthorities()).isNotNull(); + assertThat(convertedUser.getAuthorities()).isNotEmpty(); + assertThat(convertedUser.getAuthorities().iterator().next().getName()).isEqualTo(AuthoritiesConstants.USER); + } + + @Test + void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { + userDto.setAuthorities(null); + + User persistUser = userMapper.userDTOToUser(userDto); + + assertThat(persistUser).isNotNull(); + assertThat(persistUser.getAuthorities()).isNotNull(); + assertThat(persistUser.getAuthorities()).isEmpty(); + } + + @Test + void userDTOToUserMapWithNullUserShouldReturnNull() { + assertThat(userMapper.userDTOToUser(null)).isNull(); + } + + @Test + void testUserFromId() { + assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID); + assertThat(userMapper.userFromId(null)).isNull(); + } +} diff --git a/src/test/java/com/example/questionbank/web/filter/SpaWebFilterIT.java b/src/test/java/com/example/questionbank/web/filter/SpaWebFilterIT.java new file mode 100644 index 0000000..9d0d29b --- /dev/null +++ b/src/test/java/com/example/questionbank/web/filter/SpaWebFilterIT.java @@ -0,0 +1,88 @@ +package com.example.questionbank.web.filter; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.example.questionbank.IntegrationTest; +import com.example.questionbank.security.AuthoritiesConstants; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; + +@AutoConfigureMockMvc +@WithMockUser +@IntegrationTest +class SpaWebFilterIT { + + @Autowired + private MockMvc mockMvc; + + @Test + void testFilterForwardsToIndex() throws Exception { + mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); + } + + @Test + void testFilterDoesNotForwardToIndexForApi() throws Exception { + mockMvc.perform(get("/api/authenticate")).andExpect(status().is2xxSuccessful()).andExpect(forwardedUrl(null)); + } + + @Test + @WithMockUser(authorities = AuthoritiesConstants.ADMIN) + void testFilterDoesNotForwardToIndexForV3ApiDocs() throws Exception { + mockMvc.perform(get("/v3/api-docs")).andExpect(status().isOk()).andExpect(forwardedUrl(null)); + } + + @Test + void testFilterDoesNotForwardToIndexForDotFile() throws Exception { + mockMvc.perform(get("/file.js")).andExpect(status().isNotFound()); + } + + @Test + void getBackendEndpoint() throws Exception { + mockMvc.perform(get("/test")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); + } + + @Test + void forwardUnmappedFirstLevelMapping() throws Exception { + mockMvc.perform(get("/first-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); + } + + @Test + void forwardUnmappedSecondLevelMapping() throws Exception { + mockMvc.perform(get("/first-level/second-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); + } + + @Test + void forwardUnmappedThirdLevelMapping() throws Exception { + mockMvc.perform(get("/first-level/second-level/third-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); + } + + @Test + void forwardUnmappedDeepMapping() throws Exception { + mockMvc.perform(get("/1/2/3/4/5/6/7/8/9/10")).andExpect(forwardedUrl("/index.html")); + } + + @Test + void getUnmappedFirstLevelFile() throws Exception { + mockMvc.perform(get("/foo.js")).andExpect(status().isNotFound()); + } + + /** + * This test verifies that any files that aren't permitted by Spring Security will be forbidden. + * If you want to change this to return isNotFound(), you need to add a request mapping that + * allows this file in SecurityConfiguration. + */ + @Test + void getUnmappedSecondLevelFile() throws Exception { + mockMvc.perform(get("/foo/bar.js")).andExpect(status().isForbidden()); + } + + @Test + void getUnmappedThirdLevelFile() throws Exception { + mockMvc.perform(get("/foo/another/bar.js")).andExpect(status().isForbidden()); + } +} diff --git a/src/test/java/com/example/questionbank/web/rest/AccountResourceIT.java b/src/test/java/com/example/questionbank/web/rest/AccountResourceIT.java new file mode 100644 index 0000000..43903fe --- /dev/null +++ b/src/test/java/com/example/questionbank/web/rest/AccountResourceIT.java @@ -0,0 +1,790 @@ +package com.example.questionbank.web.rest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.example.questionbank.IntegrationTest; +import com.example.questionbank.config.Constants; +import com.example.questionbank.domain.User; +import com.example.questionbank.repository.AuthorityRepository; +import com.example.questionbank.repository.UserRepository; +import com.example.questionbank.security.AuthoritiesConstants; +import com.example.questionbank.service.UserService; +import com.example.questionbank.service.dto.AdminUserDTO; +import com.example.questionbank.service.dto.PasswordChangeDTO; +import com.example.questionbank.web.rest.vm.KeyAndPasswordVM; +import com.example.questionbank.web.rest.vm.ManagedUserVM; +import java.time.Instant; +import java.util.*; +import java.util.stream.Stream; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; +import tools.jackson.databind.ObjectMapper; + +/** + * Integration tests for the {@link AccountResource} REST controller. + */ +@AutoConfigureMockMvc +@IntegrationTest +class AccountResourceIT { + + static final String TEST_USER_LOGIN = "test"; + + @Autowired + private ObjectMapper om; + + @Autowired + private UserRepository userRepository; + + @Autowired + private AuthorityRepository authorityRepository; + + @Autowired + private UserService userService; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private MockMvc restAccountMockMvc; + + private Long numberOfUsers; + + @BeforeEach + void countUsers() { + numberOfUsers = userRepository.count(); + } + + @AfterEach + void cleanupAndCheck() { + assertThat(userRepository.count()).isEqualTo(numberOfUsers); + numberOfUsers = null; + } + + @Test + @WithUnauthenticatedMockUser + void testNonAuthenticatedUser() throws Exception { + restAccountMockMvc.perform(get("/api/authenticate")).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(TEST_USER_LOGIN) + void testAuthenticatedUser() throws Exception { + restAccountMockMvc.perform(get("/api/authenticate").with(request -> request)).andExpect(status().isNoContent()); + } + + @Test + @WithMockUser(TEST_USER_LOGIN) + void testGetExistingAccount() throws Exception { + Set authorities = new HashSet<>(); + authorities.add(AuthoritiesConstants.ADMIN); + + AdminUserDTO user = new AdminUserDTO(); + user.setLogin(TEST_USER_LOGIN); + user.setFirstName("john"); + user.setLastName("doe"); + user.setEmail("john.doe@jhipster.com"); + user.setImageUrl("http://placehold.it/50x50"); + user.setLangKey("en"); + user.setAuthorities(authorities); + userService.createUser(user); + + restAccountMockMvc + .perform(get("/api/account").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.login").value(TEST_USER_LOGIN)) + .andExpect(jsonPath("$.firstName").value("john")) + .andExpect(jsonPath("$.lastName").value("doe")) + .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) + .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) + .andExpect(jsonPath("$.langKey").value("en")) + .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); + + userService.deleteUser(TEST_USER_LOGIN); + } + + @Test + void testGetUnknownAccount() throws Exception { + restAccountMockMvc.perform(get("/api/account").accept(MediaType.APPLICATION_PROBLEM_JSON)).andExpect(status().isUnauthorized()); + } + + @Test + @Transactional + void testRegisterValid() throws Exception { + ManagedUserVM validUser = new ManagedUserVM(); + validUser.setLogin("test-register-valid"); + validUser.setPassword("password"); + validUser.setFirstName("Alice"); + validUser.setLastName("Test"); + validUser.setEmail("test-register-valid@example.com"); + validUser.setImageUrl("http://placehold.it/50x50"); + validUser.setLangKey(Constants.DEFAULT_LANGUAGE); + validUser.setAuthorities(Set.of(AuthoritiesConstants.USER)); + assertThat(userRepository.findOneByLogin("test-register-valid")).isEmpty(); + + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(validUser))) + .andExpect(status().isCreated()); + + assertThat(userRepository.findOneByLogin("test-register-valid")).isPresent(); + + userService.deleteUser("test-register-valid"); + } + + @Test + @Transactional + void testRegisterInvalidLogin() throws Exception { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin("funky-log(n"); // <-- invalid + invalidUser.setPassword("password"); + invalidUser.setFirstName("Funky"); + invalidUser.setLastName("One"); + invalidUser.setEmail("funky@example.com"); + invalidUser.setActivated(true); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); + assertThat(user).isEmpty(); + } + + static Stream invalidUsers() { + return Stream.of( + createInvalidUser("bob", "password", "Bob", "Green", "invalid", true), // <-- invalid + createInvalidUser("bob", "123", "Bob", "Green", "bob@example.com", true), // password with only 3 digits + createInvalidUser("bob", null, "Bob", "Green", "bob@example.com", true) // invalid null password + ); + } + + @ParameterizedTest + @MethodSource("invalidUsers") + @Transactional + void testRegisterInvalidUsers(ManagedUserVM invalidUser) throws Exception { + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(invalidUser))) + .andExpect(status().isBadRequest()); + + Optional user = userRepository.findOneByLogin("bob"); + assertThat(user).isEmpty(); + } + + private static ManagedUserVM createInvalidUser( + String login, + String password, + String firstName, + String lastName, + String email, + boolean activated + ) { + ManagedUserVM invalidUser = new ManagedUserVM(); + invalidUser.setLogin(login); + invalidUser.setPassword(password); + invalidUser.setFirstName(firstName); + invalidUser.setLastName(lastName); + invalidUser.setEmail(email); + invalidUser.setActivated(activated); + invalidUser.setImageUrl("http://placehold.it/50x50"); + invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); + invalidUser.setAuthorities(Set.of(AuthoritiesConstants.USER)); + return invalidUser; + } + + @Test + @Transactional + void testRegisterDuplicateLogin() throws Exception { + // First registration + ManagedUserVM firstUser = new ManagedUserVM(); + firstUser.setLogin("alice"); + firstUser.setPassword("password"); + firstUser.setFirstName("Alice"); + firstUser.setLastName("Something"); + firstUser.setEmail("alice@example.com"); + firstUser.setImageUrl("http://placehold.it/50x50"); + firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); + firstUser.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + // Duplicate login, different email + ManagedUserVM secondUser = new ManagedUserVM(); + secondUser.setLogin(firstUser.getLogin()); + secondUser.setPassword(firstUser.getPassword()); + secondUser.setFirstName(firstUser.getFirstName()); + secondUser.setLastName(firstUser.getLastName()); + secondUser.setEmail("alice2@example.com"); + secondUser.setImageUrl(firstUser.getImageUrl()); + secondUser.setLangKey(firstUser.getLangKey()); + secondUser.setCreatedBy(firstUser.getCreatedBy()); + secondUser.setCreatedDate(firstUser.getCreatedDate()); + secondUser.setLastModifiedBy(firstUser.getLastModifiedBy()); + secondUser.setLastModifiedDate(firstUser.getLastModifiedDate()); + secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // First user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(firstUser))) + .andExpect(status().isCreated()); + + // Second (non activated) user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(secondUser))) + .andExpect(status().isCreated()); + + Optional testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); + assertThat(testUser).isPresent(); + testUser.orElseThrow().setActivated(true); + userRepository.save(testUser.orElseThrow()); + + // Second (already activated) user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(secondUser))) + .andExpect(status().is4xxClientError()); + + userService.deleteUser("alice"); + } + + @Test + @Transactional + void testRegisterDuplicateEmail() throws Exception { + // First user + ManagedUserVM firstUser = new ManagedUserVM(); + firstUser.setLogin("test-register-duplicate-email"); + firstUser.setPassword("password"); + firstUser.setFirstName("Alice"); + firstUser.setLastName("Test"); + firstUser.setEmail("test-register-duplicate-email@example.com"); + firstUser.setImageUrl("http://placehold.it/50x50"); + firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); + firstUser.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + // Register first user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(firstUser))) + .andExpect(status().isCreated()); + + Optional testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); + assertThat(testUser1).isPresent(); + + // Duplicate email, different login + ManagedUserVM secondUser = new ManagedUserVM(); + secondUser.setLogin("test-register-duplicate-email-2"); + secondUser.setPassword(firstUser.getPassword()); + secondUser.setFirstName(firstUser.getFirstName()); + secondUser.setLastName(firstUser.getLastName()); + secondUser.setEmail(firstUser.getEmail()); + secondUser.setImageUrl(firstUser.getImageUrl()); + secondUser.setLangKey(firstUser.getLangKey()); + secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // Register second (non activated) user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(secondUser))) + .andExpect(status().isCreated()); + + Optional testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); + assertThat(testUser2).isEmpty(); + + Optional testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); + assertThat(testUser3).isPresent(); + + // Duplicate email - with uppercase email address + ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM(); + userWithUpperCaseEmail.setId(firstUser.getId()); + userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3"); + userWithUpperCaseEmail.setPassword(firstUser.getPassword()); + userWithUpperCaseEmail.setFirstName(firstUser.getFirstName()); + userWithUpperCaseEmail.setLastName(firstUser.getLastName()); + userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com"); + userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl()); + userWithUpperCaseEmail.setLangKey(firstUser.getLangKey()); + userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); + + // Register third (not activated) user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userWithUpperCaseEmail))) + .andExpect(status().isCreated()); + + Optional testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); + assertThat(testUser4).isPresent(); + assertThat(testUser4.orElseThrow().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); + + testUser4.orElseThrow().setActivated(true); + userService.updateUser(new AdminUserDTO(testUser4.orElseThrow())); + + // Register 4th (already activated) user + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(secondUser))) + .andExpect(status().is4xxClientError()); + + userService.deleteUser("test-register-duplicate-email-3"); + } + + @Test + @Transactional + void testRegisterAdminIsIgnored() throws Exception { + ManagedUserVM validUser = new ManagedUserVM(); + validUser.setLogin("badguy"); + validUser.setPassword("password"); + validUser.setFirstName("Bad"); + validUser.setLastName("Guy"); + validUser.setEmail("badguy@example.com"); + validUser.setActivated(true); + validUser.setImageUrl("http://placehold.it/50x50"); + validUser.setLangKey(Constants.DEFAULT_LANGUAGE); + validUser.setAuthorities(Set.of(AuthoritiesConstants.ADMIN)); + + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(validUser))) + .andExpect(status().isCreated()); + + Optional userDup = userRepository.findOneWithAuthoritiesByLogin("badguy"); + assertThat(userDup).isPresent(); + assertThat(userDup.orElseThrow().getAuthorities()) + .hasSize(1) + .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).orElseThrow()); + + userService.deleteUser("badguy"); + } + + @Test + @Transactional + void testActivateAccount() throws Exception { + final String activationKey = "some activation key"; + User user = new User(); + user.setLogin("activate-account"); + user.setEmail("activate-account@example.com"); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setActivated(false); + user.setActivationKey(activationKey); + + userRepository.saveAndFlush(user); + + restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey)).andExpect(status().isOk()); + + user = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(user.isActivated()).isTrue(); + + userService.deleteUser("activate-account"); + } + + @Test + @Transactional + void testActivateAccountWithWrongKey() throws Exception { + restAccountMockMvc.perform(get("/api/activate?key=wrongActivationKey")).andExpect(status().isBadRequest()); + } + + @Test + @Transactional + @WithMockUser("save-account") + void testSaveAccount() throws Exception { + User user = new User(); + user.setLogin("save-account"); + user.setEmail("save-account@example.com"); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setActivated(true); + userRepository.saveAndFlush(user); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-account@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.ADMIN)); + + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneWithAuthoritiesByLogin(user.getLogin()).orElse(null); + assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); + assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); + assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); + assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey()); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl()); + assertThat(updatedUser.isActivated()).isTrue(); + assertThat(updatedUser.getAuthorities()).isEmpty(); + + userService.deleteUser("save-account"); + } + + @Test + @Transactional + @WithMockUser("save-invalid-email") + void testSaveInvalidEmail() throws Exception { + User user = new User(); + user.setLogin("save-invalid-email"); + user.setEmail("save-invalid-email@example.com"); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setActivated(true); + + userRepository.saveAndFlush(user); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("invalid email"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.ADMIN)); + + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isBadRequest()); + + assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); + + userService.deleteUser("save-invalid-email"); + } + + @Test + @Transactional + @WithMockUser("save-existing-email") + void testSaveExistingEmail() throws Exception { + User user = new User(); + user.setLogin("save-existing-email"); + user.setEmail("save-existing-email@example.com"); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setActivated(true); + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("save-existing-email2"); + anotherUser.setEmail("save-existing-email2@example.com"); + anotherUser.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + anotherUser.setActivated(true); + + userRepository.saveAndFlush(anotherUser); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-existing-email2@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.ADMIN)); + + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("save-existing-email").orElseThrow(); + assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); + + userService.deleteUser("save-existing-email"); + userService.deleteUser("save-existing-email2"); + } + + @Test + @Transactional + @WithMockUser("save-existing-email-and-login") + void testSaveExistingEmailAndLogin() throws Exception { + User user = new User(); + user.setLogin("save-existing-email-and-login"); + user.setEmail("save-existing-email-and-login@example.com"); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setActivated(true); + userRepository.saveAndFlush(user); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setLogin("not-used"); + userDTO.setFirstName("firstname"); + userDTO.setLastName("lastname"); + userDTO.setEmail("save-existing-email-and-login@example.com"); + userDTO.setActivated(false); + userDTO.setImageUrl("http://placehold.it/50x50"); + userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.ADMIN)); + + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); + assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); + + userService.deleteUser("save-existing-email-and-login"); + } + + @Test + @Transactional + @WithMockUser("change-password-wrong-existing-password") + void testChangePasswordWrongExistingPassword() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.insecure().nextAlphanumeric(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-wrong-existing-password"); + user.setEmail("change-password-wrong-existing-password@example.com"); + userRepository.saveAndFlush(user); + + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(new PasswordChangeDTO("1" + currentPassword, "new password"))) + ) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); + assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); + assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue(); + + userService.deleteUser("change-password-wrong-existing-password"); + } + + @Test + @Transactional + @WithMockUser("change-password") + void testChangePassword() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.insecure().nextAlphanumeric(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password"); + user.setEmail("change-password@example.com"); + userRepository.saveAndFlush(user); + + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, "new password"))) + ) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); + assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); + + userService.deleteUser("change-password"); + } + + @Test + @Transactional + @WithMockUser("change-password-too-small") + void testChangePasswordTooSmall() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.insecure().nextAlphanumeric(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-too-small"); + user.setEmail("change-password-too-small@example.com"); + userRepository.saveAndFlush(user); + + String newPassword = RandomStringUtils.insecure().next(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); + + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, newPassword))) + ) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + + userService.deleteUser("change-password-too-small"); + } + + @Test + @Transactional + @WithMockUser("change-password-too-long") + void testChangePasswordTooLong() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.insecure().nextAlphanumeric(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-too-long"); + user.setEmail("change-password-too-long@example.com"); + userRepository.saveAndFlush(user); + + String newPassword = RandomStringUtils.insecure().next(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); + + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, newPassword))) + ) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + + userService.deleteUser("change-password-too-long"); + } + + @Test + @Transactional + @WithMockUser("change-password-empty") + void testChangePasswordEmpty() throws Exception { + User user = new User(); + String currentPassword = RandomStringUtils.insecure().nextAlphanumeric(60); + user.setPassword(passwordEncoder.encode(currentPassword)); + user.setLogin("change-password-empty"); + user.setEmail("change-password-empty@example.com"); + userRepository.saveAndFlush(user); + + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, ""))) + ) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); + assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); + + userService.deleteUser("change-password-empty"); + } + + @Test + @Transactional + void testRequestPasswordReset() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setActivated(true); + user.setLogin("password-reset"); + user.setEmail("password-reset@example.com"); + user.setLangKey("en"); + userRepository.saveAndFlush(user); + + restAccountMockMvc + .perform(post("/api/account/reset-password/init").content("password-reset@example.com")) + .andExpect(status().isOk()); + + userService.deleteUser("password-reset"); + } + + @Test + @Transactional + void testRequestPasswordResetUpperCaseEmail() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setActivated(true); + user.setLogin("password-reset-upper-case"); + user.setEmail("password-reset-upper-case@example.com"); + user.setLangKey("en"); + userRepository.saveAndFlush(user); + + restAccountMockMvc + .perform(post("/api/account/reset-password/init").content("password-reset-upper-case@EXAMPLE.COM")) + .andExpect(status().isOk()); + + userService.deleteUser("password-reset-upper-case"); + } + + @Test + void testRequestPasswordResetWrongEmail() throws Exception { + restAccountMockMvc + .perform(post("/api/account/reset-password/init").content("password-reset-wrong-email@example.com")) + .andExpect(status().isOk()); + } + + @Test + void testRequestPasswordResetInvalidEmail() throws Exception { + restAccountMockMvc.perform(post("/api/account/reset-password/init").content("invalid-email")).andExpect(status().isBadRequest()); + } + + @Test + void testRequestPasswordResetTooLongEmail() throws Exception { + restAccountMockMvc + .perform(post("/api/account/reset-password/init").content("a".repeat(250) + "@x.co")) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + void testFinishPasswordReset() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setLogin("finish-password-reset"); + user.setEmail("finish-password-reset@example.com"); + user.setResetDate(Instant.now().plusSeconds(60)); + user.setResetKey("reset key"); + userRepository.saveAndFlush(user); + + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey(user.getResetKey()); + keyAndPassword.setNewPassword("new password"); + + restAccountMockMvc + .perform( + post("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(keyAndPassword)) + ) + .andExpect(status().isOk()); + + User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); + + userService.deleteUser("finish-password-reset"); + } + + @Test + @Transactional + void testFinishPasswordResetTooSmall() throws Exception { + User user = new User(); + user.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + user.setLogin("finish-password-reset-too-small"); + user.setEmail("finish-password-reset-too-small@example.com"); + user.setResetDate(Instant.now().plusSeconds(60)); + user.setResetKey("reset key too small"); + userRepository.saveAndFlush(user); + + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey(user.getResetKey()); + keyAndPassword.setNewPassword("foo"); + + restAccountMockMvc + .perform( + post("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(keyAndPassword)) + ) + .andExpect(status().isBadRequest()); + + User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); + assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); + + userService.deleteUser("finish-password-reset-too-small"); + } + + @Test + @Transactional + void testFinishPasswordResetWrongKey() throws Exception { + KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); + keyAndPassword.setKey("wrong reset key"); + keyAndPassword.setNewPassword("new password"); + + restAccountMockMvc + .perform( + post("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .content(om.writeValueAsBytes(keyAndPassword)) + ) + .andExpect(status().isBadRequest()); + } +} diff --git a/src/test/java/com/example/questionbank/web/rest/AuthenticateControllerIT.java b/src/test/java/com/example/questionbank/web/rest/AuthenticateControllerIT.java new file mode 100644 index 0000000..d550bcf --- /dev/null +++ b/src/test/java/com/example/questionbank/web/rest/AuthenticateControllerIT.java @@ -0,0 +1,102 @@ +package com.example.questionbank.web.rest; + +import static org.hamcrest.Matchers.emptyString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.example.questionbank.IntegrationTest; +import com.example.questionbank.domain.User; +import com.example.questionbank.repository.UserRepository; +import com.example.questionbank.web.rest.vm.LoginVM; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; +import tools.jackson.databind.ObjectMapper; + +/** + * Integration tests for the {@link AuthenticateController} REST controller. + */ +@AutoConfigureMockMvc +@IntegrationTest +class AuthenticateControllerIT { + + @Autowired + private ObjectMapper om; + + @Autowired + private UserRepository userRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private MockMvc mockMvc; + + @Test + @Transactional + void testAuthorize() throws Exception { + User user = new User(); + user.setLogin("user-jwt-controller"); + user.setEmail("user-jwt-controller@example.com"); + user.setActivated(true); + user.setPassword(passwordEncoder.encode("test")); + + userRepository.saveAndFlush(user); + + LoginVM login = new LoginVM(); + login.setUsername("user-jwt-controller"); + login.setPassword("test"); + mockMvc + .perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(login))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id_token").isString()) + .andExpect(jsonPath("$.id_token").isNotEmpty()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(is(emptyString())))); + } + + @Test + @Transactional + void testAuthorizeWithRememberMe() throws Exception { + User user = new User(); + user.setLogin("user-jwt-controller-remember-me"); + user.setEmail("user-jwt-controller-remember-me@example.com"); + user.setActivated(true); + user.setPassword(passwordEncoder.encode("test")); + + userRepository.saveAndFlush(user); + + LoginVM login = new LoginVM(); + login.setUsername("user-jwt-controller-remember-me"); + login.setPassword("test"); + login.setRememberMe(true); + mockMvc + .perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(login))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id_token").isString()) + .andExpect(jsonPath("$.id_token").isNotEmpty()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(is(emptyString())))); + } + + @Test + void testAuthorizeFails() throws Exception { + LoginVM login = new LoginVM(); + login.setUsername("wrong-user"); + login.setPassword("wrong password"); + mockMvc + .perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(login))) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.id_token").doesNotExist()) + .andExpect(header().doesNotExist("Authorization")); + } +} diff --git a/src/test/java/com/example/questionbank/web/rest/AuthorityResourceIT.java b/src/test/java/com/example/questionbank/web/rest/AuthorityResourceIT.java new file mode 100644 index 0000000..2a8cc30 --- /dev/null +++ b/src/test/java/com/example/questionbank/web/rest/AuthorityResourceIT.java @@ -0,0 +1,206 @@ +package com.example.questionbank.web.rest; + +import static com.example.questionbank.domain.AuthorityAsserts.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.example.questionbank.IntegrationTest; +import com.example.questionbank.domain.Authority; +import com.example.questionbank.repository.AuthorityRepository; +import jakarta.persistence.EntityManager; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; +import tools.jackson.databind.ObjectMapper; + +/** + * Integration tests for the {@link AuthorityResource} REST controller. + */ +@IntegrationTest +@AutoConfigureMockMvc +@WithMockUser(authorities = { "ROLE_ADMIN" }) +class AuthorityResourceIT { + + private static final String ENTITY_API_URL = "/api/authorities"; + private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{name}"; + + @Autowired + private ObjectMapper om; + + @Autowired + private AuthorityRepository authorityRepository; + + @Autowired + private EntityManager em; + + @Autowired + private MockMvc restAuthorityMockMvc; + + private Authority authority; + + private Authority insertedAuthority; + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Authority createEntity() { + return new Authority().name(UUID.randomUUID().toString()); + } + + /** + * Create an updated entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Authority createUpdatedEntity() { + return new Authority().name(UUID.randomUUID().toString()); + } + + @BeforeEach + void initTest() { + authority = createEntity(); + } + + @AfterEach + void cleanup() { + if (insertedAuthority != null) { + authorityRepository.delete(insertedAuthority); + insertedAuthority = null; + } + } + + @Test + @Transactional + void createAuthority() throws Exception { + long databaseSizeBeforeCreate = getRepositoryCount(); + // Create the Authority + var returnedAuthority = om.readValue( + restAuthorityMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(authority))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getContentAsString(), + Authority.class + ); + + // Validate the Authority in the database + assertIncrementedRepositoryCount(databaseSizeBeforeCreate); + assertAuthorityUpdatableFieldsEquals(returnedAuthority, getPersistedAuthority(returnedAuthority)); + + insertedAuthority = returnedAuthority; + } + + @Test + @Transactional + void createAuthorityWithExistingId() throws Exception { + // Create the Authority with an existing ID + insertedAuthority = authorityRepository.saveAndFlush(authority); + + long databaseSizeBeforeCreate = getRepositoryCount(); + + // An entity with an existing ID cannot be created, so this API call must fail + restAuthorityMockMvc + .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(authority))) + .andExpect(status().isBadRequest()); + + // Validate the Authority in the database + assertSameRepositoryCount(databaseSizeBeforeCreate); + } + + @Test + @Transactional + void getAllAuthorities() throws Exception { + // Initialize the database + authority.setName(UUID.randomUUID().toString()); + insertedAuthority = authorityRepository.saveAndFlush(authority); + + // Get all the authorityList + restAuthorityMockMvc + .perform(get(ENTITY_API_URL + "?sort=name,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].name").value(hasItem(authority.getName()))); + } + + @Test + @Transactional + void getAuthority() throws Exception { + // Initialize the database + authority.setName(UUID.randomUUID().toString()); + insertedAuthority = authorityRepository.saveAndFlush(authority); + + // Get the authority + restAuthorityMockMvc + .perform(get(ENTITY_API_URL_ID, authority.getName())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.name").value(authority.getName())); + } + + @Test + @Transactional + void getNonExistingAuthority() throws Exception { + // Get the authority + restAuthorityMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); + } + + @Test + @Transactional + void deleteAuthority() throws Exception { + // Initialize the database + authority.setName(UUID.randomUUID().toString()); + insertedAuthority = authorityRepository.saveAndFlush(authority); + + long databaseSizeBeforeDelete = getRepositoryCount(); + + // Delete the authority + restAuthorityMockMvc + .perform(delete(ENTITY_API_URL_ID, authority.getName()).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + assertDecrementedRepositoryCount(databaseSizeBeforeDelete); + } + + protected long getRepositoryCount() { + return authorityRepository.count(); + } + + protected void assertIncrementedRepositoryCount(long countBefore) { + assertThat(countBefore + 1).isEqualTo(getRepositoryCount()); + } + + protected void assertDecrementedRepositoryCount(long countBefore) { + assertThat(countBefore - 1).isEqualTo(getRepositoryCount()); + } + + protected void assertSameRepositoryCount(long countBefore) { + assertThat(countBefore).isEqualTo(getRepositoryCount()); + } + + protected Authority getPersistedAuthority(Authority authority) { + return authorityRepository.findById(authority.getName()).orElseThrow(); + } + + protected void assertPersistedAuthorityToMatchAllProperties(Authority expectedAuthority) { + assertAuthorityAllPropertiesEquals(expectedAuthority, getPersistedAuthority(expectedAuthority)); + } + + protected void assertPersistedAuthorityToMatchUpdatableProperties(Authority expectedAuthority) { + assertAuthorityAllUpdatablePropertiesEquals(expectedAuthority, getPersistedAuthority(expectedAuthority)); + } +} diff --git a/src/test/java/com/example/questionbank/web/rest/PublicUserResourceIT.java b/src/test/java/com/example/questionbank/web/rest/PublicUserResourceIT.java new file mode 100644 index 0000000..b5017bc --- /dev/null +++ b/src/test/java/com/example/questionbank/web/rest/PublicUserResourceIT.java @@ -0,0 +1,87 @@ +package com.example.questionbank.web.rest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.example.questionbank.IntegrationTest; +import com.example.questionbank.domain.User; +import com.example.questionbank.repository.UserRepository; +import com.example.questionbank.security.AuthoritiesConstants; +import com.example.questionbank.service.UserService; +import java.util.Set; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; + +/** + * Integration tests for the {@link PublicUserResource} REST controller. + */ +@AutoConfigureMockMvc +@WithMockUser(authorities = AuthoritiesConstants.ADMIN) +@IntegrationTest +class PublicUserResourceIT { + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserService userService; + + @Autowired + private MockMvc restUserMockMvc; + + private User user; + private Long numberOfUsers; + + @BeforeEach + void initTest() { + numberOfUsers = userRepository.count(); + user = UserResourceIT.initTestUser(); + } + + @AfterEach + void cleanupAndCheck() { + userService.deleteUser(user.getLogin()); + assertThat(userRepository.count()).isEqualTo(numberOfUsers); + numberOfUsers = null; + } + + @Test + @Transactional + void getAllPublicUsers() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + // Get all the users + restUserMockMvc + .perform(get("/api/users?sort=id,desc").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[?(@.id == %d)].login".formatted(user.getId())).value(user.getLogin())) + .andExpect(jsonPath("$.[?(@.id == %d)].keys()".formatted(user.getId())).value(Set.of("id", "login"))) + .andExpect(jsonPath("$.[*].email").doesNotHaveJsonPath()) + .andExpect(jsonPath("$.[*].imageUrl").doesNotHaveJsonPath()) + .andExpect(jsonPath("$.[*].langKey").doesNotHaveJsonPath()); + } + + @Test + @Transactional + void getAllUsersSortedByParameters() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + restUserMockMvc.perform(get("/api/users?sort=resetKey,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()); + restUserMockMvc.perform(get("/api/users?sort=password,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest()); + restUserMockMvc + .perform(get("/api/users?sort=resetKey,desc&sort=id,desc").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + restUserMockMvc.perform(get("/api/users?sort=id,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); + } +} diff --git a/src/test/java/com/example/questionbank/web/rest/TestUtil.java b/src/test/java/com/example/questionbank/web/rest/TestUtil.java new file mode 100644 index 0000000..8d9cc55 --- /dev/null +++ b/src/test/java/com/example/questionbank/web/rest/TestUtil.java @@ -0,0 +1,190 @@ +package com.example.questionbank.web.rest; + +import static org.assertj.core.api.Assertions.assertThat; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import java.math.BigDecimal; +import java.time.ZonedDateTime; +import java.time.format.DateTimeParseException; +import java.util.Arrays; +import java.util.List; +import org.hamcrest.Description; +import org.hamcrest.TypeSafeDiagnosingMatcher; +import org.hamcrest.TypeSafeMatcher; +import org.springframework.cglib.proxy.Enhancer; +import org.springframework.cglib.proxy.MethodInterceptor; +import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; +import org.springframework.format.support.DefaultFormattingConversionService; +import org.springframework.format.support.FormattingConversionService; + +/** + * Utility class for testing REST controllers. + */ +public final class TestUtil { + + /** + * Create a byte array with a specific size filled with specified data. + * + * @param size the size of the byte array. + * @param data the data to put in the byte array. + * @return the JSON byte array. + */ + public static byte[] createByteArray(int size, String data) { + byte[] byteArray = new byte[size]; + Arrays.fill(byteArray, Byte.parseByte(data, 2)); + return byteArray; + } + + /** + * A matcher that tests that the examined string represents the same instant as the reference datetime. + */ + public static class ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher { + + private final ZonedDateTime date; + + public ZonedDateTimeMatcher(ZonedDateTime date) { + this.date = date; + } + + @Override + protected boolean matchesSafely(String item, Description mismatchDescription) { + try { + if (!date.isEqual(ZonedDateTime.parse(item))) { + mismatchDescription.appendText("was ").appendValue(item); + return false; + } + return true; + } catch (DateTimeParseException e) { + mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime"); + return false; + } + } + + @Override + public void describeTo(Description description) { + description.appendText("a String representing the same Instant as ").appendValue(date); + } + } + + /** + * Creates a matcher that matches when the examined string represents the same instant as the reference datetime. + * + * @param date the reference datetime against which the examined string is checked. + */ + public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) { + return new ZonedDateTimeMatcher(date); + } + + /** + * A matcher that tests that the examined number represents the same value - it can be Long, Double, etc - as the reference BigDecimal. + */ + public static class NumberMatcher extends TypeSafeMatcher { + + final BigDecimal value; + + public NumberMatcher(BigDecimal value) { + this.value = value; + } + + @Override + public void describeTo(Description description) { + description.appendText("a numeric value is ").appendValue(value); + } + + @Override + protected boolean matchesSafely(Number item) { + BigDecimal bigDecimal = asDecimal(item); + return bigDecimal != null && value.compareTo(bigDecimal) == 0; + } + + private static BigDecimal asDecimal(Number item) { + return switch (item) { + case null -> null; + case BigDecimal bigDecimal -> bigDecimal; + case Long l -> BigDecimal.valueOf(l); + case Integer i -> BigDecimal.valueOf(i); + case Double v -> BigDecimal.valueOf(v); + case Float v -> BigDecimal.valueOf(v); + default -> BigDecimal.valueOf(item.doubleValue()); + }; + } + } + + /** + * Creates a matcher that matches when the examined number represents the same value as the reference BigDecimal. + * + * @param number the reference BigDecimal against which the examined number is checked. + */ + public static NumberMatcher sameNumber(BigDecimal number) { + return new NumberMatcher(number); + } + + /** + * Verifies the equals/hashcode contract on the domain object. + */ + public static void equalsVerifier(Class clazz) throws Exception { + T domainObject1 = clazz.getConstructor().newInstance(); + assertThat(domainObject1.toString()).isNotNull(); + assertThat(domainObject1).isEqualTo(domainObject1); + assertThat(domainObject1).hasSameHashCodeAs(domainObject1); + // Test with an instance of another class + Object testOtherObject = new Object(); + assertThat(domainObject1).isNotEqualTo(testOtherObject); + assertThat(domainObject1).isNotEqualTo(null); + // Test with an instance of the same class + T domainObject2 = clazz.getConstructor().newInstance(); + assertThat(domainObject1).isNotEqualTo(domainObject2); + // HashCodes are equals because the objects are not persisted yet + assertThat(domainObject1).hasSameHashCodeAs(domainObject2); + } + + /** + * Create a {@link FormattingConversionService} which use ISO date format, instead of the localized one. + * @return the {@link FormattingConversionService}. + */ + public static FormattingConversionService createFormattingConversionService() { + DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService(); + var registrar = new DateTimeFormatterRegistrar(); + registrar.setUseIsoFormat(true); + registrar.registerFormatters(dfcs); + return dfcs; + } + + /** + * Executes a query on the EntityManager finding all stored objects. + * @param The type of objects to be searched + * @param em The instance of the EntityManager + * @param clazz The class type to be searched + * @return A list of all found objects + */ + public static List findAll(EntityManager em, Class clazz) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(clazz); + Root rootEntry = cq.from(clazz); + CriteriaQuery all = cq.select(rootEntry); + TypedQuery allQuery = em.createQuery(all); + return allQuery.getResultList(); + } + + @SuppressWarnings("unchecked") + public static T createUpdateProxyForBean(T update, T original) { + Enhancer e = new Enhancer(); + e.setSuperclass(original.getClass()); + e.setCallback( + (MethodInterceptor) (obj, method, args, proxy) -> { + Object val = update.getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(update, args); + if (val == null) { + return original.getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(original, args); + } + return val; + } + ); + return (T) e.create(); + } + + private TestUtil() {} +} diff --git a/src/test/java/com/example/questionbank/web/rest/UserResourceIT.java b/src/test/java/com/example/questionbank/web/rest/UserResourceIT.java new file mode 100644 index 0000000..584a493 --- /dev/null +++ b/src/test/java/com/example/questionbank/web/rest/UserResourceIT.java @@ -0,0 +1,484 @@ +package com.example.questionbank.web.rest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import com.example.questionbank.IntegrationTest; +import com.example.questionbank.domain.User; +import com.example.questionbank.repository.UserRepository; +import com.example.questionbank.security.AuthoritiesConstants; +import com.example.questionbank.service.UserService; +import com.example.questionbank.service.dto.AdminUserDTO; +import com.example.questionbank.service.mapper.UserMapper; +import jakarta.persistence.EntityManager; +import java.util.*; +import java.util.function.Consumer; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; +import tools.jackson.databind.ObjectMapper; + +/** + * Integration tests for the {@link UserResource} REST controller. + */ +@AutoConfigureMockMvc +@WithMockUser(authorities = AuthoritiesConstants.ADMIN) +@IntegrationTest +class UserResourceIT { + + private static final String DEFAULT_LOGIN = "johndoe"; + private static final String UPDATED_LOGIN = "jhipster"; + + private static final Long DEFAULT_ID = 1L; + + private static final String DEFAULT_EMAIL = "johndoe@localhost"; + private static final String UPDATED_EMAIL = "jhipster@localhost"; + + private static final String DEFAULT_FIRSTNAME = "john"; + private static final String UPDATED_FIRSTNAME = "jhipsterFirstName"; + + private static final String DEFAULT_LASTNAME = "doe"; + private static final String UPDATED_LASTNAME = "jhipsterLastName"; + + private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50"; + private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40"; + + private static final String DEFAULT_LANGKEY = "en"; + private static final String UPDATED_LANGKEY = "fr"; + + @Autowired + private ObjectMapper om; + + @Autowired + private UserRepository userRepository; + + @Autowired + private UserService userService; + + @Autowired + private UserMapper userMapper; + + @Autowired + private EntityManager em; + + @Autowired + private MockMvc restUserMockMvc; + + private User user; + + private Long numberOfUsers; + + /** + * Create a User. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which has a required relationship to the User entity. + */ + public static User createEntity() { + User persistUser = new User(); + persistUser.setLogin(DEFAULT_LOGIN + RandomStringUtils.insecure().nextAlphabetic(5)); + persistUser.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + persistUser.setActivated(true); + persistUser.setEmail(RandomStringUtils.insecure().nextAlphabetic(5) + DEFAULT_EMAIL); + persistUser.setFirstName(DEFAULT_FIRSTNAME); + persistUser.setLastName(DEFAULT_LASTNAME); + persistUser.setImageUrl(DEFAULT_IMAGEURL); + persistUser.setLangKey(DEFAULT_LANGKEY); + return persistUser; + } + + /** + * Setups the database with one user. + */ + public static User initTestUser() { + User persistUser = createEntity(); + persistUser.setLogin(DEFAULT_LOGIN); + persistUser.setEmail(DEFAULT_EMAIL); + return persistUser; + } + + @BeforeEach + void initTest() { + numberOfUsers = userRepository.count(); + user = initTestUser(); + } + + @AfterEach + void cleanupAndCheck() { + userService.deleteUser(DEFAULT_LOGIN); + userService.deleteUser(UPDATED_LOGIN); + userService.deleteUser(user.getLogin()); + userService.deleteUser("anotherlogin"); + assertThat(userRepository.count()).isEqualTo(numberOfUsers); + numberOfUsers = null; + } + + @Test + @Transactional + void createUser() throws Exception { + // Create the User + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setLogin(DEFAULT_LOGIN); + userDTO.setFirstName(DEFAULT_FIRSTNAME); + userDTO.setLastName(DEFAULT_LASTNAME); + userDTO.setEmail(DEFAULT_EMAIL); + userDTO.setActivated(true); + userDTO.setImageUrl(DEFAULT_IMAGEURL); + userDTO.setLangKey(DEFAULT_LANGKEY); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + var returnedUserDTO = om.readValue( + restUserMockMvc + .perform(post("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isCreated()) + .andReturn() + .getResponse() + .getContentAsString(), + AdminUserDTO.class + ); + + User convertedUser = userMapper.userDTOToUser(returnedUserDTO); + // Validate the returned User + assertThat(convertedUser.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(convertedUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(convertedUser.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(convertedUser.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(convertedUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(convertedUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + } + + @Test + @Transactional + void createUserWithExistingId() throws Exception { + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setId(DEFAULT_ID); + userDTO.setLogin(DEFAULT_LOGIN); + userDTO.setFirstName(DEFAULT_FIRSTNAME); + userDTO.setLastName(DEFAULT_LASTNAME); + userDTO.setEmail(DEFAULT_EMAIL); + userDTO.setActivated(true); + userDTO.setImageUrl(DEFAULT_IMAGEURL); + userDTO.setLangKey(DEFAULT_LANGKEY); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + // An entity with an existing ID cannot be created, so this API call must fail + restUserMockMvc + .perform(post("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate)); + } + + @Test + @Transactional + void createUserWithExistingLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setLogin(DEFAULT_LOGIN); // this login should already be used + userDTO.setFirstName(DEFAULT_FIRSTNAME); + userDTO.setLastName(DEFAULT_LASTNAME); + userDTO.setEmail("anothermail@localhost"); + userDTO.setActivated(true); + userDTO.setImageUrl(DEFAULT_IMAGEURL); + userDTO.setLangKey(DEFAULT_LANGKEY); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + // Create the User + restUserMockMvc + .perform(post("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate)); + } + + @Test + @Transactional + void createUserWithExistingEmail() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeCreate = userRepository.findAll().size(); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setLogin("anotherlogin"); + userDTO.setFirstName(DEFAULT_FIRSTNAME); + userDTO.setLastName(DEFAULT_LASTNAME); + userDTO.setEmail(DEFAULT_EMAIL); // this email should already be used + userDTO.setActivated(true); + userDTO.setImageUrl(DEFAULT_IMAGEURL); + userDTO.setLangKey(DEFAULT_LANGKEY); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + // Create the User + restUserMockMvc + .perform(post("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isBadRequest()); + + // Validate the User in the database + assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate)); + } + + @Test + @Transactional + void getAllUsers() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + // Get all the users + restUserMockMvc + .perform(get("/api/admin/users?sort=id,desc").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) + .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) + .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) + .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) + .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) + .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); + } + + @Test + @Transactional + void getUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + // Get the user + restUserMockMvc + .perform(get("/api/admin/users/{login}", user.getLogin())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(jsonPath("$.login").value(user.getLogin())) + .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) + .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) + .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) + .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) + .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); + } + + @Test + @Transactional + void getNonExistingUser() throws Exception { + restUserMockMvc.perform(get("/api/admin/users/unknown")).andExpect(status().isNotFound()); + } + + @Test + @Transactional + void updateUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeUpdate = userRepository.findAll().size(); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).orElseThrow(); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setId(updatedUser.getId()); + userDTO.setLogin(updatedUser.getLogin()); + userDTO.setFirstName(UPDATED_FIRSTNAME); + userDTO.setLastName(UPDATED_LASTNAME); + userDTO.setEmail(UPDATED_EMAIL); + userDTO.setActivated(updatedUser.isActivated()); + userDTO.setImageUrl(UPDATED_IMAGEURL); + userDTO.setLangKey(UPDATED_LANGKEY); + userDTO.setCreatedBy(updatedUser.getCreatedBy()); + userDTO.setCreatedDate(updatedUser.getCreatedDate()); + userDTO.setLastModifiedBy(updatedUser.getLastModifiedBy()); + userDTO.setLastModifiedDate(updatedUser.getLastModifiedDate()); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + restUserMockMvc + .perform(put("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isOk()); + + // Validate the User in the database + assertPersistedUsers(users -> { + assertThat(users).hasSize(databaseSizeBeforeUpdate); + User testUser = users + .stream() + .filter(usr -> usr.getId().equals(updatedUser.getId())) + .findFirst() + .orElseThrow(); + assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); + }); + } + + @Test + @Transactional + void updateUserLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeUpdate = userRepository.findAll().size(); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).orElseThrow(); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setId(updatedUser.getId()); + userDTO.setLogin(UPDATED_LOGIN); + userDTO.setFirstName(UPDATED_FIRSTNAME); + userDTO.setLastName(UPDATED_LASTNAME); + userDTO.setEmail(UPDATED_EMAIL); + userDTO.setActivated(updatedUser.isActivated()); + userDTO.setImageUrl(UPDATED_IMAGEURL); + userDTO.setLangKey(UPDATED_LANGKEY); + userDTO.setCreatedBy(updatedUser.getCreatedBy()); + userDTO.setCreatedDate(updatedUser.getCreatedDate()); + userDTO.setLastModifiedBy(updatedUser.getLastModifiedBy()); + userDTO.setLastModifiedDate(updatedUser.getLastModifiedDate()); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + restUserMockMvc + .perform(put("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isOk()); + + // Validate the User in the database + assertPersistedUsers(users -> { + assertThat(users).hasSize(databaseSizeBeforeUpdate); + User testUser = users + .stream() + .filter(usr -> usr.getId().equals(updatedUser.getId())) + .findFirst() + .orElseThrow(); + assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN); + assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); + }); + } + + @Test + @Transactional + void updateUserExistingEmail() throws Exception { + // Initialize the database with 2 users + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("jhipster"); + anotherUser.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + anotherUser.setActivated(true); + anotherUser.setEmail("jhipster@localhost"); + anotherUser.setFirstName("java"); + anotherUser.setLastName("hipster"); + anotherUser.setImageUrl(""); + anotherUser.setLangKey("en"); + userRepository.saveAndFlush(anotherUser); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).orElseThrow(); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setId(updatedUser.getId()); + userDTO.setLogin(updatedUser.getLogin()); + userDTO.setFirstName(updatedUser.getFirstName()); + userDTO.setLastName(updatedUser.getLastName()); + userDTO.setEmail("jhipster@localhost"); // this email should already be used by anotherUser + userDTO.setActivated(updatedUser.isActivated()); + userDTO.setImageUrl(updatedUser.getImageUrl()); + userDTO.setLangKey(updatedUser.getLangKey()); + userDTO.setCreatedBy(updatedUser.getCreatedBy()); + userDTO.setCreatedDate(updatedUser.getCreatedDate()); + userDTO.setLastModifiedBy(updatedUser.getLastModifiedBy()); + userDTO.setLastModifiedDate(updatedUser.getLastModifiedDate()); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + restUserMockMvc + .perform(put("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + void updateUserExistingLogin() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + + User anotherUser = new User(); + anotherUser.setLogin("jhipster"); + anotherUser.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60)); + anotherUser.setActivated(true); + anotherUser.setEmail("jhipster@localhost"); + anotherUser.setFirstName("java"); + anotherUser.setLastName("hipster"); + anotherUser.setImageUrl(""); + anotherUser.setLangKey("en"); + userRepository.saveAndFlush(anotherUser); + + // Update the user + User updatedUser = userRepository.findById(user.getId()).orElseThrow(); + + AdminUserDTO userDTO = new AdminUserDTO(); + userDTO.setId(updatedUser.getId()); + userDTO.setLogin("jhipster"); // this login should already be used by anotherUser + userDTO.setFirstName(updatedUser.getFirstName()); + userDTO.setLastName(updatedUser.getLastName()); + userDTO.setEmail(updatedUser.getEmail()); + userDTO.setActivated(updatedUser.isActivated()); + userDTO.setImageUrl(updatedUser.getImageUrl()); + userDTO.setLangKey(updatedUser.getLangKey()); + userDTO.setCreatedBy(updatedUser.getCreatedBy()); + userDTO.setCreatedDate(updatedUser.getCreatedDate()); + userDTO.setLastModifiedBy(updatedUser.getLastModifiedBy()); + userDTO.setLastModifiedDate(updatedUser.getLastModifiedDate()); + userDTO.setAuthorities(Set.of(AuthoritiesConstants.USER)); + + restUserMockMvc + .perform(put("/api/admin/users").contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(userDTO))) + .andExpect(status().isBadRequest()); + } + + @Test + @Transactional + void deleteUser() throws Exception { + // Initialize the database + userRepository.saveAndFlush(user); + int databaseSizeBeforeDelete = userRepository.findAll().size(); + + // Delete the user + restUserMockMvc + .perform(delete("/api/admin/users/{login}", user.getLogin()).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeDelete - 1)); + } + + @Test + void testUserEquals() throws Exception { + TestUtil.equalsVerifier(User.class); + User user1 = new User(); + user1.setId(DEFAULT_ID); + User user2 = new User(); + user2.setId(user1.getId()); + assertThat(user1).isEqualTo(user2); + user2.setId(2L); + assertThat(user1).isNotEqualTo(user2); + user1.setId(null); + assertThat(user1).isNotEqualTo(user2); + } + + private void assertPersistedUsers(Consumer> userAssertion) { + userAssertion.accept(userRepository.findAll()); + } +} diff --git a/src/test/java/com/example/questionbank/web/rest/WithUnauthenticatedMockUser.java b/src/test/java/com/example/questionbank/web/rest/WithUnauthenticatedMockUser.java new file mode 100644 index 0000000..1657e38 --- /dev/null +++ b/src/test/java/com/example/questionbank/web/rest/WithUnauthenticatedMockUser.java @@ -0,0 +1,23 @@ +package com.example.questionbank.web.rest; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.test.context.support.WithSecurityContext; +import org.springframework.security.test.context.support.WithSecurityContextFactory; + +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@WithSecurityContext(factory = WithUnauthenticatedMockUser.Factory.class) +public @interface WithUnauthenticatedMockUser { + class Factory implements WithSecurityContextFactory { + + @Override + public SecurityContext createSecurityContext(WithUnauthenticatedMockUser annotation) { + return SecurityContextHolder.createEmptyContext(); + } + } +} diff --git a/src/test/java/com/example/questionbank/web/rest/errors/ExceptionTranslatorIT.java b/src/test/java/com/example/questionbank/web/rest/errors/ExceptionTranslatorIT.java new file mode 100644 index 0000000..737f6af --- /dev/null +++ b/src/test/java/com/example/questionbank/web/rest/errors/ExceptionTranslatorIT.java @@ -0,0 +1,117 @@ +package com.example.questionbank.web.rest.errors; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.example.questionbank.IntegrationTest; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; + +/** + * Integration tests {@link ExceptionTranslator} controller advice. + */ +@WithMockUser +@AutoConfigureMockMvc +@IntegrationTest +class ExceptionTranslatorIT { + + @Autowired + private MockMvc mockMvc; + + @Test + void testConcurrencyFailure() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/concurrency-failure")) + .andExpect(status().isConflict()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); + } + + @Test + void testMethodArgumentNotValid() throws Exception { + mockMvc + .perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) + .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("test")) + .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) + .andExpect(jsonPath("$.fieldErrors.[0].message").value("must not be null")); + } + + @Test + void testMissingServletRequestPartException() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/missing-servlet-request-part")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); + } + + @Test + void testMissingServletRequestParameterException() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/missing-servlet-request-parameter")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); + } + + @Test + void testAccessDenied() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/access-denied")) + .andExpect(status().isForbidden()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.403")) + .andExpect(jsonPath("$.detail").value("test access denied!")); + } + + @Test + void testUnauthorized() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/unauthorized")) + .andExpect(status().isUnauthorized()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.401")) + .andExpect(jsonPath("$.path").value("/api/exception-translator-test/unauthorized")) + .andExpect(jsonPath("$.detail").value("test authentication failed!")); + } + + @Test + void testMethodNotSupported() throws Exception { + mockMvc + .perform(post("/api/exception-translator-test/access-denied")) + .andExpect(status().isMethodNotAllowed()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.405")) + .andExpect(jsonPath("$.detail").value("Request method 'POST' is not supported")); + } + + @Test + void testExceptionWithResponseStatus() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/response-status")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")) + .andExpect(jsonPath("$.title").value("test response status")); + } + + @Test + void testInternalServerError() throws Exception { + mockMvc + .perform(get("/api/exception-translator-test/internal-server-error")) + .andExpect(status().isInternalServerError()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.500")) + .andExpect(jsonPath("$.title").value("Internal Server Error")); + } +} diff --git a/src/test/java/com/example/questionbank/web/rest/errors/ExceptionTranslatorTestController.java b/src/test/java/com/example/questionbank/web/rest/errors/ExceptionTranslatorTestController.java new file mode 100644 index 0000000..44d4240 --- /dev/null +++ b/src/test/java/com/example/questionbank/web/rest/errors/ExceptionTranslatorTestController.java @@ -0,0 +1,72 @@ +package com.example.questionbank.web.rest.errors; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; +import org.springframework.dao.ConcurrencyFailureException; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/api/exception-translator-test") +public class ExceptionTranslatorTestController { + + @GetMapping("/concurrency-failure") + public void concurrencyFailure() { + throw new ConcurrencyFailureException("test concurrency failure"); + } + + @PostMapping("/method-argument") + public void methodArgument(@Valid @RequestBody TestDTO testDTO) { + // empty method + } + + @GetMapping("/missing-servlet-request-part") + public void missingServletRequestPartException(@RequestPart("part") String part) { + // empty method + } + + @GetMapping("/missing-servlet-request-parameter") + public void missingServletRequestParameterException(@RequestParam("param") String param) { + // empty method + } + + @GetMapping("/access-denied") + public void accessdenied() { + throw new AccessDeniedException("test access denied!"); + } + + @GetMapping("/unauthorized") + public void unauthorized() { + throw new BadCredentialsException("test authentication failed!"); + } + + @GetMapping("/response-status") + public void exceptionWithResponseStatus() { + throw new TestResponseStatusException(); + } + + @GetMapping("/internal-server-error") + public void internalServerError() { + throw new RuntimeException(); + } + + public static class TestDTO { + + @NotNull + private String test; + + public String getTest() { + return test; + } + + public void setTest(String test) { + this.test = test; + } + } + + @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status") + @SuppressWarnings("serial") + public static class TestResponseStatusException extends RuntimeException {} +} diff --git a/src/test/resources/config/application-testdev.yml b/src/test/resources/config/application-testdev.yml new file mode 100644 index 0000000..e7ddb97 --- /dev/null +++ b/src/test/resources/config/application-testdev.yml @@ -0,0 +1,32 @@ +# =================================================================== +# Spring Boot configuration. +# +# This configuration is used for unit/integration tests with testcontainers database containers. +# +# To activate this configuration launch integration tests with the 'testcontainers' profile +# +# More information on database containers: https://www.testcontainers.org/modules/databases/ +# =================================================================== + +spring: + datasource: + type: com.zaxxer.hikari.HikariDataSource + hikari: + auto-commit: false + poolName: Hikari + maximum-pool-size: 1 + jpa: + open-in-view: false + hibernate: + ddl-auto: none + properties: + hibernate.id.new_generator_mappings: true + hibernate.connection.provider_disables_autocommit: true + hibernate.cache.use_second_level_cache: false + hibernate.cache.use_query_cache: false + hibernate.generate_statistics: false + hibernate.hbm2ddl.auto: none #TODO: temp relief for integration tests, revisit required + hibernate.type.preferred_instant_jdbc_type: TIMESTAMP + hibernate.jdbc.time_zone: UTC + hibernate.timezone.default_storage: NORMALIZE + hibernate.query.fail_on_pagination_over_collection_fetch: true diff --git a/src/test/resources/config/application-testprod.yml b/src/test/resources/config/application-testprod.yml new file mode 100644 index 0000000..b29b452 --- /dev/null +++ b/src/test/resources/config/application-testprod.yml @@ -0,0 +1,32 @@ +# =================================================================== +# Spring Boot configuration. +# +# This configuration is used for unit/integration tests with testcontainers database containers. +# +# To activate this configuration launch integration tests with the 'testcontainers' profile +# +# More information on database containers: https://www.testcontainers.org/modules/databases/ +# =================================================================== + +spring: + datasource: + type: com.zaxxer.hikari.HikariDataSource + hikari: + poolName: Hikari + auto-commit: false + maximum-pool-size: 1 + jpa: + open-in-view: false + hibernate: + ddl-auto: none + properties: + hibernate.id.new_generator_mappings: true + hibernate.connection.provider_disables_autocommit: true + hibernate.cache.use_second_level_cache: false + hibernate.cache.use_query_cache: false + hibernate.generate_statistics: false + hibernate.hbm2ddl.auto: none #TODO: temp relief for integration tests, revisit required + hibernate.type.preferred_instant_jdbc_type: TIMESTAMP + hibernate.jdbc.time_zone: UTC + hibernate.timezone.default_storage: NORMALIZE + hibernate.query.fail_on_pagination_over_collection_fetch: true diff --git a/src/test/resources/config/application.yml b/src/test/resources/config/application.yml new file mode 100644 index 0000000..23148ff --- /dev/null +++ b/src/test/resources/config/application.yml @@ -0,0 +1,97 @@ +# =================================================================== +# Spring Boot configuration. +# +# This configuration is used for unit/integration tests. +# +# More information on profiles: https://www.jhipster.tech/profiles/ +# More information on configuration properties: https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +# =================================================================== +# Standard Spring Boot properties. +# Full reference is available at: +# https://docs.spring.io/spring-boot/appendix/application-properties/index.html +# =================================================================== + +spring: + application: + name: questionBank + # Replace by 'prod, faker' to add the faker context and have sample data loaded in production + liquibase: + contexts: test + jackson: + datatype: + datetime: + write-durations-as-timestamps: false + mail: + host: localhost + main: + allow-bean-definition-overriding: true + messages: + basename: i18n/messages + security: + oauth2: + resourceserver: + jwt: + authority-prefix: '' + authorities-claim-name: auth + task: + execution: + thread-name-prefix: question-bank-task- + pool: + core-size: 1 + max-size: 50 + queue-capacity: 10000 + scheduling: + thread-name-prefix: question-bank-scheduling- + pool: + size: 20 + thymeleaf: + mode: HTML + +server: + port: 10344 + address: localhost + +# =================================================================== +# JHipster specific properties +# +# Full reference is available at: https://www.jhipster.tech/common-application-properties/ +# =================================================================== +jhipster: + clientApp: + name: 'questionBankApp' + mail: + from: questionBank@localhost.com + base-url: http://127.0.0.1:8080 + logging: + # To test json console appender + use-json-format: false + logstash: + enabled: false + host: localhost + port: 5000 + ring-buffer-size: 512 + security: + authentication: + jwt: + # This token must be encoded using Base64 (you can type `echo 'secret-key'|base64` on your command line) + base64-secret: MzY1ZDU0MDM3M2Y5YWRiMDYxYjBmYzZlOTMxMWFiNmYyMDEyZTUzZjYxOWFjNjhlNjU2NzcxYjkwY2Y0MGIwOGUyNTc5NWQyOGY3OGJkMjExZjhkYzU3ZGU4ZDc0ZmZiMTYwMzY0NGM4ZWZmODRhZTZjNzBlNjk5MWJkYjM5YjI= + # Token is valid 24 hours + token-validity-in-seconds: 86400 + token-validity-in-seconds-for-remember-me: 86400 + +# =================================================================== +# Application specific properties +# Add your own application properties here, see the ApplicationProperties class +# to have type-safe configuration, like in the JHipsterProperties above +# +# More documentation is available at: +# https://www.jhipster.tech/common-application-properties/ +# =================================================================== + +# application: +management: + health: + mail: + enabled: false diff --git a/src/test/resources/i18n/messages_en.properties b/src/test/resources/i18n/messages_en.properties new file mode 100644 index 0000000..d1e6fd7 --- /dev/null +++ b/src/test/resources/i18n/messages_en.properties @@ -0,0 +1,4 @@ +email.test.title=test title +# Value used for English locale unit test in MailServiceIT +# as this file is loaded instead of real file +email.activation.title=questionBank account activation diff --git a/src/test/resources/junit-platform.properties b/src/test/resources/junit-platform.properties new file mode 100644 index 0000000..80967e2 --- /dev/null +++ b/src/test/resources/junit-platform.properties @@ -0,0 +1,4 @@ +junit.jupiter.execution.timeout.default = 15 s +junit.jupiter.execution.timeout.testable.method.default = 15 s +junit.jupiter.execution.timeout.beforeall.method.default = 60 s +junit.jupiter.testclass.order.default=com.example.questionbank.config.SpringBootTestClassOrderer diff --git a/src/test/resources/logback.xml b/src/test/resources/logback.xml new file mode 100644 index 0000000..05b86b5 --- /dev/null +++ b/src/test/resources/logback.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/templates/mail/activationEmail.html b/src/test/resources/templates/mail/activationEmail.html new file mode 100644 index 0000000..6db87f6 --- /dev/null +++ b/src/test/resources/templates/mail/activationEmail.html @@ -0,0 +1,19 @@ + + + + JHipster activation + + + +

Dear

+

Your JHipster account has been created, please click on the URL below to activate it:

+

+ Activation link +

+

+ Regards, +
+ JHipster. +

+ + diff --git a/src/test/resources/templates/mail/creationEmail.html b/src/test/resources/templates/mail/creationEmail.html new file mode 100644 index 0000000..07075e0 --- /dev/null +++ b/src/test/resources/templates/mail/creationEmail.html @@ -0,0 +1,19 @@ + + + + JHipster creation + + + +

Dear

+

Your JHipster account has been created, please click on the URL below to access it:

+

+ Login link +

+

+ Regards, +
+ JHipster. +

+ + diff --git a/src/test/resources/templates/mail/passwordResetEmail.html b/src/test/resources/templates/mail/passwordResetEmail.html new file mode 100644 index 0000000..6ddc5d2 --- /dev/null +++ b/src/test/resources/templates/mail/passwordResetEmail.html @@ -0,0 +1,21 @@ + + + + JHipster password reset + + + +

Dear

+

+ For your JHipster account a password reset was requested, please click on the URL below to reset it: +

+

+ Login link +

+

+ Regards, +
+ JHipster. +

+ + diff --git a/src/test/resources/templates/mail/testEmail.html b/src/test/resources/templates/mail/testEmail.html new file mode 100644 index 0000000..a4ca16a --- /dev/null +++ b/src/test/resources/templates/mail/testEmail.html @@ -0,0 +1 @@ + diff --git a/tsconfig.app.json b/tsconfig.app.json new file mode 100644 index 0000000..786f59d --- /dev/null +++ b/tsconfig.app.json @@ -0,0 +1,13 @@ +{ + "extends": "@vue/tsconfig/tsconfig.dom.json", + "include": ["src/main/webapp/**/*", "src/main/webapp/app/**/*.vue"], + "exclude": ["src/main/webapp/app/**/*.spec.ts"], + "compilerOptions": { + "composite": true, + "outDir": "target/out-tsc/dist", + "types": ["vite/client"], + "paths": { + "@/*": ["./src/main/webapp/app/*"] + } + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..100cf6a --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,14 @@ +{ + "files": [], + "references": [ + { + "path": "./tsconfig.node.json" + }, + { + "path": "./tsconfig.app.json" + }, + { + "path": "./tsconfig.vitest.json" + } + ] +} diff --git a/tsconfig.node.json b/tsconfig.node.json new file mode 100644 index 0000000..8126dfa --- /dev/null +++ b/tsconfig.node.json @@ -0,0 +1,11 @@ +{ + "extends": "@tsconfig/node18/tsconfig.json", + "include": ["vite.config.*", "vitest.config.*"], + "compilerOptions": { + "composite": true, + "lib": ["ES2025"], + "module": "ESNext", + "moduleResolution": "Bundler", + "types": ["node"] + } +} diff --git a/tsconfig.vitest.json b/tsconfig.vitest.json new file mode 100644 index 0000000..d080d61 --- /dev/null +++ b/tsconfig.vitest.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.app.json", + "exclude": [], + "compilerOptions": { + "composite": true, + "lib": [], + "types": ["node", "jsdom"] + } +} diff --git a/vite.config.ts b/vite.config.ts new file mode 100644 index 0000000..eb4d2f1 --- /dev/null +++ b/vite.config.ts @@ -0,0 +1,76 @@ +import path from 'node:path'; +import { URL, fileURLToPath } from 'node:url'; + +import vue from '@vitejs/plugin-vue'; +import { defineConfig, normalizePath } from 'vite'; +import { viteStaticCopy } from 'vite-plugin-static-copy'; + +const { getAbsoluteFSPath } = await import('swagger-ui-dist'); +const swaggerUiPath = getAbsoluteFSPath(); +const webappDir = fileURLToPath(new URL('./src/main/webapp/', import.meta.url)); + +const config = defineConfig({ + plugins: [ + vue(), + viteStaticCopy({ + targets: [ + { + src: [ + `${normalizePath(swaggerUiPath)}/*.{js,css,html,png}`, + `!${normalizePath(swaggerUiPath)}/**/index.html`, + normalizePath(fileURLToPath(new URL('./dist/axios.min.js', import.meta.resolve('axios/package.json')))), + normalizePath(fileURLToPath(new URL('./src/main/webapp/swagger-ui/index.html', import.meta.url))), + ], + dest: 'swagger-ui', + rename: (name, ext, srcPath) => { + const rel = path.relative(webappDir, path.dirname(srcPath)).replace(/^(\.\.\/)+/, ''); + return `${'../'.repeat(rel === '.' ? 0 : rel.split('/').length)}${name}.${ext}`; + }, + }, + ], + }), + ], + root: fileURLToPath(new URL('./src/main/webapp/', import.meta.url)), + publicDir: fileURLToPath(new URL('./target/classes/static/public', import.meta.url)), + cacheDir: fileURLToPath(new URL('./target/.vite-cache', import.meta.url)), + optimizeDeps: { + // Discover dependencies of lazily loaded modules (translations, ...) at startup, + // a dependency discovered at runtime triggers a re-optimization and a page reload. + entries: [fileURLToPath(new URL('./src/main/webapp/**/*.{ts,vue,js}', import.meta.url))], + }, + build: { + emptyOutDir: true, + outDir: fileURLToPath(new URL('./target/classes/static/', import.meta.url)), + rollupOptions: { + input: { + app: fileURLToPath(new URL('./src/main/webapp/index.html', import.meta.url)), + }, + }, + }, + resolve: { + tsconfigPaths: true, + alias: { + vue: 'vue/dist/vue.esm-bundler.js', + }, + }, + define: { + SERVER_API_URL: '"/"', + APP_VERSION: `"${process.env.APP_VERSION ? process.env.APP_VERSION : 'DEV'}"`, + }, + server: { + host: true, + port: 9000, + proxy: Object.fromEntries( + ['/api', '/management', '/v3/api-docs'].map(res => [ + res, + { + target: 'http://localhost:8080', + }, + ]), + ), + }, +}); + +// jhipster-needle-add-vite-config - JHipster will add custom config + +export default config; diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..888dc73 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url'; + +import { defineConfig, mergeConfig } from 'vitest/config'; + +import viteConfig from './vite.config.ts'; + +export default mergeConfig( + viteConfig, + defineConfig({ + resolve: { + alias: { + vue: 'vue', + }, + }, + test: { + globals: true, + environment: 'happy-dom', // happy-dom provides a better performance but doesn't have a default url. + setupFiles: [fileURLToPath(new URL('./src/main/webapp/app/test-setup.ts', import.meta.url))], + reporters: ['default', 'vitest-sonar-reporter'], + outputFile: { + 'vitest-sonar-reporter': fileURLToPath(new URL('./target/test-results/TESTS-results-vitest.xml', import.meta.url)), + }, + coverage: { + provider: 'v8', + statements: 85, + branches: 75, + lines: 85, + reportsDirectory: fileURLToPath(new URL('./target/vite-coverage', import.meta.url)), + }, + }, + }), +);