11 Commits

Author SHA1 Message Date
Paulo Gustavo Veiga
f3afdc04cd Merge branch 'develop' 2022-03-27 15:02:24 -03:00
Paulo Gustavo Veiga
ef43e2889e Merge branch 'develop' 2022-03-27 14:56:51 -03:00
Paulo Gustavo Veiga
fe3a5f884b Merge branch 'develop' 2022-03-14 00:08:58 -03:00
Paulo Gustavo Veiga
e8c86bd159 Merge branch 'develop' 2022-02-23 06:59:36 -08:00
Paulo Gustavo Veiga
51b5de2eed Release 5.0.5 2022-02-16 18:43:21 -08:00
Paulo Gustavo Veiga
c84a583c3f Merge branch 'develop' 2022-02-16 18:41:21 -08:00
Paulo Gustavo Veiga
18c67233da Improve JS error loggin 2022-02-11 23:56:53 -08:00
Paulo Gustavo Veiga
d567caa61c Merge branch 'develop' 2022-02-11 18:09:30 -08:00
Paulo Gustavo Veiga
41561a3a8a Bump up version 2022-02-08 17:38:03 -08:00
Paulo Gustavo Veiga
70fba42683 Merge branch 'develop' 2022-02-08 17:32:39 -08:00
Paulo Gustavo Veiga
644b7078d7 Bump up version 2020-11-23 18:58:25 -08:00
271 changed files with 7049 additions and 6109 deletions

View File

@@ -1,35 +0,0 @@
# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
name: WiseMapping API
on:
push:
branches: [ "develop" ]
pull_request:
branches: [ "develop" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up JDK 21
uses: actions/setup-java@v3
with:
java-version: '21'
distribution: 'zulu'
cache: maven
- name: Build with Maven
run: mvn -B clean package --file wise-api/pom.xml
- name: Build the Docker image
run: docker build -t wisemapping/wisemapping-api:latest wise-api
# Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive
#- name: Update dependency graph
# uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6

View File

@@ -1,15 +0,0 @@
# WiseMapping Public License Version 1.0 (WPL)
WiseMapping open source edition is licensed under the WiseMapping Public License Version 1.0. It is basically Apache License Version 2.0 plus the "powered by wisemapping" text requirement on every single page (the "License") unless we authorize you to remove it.
The WiseMapping Public License Version 1.0 ("WPL") consists of the [APACHE LICENSE, VERSION 2.0](http://www.apache.org/licenses/LICENSE-2.0), modified to be specific to WiseMapping, with the Additional Terms in Exhibit B.
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.
## EXHIBIT B - WiseMapping Public License.
Additional Terms applicable to the WiseMapping Public License.
I. Effect.
These additional terms described in this wiseMapping Public License - Additional Terms shall apply to the Covered Code under this License.
II. WiseMapping and "powered by WiseMapping" text.
This License does not grant any rights to use the trademarks "WiseMapping" even if such marks are included in the Original Code or Modifications.
However, in addition to the other notice obligations, unless wisemapping founders authorize you by email not to do it, (1) all copies of the Original Code in Executable and Source Code form must, as a form of attribution of the original author, include on each user interface screen (i) the "powered by WiseMapping" text; and (2) all derivative works and copies of derivative works of the Covered Code in Executable and Source Code form must include on each user interface screen (i) the "powered by WiseMapping" text. In addition, the "powered by WiseMapping" text, as appropriate, must be visible to all users, must appear in each user interface screen, and must be in the same position. When users click on the "powered by WiseMapping" text it must direct them to http://www.wisemapping.com. This obligation shall also apply to any copies or derivative works which are distributed under the alternative terms of Section 3.6 and this obligation must be included in any such license

View File

@@ -1,89 +1,75 @@
# WiseMapping Open Source
# Overview
WiseMapping is an open-source web-based mind mapping tool that harnesses the potential of Mind Maps by blending together open standards technologies like SVG and React. It is built upon the foundation of the code supporting http://www.wisemapping.com, ensuring reliability and continuity in its development.
Wise Mapping is the web mind mapping open source tool that leverages the power of Mind Maps mixing open standards technologies such as SVG and React.
WiseMapping is based on the same code product supporting [http://www.wisemapping.com].
# Build and Start Application
## Compiling and Running
The following section describes the steps to check out, compile, and start WiseMapping locally. If you are interested in deploying it, I recommend using the already published images https://hub.docker.com/r/wisemapping/wisemapping.
### Prerequisites
## Prerequisites
The following products must be installed:
* JDK 21 or higher
* Maven v3.x or higher ([http://maven.apache.org/])
* Yarn v1 or higher
* Node v18 or higher
* OpenJDK 11 or higher
* Maven 3.x or higher ([http://maven.apache.org/])
* npm 6 or higher ([https://www.npmjs.com/package/npm?activeTab=versions])
## Option 1: Quick Start with Docker Compose
### Compiling
The following command line will start WiseMapping locally using HSQLDB in memory for development purposes:
WiseMapping uses Maven as packaging and project management. It's composed of 5 maven sub-modules:
```
$ mvn -f wise-api/pom.xml package
$ docker compose up --build
```
* wise-ui: React font-end fetcher
* wise-webapp: J2EE web application
Application will start at http://localhost/c/login. You can login using *test@wisemapping.org* and password *test*
The full compilation of the project can be performed executing within <project-dir>:
## Option 2: Start Frontend and Backend API
`mvn clean install`
### Compile and Start API
Once this command is executed, the file <project-dir>/wise-webapp/target/wisemapping*.war will be generated.
```
$ mvn -f wise-api/pom.xml package
$ cd wise-api
$ mvn spring-boot:run
```
### Local Development
The previously generated war can be deployed locally executing within the directory <project-dir>/wise-webapp the following command:
### Compile and Start Frontend
`cd wise-webapp;mvn jetty:run-war`
You need to checkout https://github.com/wisemapping/wisemapping-frontend first. Then, follow the next steps:
This will start the application on the URL: [http://localhost:8080/] using file based database.
```
$ export NODE_OPTIONS=--openssl-legacy-provider
$ export APP_CONFIG_TYPE="file:dev"
User: test@wisemapping.org
Password: test
$ cd wisemapping-frontend
$ yarn install
$ yarn build
### Local Development + UI Integration
$ cd packages/webapp; yarn start
```
Application will start at http://localhost:3000/c/login. You can login using *test@wisemapping.org* and password *test*
In order to reduce the life-cycle to develop UI backend testing, you can do the following hack:
# Supportability Matrix
* Clone [wisemapping-open-source](https://bitbucket.org/wisemapping/wisemapping-open-source/) and [wisemapping-frontend](https://bitbucket.org/wisemapping/wisemapping-frontend/) at the same top level directory
* Compile `wisemapping-frontend`. Details for compilation can be found in the `wisemapping-frontend` readme.
* Compile `wisemapping-open-source`
## Databases
A quick and dirty solution to share changes in the UI is to manually compile the dist. This will make the loader file available without the need to publish:
* MySQL v8 or higher
* PostgreSQL v15 or higher
* Hsqldb v2.7 or higher
`yarn --cwd wisemapping-frontend build;cp -r wisemapping-frontend/packages/mindplot/dist/* wisemapping-open-source/wise-ui/target/wisemapping-mindplot/package/dist;cp -r wisemapping-frontend/packages/mindplot/dist/* wisemapping-open-source/wise-ui/target/wisemapping-mindplot/package/dist`
# Configuration
WiseMapping backend is based on SpringBoot v3 and it's highly customizable. Additional documentation can be found [here](https://docs.spring.io/spring-boot/3.3/reference/features/external-config.html)
### Compiling and running with docker-compose
The perfered option is to extended by overwriting [application.yaml](https://github.com/wisemapping/wisemapping-open-source/blob/develop/wise-api/src/main/resources/application.yml)
Check out the [docker section](./docker/README.
```
$ java -jar target/wisemapping-api.jar --spring.config.additional-location=../../wise-conf/app.yml
```
## Members
For example, this [example](https://github.com/wisemapping/wisemapping-open-source/blob/develop/config/database/postgresql/app-postgresql.yaml) configure PostgreSQL as database.
# Members
## Founders
### Founders
* Paulo Veiga <pveiga@wisemapping.com>
* Pablo Luna <pablo@wisemapping.com>
## Past Individual Contributors
### Individual Contributors
* Ignacio Manzano
* Ezequiel Bergamaschi <ezequielbergamaschi@gmail.com>
### Past Individual Contributors
* Ignacio Manzano
## License
The source code is Licensed under the WiseMapping Open License, Version 1.0 (the “License”);
You may obtain a copy of the License at: [https://github.com/wisemapping/wisemapping-open-source/blob/develop/LICENSE.md](https://github.com/wisemapping/wisemapping-open-source/blob/develop/LICENSE.md)
You may obtain a copy of the License at: [https://wisemapping.atlassian.net/wiki/display/WS/License]

39
bitbucket-pipelines.yml Normal file
View File

@@ -0,0 +1,39 @@
# Template maven-build
# This template allows you to test and build your Java project with Maven.
# The workflow allows running tests, code checkstyle and security scans on the default branch.
# Prerequisites: pom.xml and appropriate project structure should exist in the repository.
image: maven:3.6.3
pipelines:
branches:
'{master,develop}':
- step:
name: Build and Test
caches:
- node
- maven
- docker
script:
# Compile sources ...
- curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.36.0/install.sh | bash
- . $HOME/.nvm/nvm.sh && nvm install node
- mvn -B verify --file pom.xml
# Publish to docker repo ...
- docker login --username $DOCKER_USERNAME --password $DOCKER_PASSWORD
- docker build -t wisemapping/wisemapping:latest -f distribution/Dockerfile wise-webapp/target/
- docker push wisemapping/wisemapping:latest
after-script:
# Collect checkstyle results, if any, and convert to Bitbucket Code Insights.
- pipe: atlassian/checkstyle-report:0.3.0
services:
- docker
- step:
name: Security Scan
script:
# Run a security scan for sensitive data.
# See more security tools at https://bitbucket.org/product/features/pipelines/integrations?&category=security
- pipe: atlassian/git-secrets-scan:0.5.1

View File

@@ -1,45 +0,0 @@
# Database Configuration
## Overview
WiseMapping supports a wide variety of databases. However, we run intensively tests over HSQL and MySQL database.
* HyperSQL: Automatically configured when you compile WiseMapping and It's used primarily for testing. Additionally, the binary distribution already has an instance configured to provide a single click installation.
* MySQL: This version is the most tested database we support. MySQL is the database use in http://www.wisemapping.com and it's the suggested version for production environments.
* PostgreSQL: Scripts are distributed for the creation and configuration of the it. You will find them within "config/postgres" directory in the binary distribution. Additionally, JDBC driver need to be added to the container.
* Others: In spite of the fact that we don't provide yet initialization scripts for others databases, WiseMapping can be deployed in any relational database. Please, contact us if you have any particular question on this area.
* In the following section, you are going to find a detailed explanation how to configure you WiseMapping using MySQL 5.5.
## MySQL Installation
### Prerequisites
* Download and install MySQL. You can download it for free from: http://dev.mysql.com/downloads/
Running SQL Scripts
Inside the WiseMapping binary distribution, you will find a directory "config/mysql". It contains all the SQL script required to configure a new WiseMapping database instance.
You will find 4 scripts:
* create-database.sql: Create all wisemapping database and wisemapping user.
* create-schemas.sql: Create all database tables and index.
* apopulate-schemas.sql: Creates a mind map example and an a test user "test@wisemapping.org" with password "test".
* drop-schemas.sql: Drop all wisemapping tables in case you want to have a fresh installation.
There are a lot of good tools you can use to run this scripts (eg: MySQLWorkbench). However, the simples way is to use the command line tool that is distributed as part of the MySQL installation.
If you are one brave hearts that is not afraid of the command line tools, open a terminar and execute the following lines:
~~~~
cd <WISEMAPPING-DIR>/config/database/mysql
# Default MySQL installation creates a "root" user with empty password. You can connect to the database with this user if you are # logged in same machine where the database is installed and must be executed logged as "root"
#
# If you have changed the default database "root" password , you need to specify an additional -p parameter and provide the
# new password.
mysql -uroot < create-database.sql
# Create tables and default tests user
mysql -uwisemapping -Dwisemapping -ppassword < create-schemas.sql
mysql -uwisemapping -Dwisemapping -ppassword < apopulate-schemas.sql
~~~~
Great, you have configured you database !. Let's configure WiseMapping now.

View File

@@ -0,0 +1,10 @@
INSERT INTO COLLABORATOR (id, email, creation_date) VALUES (1, 'test@wisemapping.org', CURDATE());
INSERT INTO USER (colaborator_id, firstname, lastname, password, activation_code, activation_date, allow_send_email,authentication_type)
VALUES (1, 'Test', 'User', 'ENC:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', 1237, CURDATE(), 1,'D');
INSERT INTO COLLABORATOR (id, email, creation_date) VALUES (2, 'admin@wisemapping.org', CURDATE());
INSERT INTO USER (colaborator_id, firstname, lastname, password, activation_code, activation_date, allow_send_email,authentication_type)
VALUES (2, 'Admin', 'User', 'ENC:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', 1237, CURDATE(), 1,'D');
COMMIT;
SHUTDOWN;

View File

@@ -0,0 +1,96 @@
CREATE TABLE COLLABORATOR (
id INTEGER NOT NULL IDENTITY,
email VARCHAR(255) NOT NULL,
creation_date DATE
);
CREATE TABLE USER (
colaborator_id INTEGER NOT NULL IDENTITY,
authentication_type CHAR(1) NOT NULL,
authenticator_uri VARCHAR(255) NULL,
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
activation_code BIGINT NOT NULL,
activation_date DATE,
allow_send_email CHAR(1) NOT NULL,
locale VARCHAR(5),
FOREIGN KEY (colaborator_id) REFERENCES COLLABORATOR (id)
);
CREATE TABLE MINDMAP (
id INTEGER NOT NULL IDENTITY,
title VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
xml LONGVARBINARY NOT NULL,
public BOOLEAN NOT NULL,
creation_date DATETIME,
edition_date DATETIME,
creator_id INTEGER NOT NULL,
tags VARCHAR(1014),
last_editor_id INTEGER NOT NULL
--FOREIGN KEY(creator_id) REFERENCES USER(colaborator_id)
);
CREATE TABLE LABEL (
id INTEGER NOT NULL PRIMARY KEY IDENTITY,
title VARCHAR(30),
creator_id INTEGER NOT NULL,
parent_label_id INTEGER,
color VARCHAR(7) NOT NULL,
iconName VARCHAR(50) NOT NULL
--FOREIGN KEY (creator_id) REFERENCES USER (colaborator_id)
);
CREATE TABLE R_LABEL_MINDMAP (
mindmap_id INTEGER NOT NULL,
label_id INTEGER NOT NULL,
PRIMARY KEY (mindmap_id, label_id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id),
FOREIGN KEY (label_id) REFERENCES LABEL (id) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE TABLE MINDMAP_HISTORY (
id INTEGER NOT NULL IDENTITY,
xml LONGVARBINARY NOT NULL,
mindmap_id INTEGER NOT NULL,
creation_date DATETIME,
editor_id INTEGER NOT NULL,
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id)
);
CREATE TABLE COLLABORATION_PROPERTIES (
id INTEGER NOT NULL IDENTITY,
starred BOOLEAN NOT NULL,
mindmap_properties VARCHAR(512)
);
CREATE TABLE COLLABORATION (
id INTEGER NOT NULL IDENTITY,
colaborator_id INTEGER NOT NULL,
properties_id INTEGER NOT NULL,
mindmap_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
FOREIGN KEY (colaborator_id) REFERENCES COLLABORATOR (id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id),
FOREIGN KEY (properties_id) REFERENCES COLLABORATION_PROPERTIES (id)
);
CREATE TABLE TAG (
id INTEGER NOT NULL IDENTITY,
name VARCHAR(255) NOT NULL,
user_id INTEGER NOT NULL,
--FOREIGN KEY(user_id) REFERENCES USER(colaborator_id)
);
CREATE TABLE ACCESS_AUDITORY (
id INTEGER NOT NULL IDENTITY,
user_id INTEGER NOT NULL,
login_date DATE,
FOREIGN KEY (user_id) REFERENCES USER (colaborator_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
);
COMMIT;

View File

@@ -0,0 +1,11 @@
DROP TABLE IF EXISTS ACCESS_AUDITORY;
DROP TABLE IF EXISTS TAG;
DROP TABLE IF EXISTS COLLABORATION;
DROP TABLE IF EXISTS COLLABORATION_PROPERTIES;
DROP TABLE IF EXISTS MINDMAP_HISTORY;
DROP TABLE IF EXISTS R_LABEL_MINDMAP;
DROP TABLE IF EXISTS LABEL;
DROP TABLE IF EXISTS MINDMAP;
DROP TABLE IF EXISTS USER;
DROP TABLE IF EXISTS COLLABORATOR;
COMMIT;

View File

@@ -1,10 +0,0 @@
RENAME TABLE USER TO ACCOUNT;
RENAME TABLE LABEL TO MINDMAP_LABEL;
ALTER TABLE COLLABORATION
RENAME COLUMN colaborator_id to collaborator_id;
ALTER TABLE ACCOUNT
RENAME COLUMN colaborator_id to collaborator_id;
ALTER TABLE MINDMAP_LABEL DROP COLUMN iconName;

View File

@@ -0,0 +1,13 @@
#
# Command: mysql -u root -p < apopulate_schemas.sql
#
INSERT INTO COLLABORATOR (id, email, creation_date) VALUES (1, 'test@wisemapping.org', CURRENT_DATE());
INSERT INTO USER (colaborator_id, firstname, lastname, password, activation_code, activation_date, allow_send_email,authentication_type)
VALUES (1, 'Test', 'User', 'ENC:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', 1237, CURRENT_DATE(), 1,'D');
INSERT INTO COLLABORATOR (id, email, creation_date) VALUES (2, 'admin@wisemapping.org', CURRENT_DATE());
INSERT INTO USER (colaborator_id, firstname, lastname, password, activation_code, activation_date, allow_send_email,authentication_type)
VALUES (2, 'Admin', 'User', 'ENC:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', 1237, CURRENT_DATE(), 1,'D');
COMMIT;

View File

@@ -1,14 +0,0 @@
spring:
datasource:
url: jdbc:mysql://localhost:3306/wisemapping?useUnicode=yes&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
password: password
username: wisemapping
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.MySQLDialect
sql:
init:
platform: mysql

View File

@@ -1,12 +1,10 @@
#
# Command: mysql -u root -p < create-database.sql
#
DROP DATABASE IF EXISTS wisemapping;
CREATE DATABASE IF NOT EXISTS wisemapping
CHARACTER SET = 'utf8'
COLLATE = 'utf8_unicode_ci';
CREATE USER 'wisemapping'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON wisemapping.* TO 'wisemapping'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
#
# Command: mysql -u root -p < create_database.sql
#
DROP DATABASE IF EXISTS wisemapping;
CREATE DATABASE IF NOT EXISTS wisemapping
CHARACTER SET = 'utf8'
COLLATE = 'utf8_unicode_ci';
GRANT ALL ON wisemapping.* TO 'wisemapping'@'localhost';
SET PASSWORD FOR 'wisemapping'@'localhost' = PASSWORD('password');

View File

@@ -1,117 +1,137 @@
CREATE TABLE IF NOT EXISTS COLLABORATOR (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(255) CHARACTER SET UTF8MB4 NOT NULL UNIQUE,
creation_date DATE
)
CHARACTER SET UTF8MB4;
CREATE TABLE IF NOT EXISTS ACCOUNT (
collaborator_id INTEGER NOT NULL PRIMARY KEY,
authentication_type CHAR(1)
CHARACTER SET UTF8MB4 NOT NULL,
authenticator_uri VARCHAR(255)
CHARACTER SET utf8,
firstname VARCHAR(255) CHARACTER SET UTF8MB4 NOT NULL,
lastname VARCHAR(255) CHARACTER SET UTF8MB4 NOT NULL,
password VARCHAR(255) CHARACTER SET UTF8MB4 NOT NULL,
activation_code BIGINT(20) NOT NULL,
activation_date DATE,
allow_send_email CHAR(1) CHARACTER SET UTF8MB4 NOT NULL DEFAULT 0,
locale VARCHAR(5),
google_sync BOOL,
sync_code VARCHAR(255),
google_token VARCHAR(255),
FOREIGN KEY (collaborator_id) REFERENCES COLLABORATOR (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
) CHARACTER SET UTF8MB4;
CREATE TABLE IF NOT EXISTS MINDMAP (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255)
CHARACTER SET UTF8MB4 NOT NULL,
description VARCHAR(255)
CHARACTER SET utf8,
xml MEDIUMBLOB NOT NULL,
public BOOL NOT NULL DEFAULT 0,
creation_date DATETIME,
edition_date DATETIME,
creator_id INTEGER NOT NULL,
last_editor_id INTEGER NOT NULL,
FOREIGN KEY (creator_id) REFERENCES ACCOUNT (collaborator_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET UTF8MB4;
CREATE TABLE IF NOT EXISTS MINDMAP_LABEL (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(30)
CHARACTER SET UTF8MB4 NOT NULL,
creator_id INTEGER NOT NULL,
parent_label_id INTEGER,
color VARCHAR(7) NOT NULL,
FOREIGN KEY (creator_id) REFERENCES ACCOUNT (collaborator_id),
FOREIGN KEY (parent_label_id) REFERENCES MINDMAP_LABEL (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET UTF8MB4;
CREATE TABLE IF NOT EXISTS R_LABEL_MINDMAP (
mindmap_id INTEGER NOT NULL,
label_id INTEGER NOT NULL,
PRIMARY KEY (mindmap_id, label_id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id),
FOREIGN KEY (label_id) REFERENCES MINDMAP_LABEL (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET UTF8MB4;
CREATE TABLE IF NOT EXISTS MINDMAP_HISTORY
(id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
xml MEDIUMBLOB NOT NULL,
mindmap_id INTEGER NOT NULL,
creation_date DATETIME,
editor_id INTEGER NOT NULL,
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET UTF8MB4;
CREATE TABLE IF NOT EXISTS COLLABORATION_PROPERTIES (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
starred BOOL NOT NULL DEFAULT 0,
mindmap_properties VARCHAR(512)
CHARACTER SET utf8
)
CHARACTER SET UTF8MB4;
CREATE TABLE IF NOT EXISTS COLLABORATION (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
collaborator_id INTEGER NOT NULL,
properties_id INTEGER NOT NULL,
mindmap_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
UNIQUE KEY UC_ROLE (mindmap_id,collaborator_id),
FOREIGN KEY (collaborator_id) REFERENCES COLLABORATOR (id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id)
ON DELETE CASCADE
ON UPDATE NO ACTION,
FOREIGN KEY (properties_id) REFERENCES COLLABORATION_PROPERTIES (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET UTF8MB4;
CREATE TABLE IF NOT EXISTS ACCESS_AUDITORY (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
login_date DATE,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES ACCOUNT (collaborator_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET UTF8MB4;
#
# Command: mysql -u root -p < create_schemas.sql
#
USE wisemapping;
CREATE TABLE COLLABORATOR (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(255)
CHARACTER SET utf8 NOT NULL UNIQUE,
creation_date DATE
)
CHARACTER SET utf8;
CREATE TABLE USER (
colaborator_id INTEGER NOT NULL PRIMARY KEY,
authentication_type CHAR(1)
CHARACTER SET utf8 NOT NULL,
authenticator_uri VARCHAR(255)
CHARACTER SET utf8,
firstname VARCHAR(255) CHARACTER SET utf8 NOT NULL,
lastname VARCHAR(255) CHARACTER SET utf8 NOT NULL,
password VARCHAR(255) CHARACTER SET utf8 NOT NULL,
activation_code BIGINT(20) NOT NULL,
activation_date DATE,
allow_send_email CHAR(1) CHARACTER SET utf8 NOT NULL DEFAULT 0,
locale VARCHAR(5),
FOREIGN KEY (colaborator_id) REFERENCES COLLABORATOR (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE MINDMAP (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255)
CHARACTER SET utf8 NOT NULL,
description VARCHAR(255)
CHARACTER SET utf8 NOT NULL,
xml MEDIUMBLOB NOT NULL,
public BOOL NOT NULL DEFAULT 0,
creation_date DATETIME,
edition_date DATETIME,
creator_id INTEGER NOT NULL,
tags VARCHAR(1014)
CHARACTER SET utf8,
last_editor_id INTEGER NOT NULL,
FOREIGN KEY (creator_id) REFERENCES USER (colaborator_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE LABEL (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(30)
CHARACTER SET utf8 NOT NULL,
creator_id INTEGER NOT NULL,
parent_label_id INTEGER,
color VARCHAR(7) NOT NULL,
iconName VARCHAR(50) NOT NULL,
FOREIGN KEY (creator_id) REFERENCES USER (colaborator_id),
FOREIGN KEY (parent_label_id) REFERENCES LABEL (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE R_LABEL_MINDMAP (
mindmap_id INTEGER NOT NULL,
label_id INTEGER NOT NULL,
PRIMARY KEY (mindmap_id, label_id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id),
FOREIGN KEY (label_id) REFERENCES LABEL (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE MINDMAP_HISTORY
(id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
xml MEDIUMBLOB NOT NULL,
mindmap_id INTEGER NOT NULL,
creation_date DATETIME,
editor_id INTEGER NOT NULL,
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE COLLABORATION_PROPERTIES (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
starred BOOL NOT NULL DEFAULT 0,
mindmap_properties VARCHAR(512)
CHARACTER SET utf8
)
CHARACTER SET utf8;
CREATE TABLE COLLABORATION (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
colaborator_id INTEGER NOT NULL,
properties_id INTEGER NOT NULL,
mindmap_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
FOREIGN KEY (colaborator_id) REFERENCES COLLABORATOR (id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id)
ON DELETE CASCADE
ON UPDATE NO ACTION,
FOREIGN KEY (properties_id) REFERENCES COLLABORATION_PROPERTIES (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE TAG (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255)
CHARACTER SET utf8 NOT NULL,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES USER (colaborator_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE ACCESS_AUDITORY (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
login_date DATE,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES USER (colaborator_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
COMMIT;

View File

@@ -0,0 +1,11 @@
DROP TABLE IF EXISTS TAG;
DROP TABLE IF EXISTS ACCESS_AUDITORY;
DROP TABLE IF EXISTS COLLABORATION;
DROP TABLE IF EXISTS COLLABORATION_PROPERTIES;
DROP TABLE IF EXISTS MINDMAP_HISTORY;
DROP TABLE IF EXISTS LABEL;
DROP TABLE IF EXISTS MINDMAP;
DROP TABLE IF EXISTS R_LABEL_MINDMAP
DROP TABLE IF EXISTS USER;
DROP TABLE IF EXISTS COLLABORATOR;
COMMIT;

View File

@@ -0,0 +1,57 @@
CREATE TABLE COLLABORATION_PROPERTIES (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
starred BOOL NOT NULL DEFAULT 0,
mindmap_properties VARCHAR(512)
CHARACTER SET utf8
)
CHARACTER SET utf8;
DROP TABLE `MINDMAP_NATIVE`;
ALTER TABLE `MINDMAP_COLABORATOR` RENAME TO `COLLABORATION`;
ALTER TABLE `COLABORATOR` RENAME TO `COLLABORATOR`;
ALTER TABLE `MINDMAP` DROP COLUMN `editor_properties`, DROP COLUMN `mindMapNative_id`;
ALTER TABLE `MINDMAP` CHANGE COLUMN `owner_id` `creator_id` INT(11) NOT NULL
, DROP INDEX `owner_id`
, ADD INDEX `owner_id` (`creator_id` ASC);
ALTER TABLE `COLLABORATION` ADD COLUMN `properties_id` INT(11) NULL DEFAULT NULL
AFTER `role_id`;
DROP TABLE USER_LOGIN;
CREATE TABLE ACCESS_AUDITORY (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
user_id INTEGER NOT NULL,
login_date DATE
)
CHARACTER SET utf8;
#ALTER TABLE ACCESS_AUDITORY
# ADD CONSTRAINT `user_id`
# FOREIGN KEY ()
# REFERENCES `USER` ()
# ON DELETE CASCADE
# ON UPDATE NO ACTION
#, ADD INDEX `user_id` () ;
ALTER TABLE `MINDMAP_HISTORY` DROP COLUMN `creator_user`, ADD COLUMN `editor_id` INT(11) NULL DEFAULT NULL AFTER `creation_date`;
ALTER TABLE `USER` ADD COLUMN `locale` VARCHAR(5) NULL
AFTER `allowSendEmail`;
ALTER TABLE `MINDMAP` DROP COLUMN `last_editor`, ADD COLUMN `last_editor_id` INT(11) NULL DEFAULT 2
AFTER `tags`;
ALTER TABLE `USER` DROP COLUMN `username`, CHANGE COLUMN `activationCode` `activation_code` BIGINT(20) NOT NULL, CHANGE COLUMN `allowSendEmail` `allow_send_email` CHAR(1) NOT NULL DEFAULT '0';
INSERT INTO `MINDMAP` (`last_editor_id`) VALUES (1);
INSERT INTO `COLLABORATOR` (`id`, `email`, `creation_date`) VALUES (8081, 'migfake@wis.com', '2007-10-09');
DELETE FROM `USER`
WHERE activation_date IS null;
DROP TABLE FEEDBACK;
ALTER TABLE `MINDMAP` CHANGE COLUMN `XML` `XML` MEDIUMBLOB NULL DEFAULT NULL;
ALTER TABLE `MINDMAP_HISTORY` CHANGE COLUMN `XML` `XML` MEDIUMBLOB NULL DEFAULT NULL;

View File

@@ -0,0 +1,5 @@
ALTER TABLE `USER` ADD COLUMN `authentication_type` CHAR(1) CHARACTER SET utf8 NOT NULL DEFAULT 'D'
AFTER `colaborator_id`;
ALTER TABLE `USER` ADD COLUMN `authenticator_uri` VARCHAR(255) CHARACTER SET utf8
AFTER `authentication_type`;

View File

@@ -0,0 +1,37 @@
ALTER TABLE `USER` DROP COLUMN `id`;
ALTER TABLE `ACCESS_AUDITORY`
ADD CONSTRAINT
FOREIGN KEY (user_id) REFERENCES USER (colaborator_id)
ON DELETE CASCADE
ON UPDATE NO ACTION;
CREATE TABLE LABEL (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(30)
CHARACTER SET utf8 NOT NULL,
creator_id INTEGER NOT NULL,
parent_label_id INTEGER,
color VARCHAR(7) NOT NULL,
FOREIGN KEY (creator_id) REFERENCES USER (colaborator_id),
FOREIGN KEY (parent_label_id) REFERENCES LABEL (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE R_LABEL_MINDMAP (
mindmap_id INTEGER NOT NULL,
label_id INTEGER NOT NULL,
PRIMARY KEY (mindmap_id, label_id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id),
FOREIGN KEY (label_id) REFERENCES LABEL (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
ALTER TABLE `LABEL`
ADD COLUMN iconName VARCHAR(50) NOT NULL;
UPDATE LABEL SET iconName = 'glyphicon glyphicon-tag';

View File

@@ -0,0 +1,3 @@
CREATE DATABASE wisemapping;
CREATE USER wisemapping WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE wisemapping TO wisemapping;

View File

@@ -1,13 +1,13 @@
create TABLE IF NOT EXISTS COLLABORATOR (
CREATE TABLE COLLABORATOR (
id SERIAL NOT NULL PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
creation_date DATE
);
create TABLE IF NOT EXISTS ACCOUNT (
CREATE TABLE "user" (
authentication_type TEXT NOT NULL,
authenticator_uri VARCHAR(255),
collaborator_id INTEGER NOT NULL PRIMARY KEY,
colaborator_id INTEGER NOT NULL PRIMARY KEY,
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
@@ -15,71 +15,82 @@ create TABLE IF NOT EXISTS ACCOUNT (
activation_date DATE,
allow_send_email TEXT NOT NULL DEFAULT 0,
locale VARCHAR(5),
google_sync BOOLEAN,
sync_code VARCHAR(255),
google_token VARCHAR(255),
FOREIGN KEY (collaborator_id) REFERENCES COLLABORATOR (id) ON delete CASCADE ON update NO ACTION
FOREIGN KEY (colaborator_id) REFERENCES COLLABORATOR (id) ON DELETE CASCADE ON UPDATE NO ACTION
);
create TABLE IF NOT EXISTS MINDMAP_LABEL (
CREATE TABLE LABEL (
id INTEGER NOT NULL PRIMARY KEY,
title VARCHAR(255),
creator_id INTEGER NOT NULL,
parent_label_id INTEGER,
color VARCHAR(7) NOT NULL,
FOREIGN KEY (creator_id) REFERENCES ACCOUNT (collaborator_id)
color VARCHAR(7) NOT NULL
--FOREIGN KEY (creator_id) REFERENCES USER (colaborator_id)
);
create TABLE IF NOT EXISTS MINDMAP (
CREATE TABLE R_LABEL_MINDMAP (
mindmap_id INTEGER NOT NULL,
label_id INTEGER NOT NULL,
PRIMARY KEY (mindmap_id, label_id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id),
FOREIGN KEY (label_id) REFERENCES LABEL (id) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE TABLE MINDMAP (
id SERIAL NOT NULL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description VARCHAR(255),
description VARCHAR(255) NOT NULL,
xml BYTEA NOT NULL,
public BOOL NOT NULL DEFAULT FALSE,
creation_date TIMESTAMP,
edition_date TIMESTAMP,
creator_id INTEGER NOT NULL,
tags VARCHAR(1014),
last_editor_id INTEGER NOT NULL --,
--FOREIGN KEY(creator_id) REFERENCES "USER"(collaborator_id) ON DELETE CASCADE ON UPDATE NO ACTION
--FOREIGN KEY(creator_id) REFERENCES "USER"(colaborator_id) ON DELETE CASCADE ON UPDATE NO ACTION
);
create TABLE IF NOT EXISTS R_LABEL_MINDMAP (
mindmap_id INTEGER NOT NULL,
label_id INTEGER NOT NULL,
PRIMARY KEY (mindmap_id, label_id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id),
FOREIGN KEY (label_id) REFERENCES MINDMAP_LABEL (id) ON delete CASCADE ON update NO ACTION
);
create TABLE IF NOT EXISTS MINDMAP_HISTORY
CREATE TABLE MINDMAP_HISTORY
(id SERIAL NOT NULL PRIMARY KEY,
xml BYTEA NOT NULL,
mindmap_id INTEGER NOT NULL,
creation_date TIMESTAMP,
editor_id INTEGER NOT NULL,
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id) ON delete CASCADE ON update NO ACTION
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id) ON DELETE CASCADE ON UPDATE NO ACTION
);
create TABLE IF NOT EXISTS COLLABORATION_PROPERTIES (
CREATE TABLE COLLABORATION_PROPERTIES (
id SERIAL NOT NULL PRIMARY KEY,
starred BOOL NOT NULL DEFAULT FALSE,
mindmap_properties VARCHAR(512)
);
create TABLE IF NOT EXISTS COLLABORATION (
CREATE TABLE COLLABORATION (
id SERIAL NOT NULL PRIMARY KEY,
collaborator_id INTEGER NOT NULL,
colaborator_id INTEGER NOT NULL,
properties_id INTEGER NOT NULL,
mindmap_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
FOREIGN KEY (collaborator_id) REFERENCES COLLABORATOR (id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id) ON delete CASCADE ON update NO ACTION,
FOREIGN KEY (properties_id) REFERENCES COLLABORATION_PROPERTIES (id) ON delete CASCADE ON update NO ACTION
FOREIGN KEY (colaborator_id) REFERENCES COLLABORATOR (id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id) ON DELETE CASCADE ON UPDATE NO ACTION,
FOREIGN KEY (properties_id) REFERENCES COLLABORATION_PROPERTIES (id) ON DELETE CASCADE ON UPDATE NO ACTION
);
create TABLE IF NOT EXISTS ACCESS_AUDITORY (
CREATE TABLE TAG (
id SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
user_id INTEGER NOT NULL --,
--FOREIGN KEY(user_id) REFERENCES "USER"(colaborator_id) ON DELETE CASCADE ON UPDATE NO ACTION
);
CREATE TABLE ACCESS_AUDITORY (
id SERIAL NOT NULL PRIMARY KEY,
login_date DATE,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES ACCOUNT (collaborator_id) ON delete CASCADE ON update NO ACTION
);
FOREIGN KEY (user_id) REFERENCES "user" (colaborator_id) ON DELETE CASCADE ON UPDATE NO ACTION
);
COMMIT;

View File

@@ -0,0 +1,11 @@
DROP TABLE TAG;
DROP TABLE ACCESS_AUDITORY;
DROP TABLE COLLABORATION;
DROP TABLE COLLABORATION_PROPERTIES;
DROP TABLE MINDMAP_HISTORY;
DROP TABLE R_LABEL_MINDMAP;
DROP TABLE LABEL;
DROP TABLE MINDMAP;
DROP TABLE "user";
DROP TABLE COLLABORATOR;
COMMIT;

View File

@@ -1,14 +0,0 @@
spring:
datasource:
url: jdbc:postgresql://localhost/wisemapping
driver-class-name: org.postgresql.Driver
password: password
username: wisemapping
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
sql:
init:
platform: postgresql

View File

@@ -1,7 +0,0 @@
CREATE DATABASE wisemapping;
CREATE USER wisemapping WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE wisemapping TO wisemapping;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO wisemapping;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO wisemapping;

View File

@@ -2,8 +2,7 @@
# Based on ubuntu:latest, installs WiseMapping (http://ww.wisemapping.org)
# Based info setup ...
#FROM --platform=$BUILDPLATFORM tomcat:9.0.71-jdk17
FROM tomcat:10.1.11-jdk17
FROM tomcat:9.0-jdk17-openjdk
LABEL maintainer="Paulo Gustavo Veiga <pveiga@wisemapping.com>"
# Build variables ...
@@ -11,7 +10,7 @@ ARG WEBAPP_TARGET_DIR="/usr/local/tomcat/webapps/ROOT"
ARG DB_BASE_DIR="/var/lib/wisemapping"
# Default ENV configurations ...
ENV JAVA_OPTS="-XX:+PrintFlagsFinal -XX:InitialRAMPercentage=30 -XX:MaxRAMPercentage=80 -Dfile.encoding=UTF-8"
ENV JAVA_OPTS="-XX:+PrintFlagsFinal -XX:InitialRAMPercentage=30 -XX:MaxRAMPercentage=80"
ENV database.base.url=${DB_BASE_DIR}
# Copy wisemapping distribution ...
@@ -21,7 +20,7 @@ RUN cd ${WEBAPP_TARGET_DIR} && jar -xvf /tmp/wisemapping.war
RUN rm /tmp/wisemapping.war
# Change logger to
RUN cp ${WEBAPP_TARGET_DIR}/WEB-INF/log4j2-stdout.xml ${WEBAPP_TARGET_DIR}/WEB-INF/classes/log4j2.xml
RUN cp ${WEBAPP_TARGET_DIR}/WEB-INF/classes/log4j-stdout.properties ${WEBAPP_TARGET_DIR}/WEB-INF/classes/log4j.properties
# Add support for proxy
RUN sed -i 's|\

View File

@@ -9,27 +9,15 @@ There are multiple ways to run WiseMapping depending on your database configurat
## Option 1: Running HSQL within the image storage
> $ docker run -it --rm -p 8080:8080 wisemapping/wisemapping:latest
> $ docker run -it --rm -p 8080:8080 veigap/wisemapping:latest>
Then, open your browser at `http://localhost:8888`. A default user is available for testing `test@wisemapping.org` and password `test`.
Then, open your browser at `http://localhost:8888`. A default user is available for testing `test@wisemapping.com` and password `test`.
***This option, all changes will be lost once the image is stopped. Use it for testing only***
## Option 2: Running HSQL with mounted directory
Only one time, copy the empty default out of the container:
> $ mkdir your- db-dir-store-path
>
> $ docker run --name wiseapp -d --mount type=bind,source=your-db-dir-store-path,target=/var/lib/wise-db wisemapping/wisemapping:latest
>
> $ docker cp wiseapp:/var/lib/wisemapping/db your-db-dir-store-path
>
> $ docker stop wiseapp;docker rm wiseapp
Then, execute the container mounting tbe directory:
> $ docker run --mount type=bind,source=your-db-dir-store-path/db,target=/var/lib/wisemapping/db -it --rm -p 8080:8080 wisemapping/wisemapping:latest
> $ docker run -it --rm -p 8080:8080 veigap/wisemapping:latest
## Option 3: External MySQL/PostgreSQL
@@ -42,13 +30,13 @@ Depending on the database your want to configure, you can create initialization
The next step is configure the WiseMapping for the database and credentials.
Download `app.properties` configuration file and configure the required sections:
> $ curl https://bitbucket.org/wisemapping/wisemapping-open-source/src/master/wise-webapp/src/main/webapp/WEB-INF/app.properties
> $ curl https://bitbucket.org/wisemapping/wisemapping-open-source/raw/644b7078d790220c7844b732a83d45495f11d64e/wise-webapp/src/main/webapp/WEB-INF/app.properties
### Starting the application
Run the application mounting your previously configured `app.properties`
> $ docker run --mount type=bind,source=your-file-path/app.properties,target=/usr/local/tomcat/webapps/ROOT/WEB-INF/app.properties -it --rm -p 8080:8080 wisemapping/wisemapping:latest
> $ docker run --mount type=bind,source=your-file-path/app.properties,target=/usr/local/tomcat/webapps/ROOT/WEB-INF/app.properties -it --rm -p 8080:8080 veigap/wisemapping:latest
# Advanced configuration

View File

@@ -4,7 +4,4 @@ set -o
set -u
mvn -f ../pom.xml clean package
docker build --platform linux/amd64 -t wisemapping/wisemapping:latest -f ./Dockerfile ../wise-webapp/target/
#docker buildx create --use --platform=linux/arm64,linux/amd64 --name multi-platform-builder
#docker buildx inspect --bootstrap
#docker buildx build --platform=linux/amd64,linux/arm64 --push -t wisemapping/wisemapping:latest -f ./Dockerfile ../wise-webapp/target/
docker build -t wisemapping/wisemapping:latest -f ./Dockerfile ../wise-webapp/target/

View File

@@ -0,0 +1,10 @@
#
# Command: mysql -u root -p < create_database.sql
#
DROP DATABASE IF EXISTS wisemapping;
CREATE DATABASE IF NOT EXISTS wisemapping
CHARACTER SET = 'utf8'
COLLATE = 'utf8_unicode_ci';
GRANT ALL ON wisemapping.* TO 'wisemapping'@'localhost';
SET PASSWORD FOR 'wisemapping'@'localhost' = PASSWORD('password');

View File

@@ -0,0 +1,137 @@
#
# Command: mysql -u root -p < create_schemas.sql
#
USE wisemapping;
CREATE TABLE COLLABORATOR (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(255)
CHARACTER SET utf8 NOT NULL UNIQUE,
creation_date DATE
)
CHARACTER SET utf8;
CREATE TABLE USER (
colaborator_id INTEGER NOT NULL PRIMARY KEY,
authentication_type CHAR(1)
CHARACTER SET utf8 NOT NULL,
authenticator_uri VARCHAR(255)
CHARACTER SET utf8,
firstname VARCHAR(255) CHARACTER SET utf8 NOT NULL,
lastname VARCHAR(255) CHARACTER SET utf8 NOT NULL,
password VARCHAR(255) CHARACTER SET utf8 NOT NULL,
activation_code BIGINT(20) NOT NULL,
activation_date DATE,
allow_send_email CHAR(1) CHARACTER SET utf8 NOT NULL DEFAULT 0,
locale VARCHAR(5),
FOREIGN KEY (colaborator_id) REFERENCES COLLABORATOR (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE MINDMAP (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255)
CHARACTER SET utf8 NOT NULL,
description VARCHAR(255)
CHARACTER SET utf8 NOT NULL,
xml MEDIUMBLOB NOT NULL,
public BOOL NOT NULL DEFAULT 0,
creation_date DATETIME,
edition_date DATETIME,
creator_id INTEGER NOT NULL,
tags VARCHAR(1014)
CHARACTER SET utf8,
last_editor_id INTEGER NOT NULL,
FOREIGN KEY (creator_id) REFERENCES USER (colaborator_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE LABEL (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(30)
CHARACTER SET utf8 NOT NULL,
creator_id INTEGER NOT NULL,
parent_label_id INTEGER,
color VARCHAR(7) NOT NULL,
iconName VARCHAR(50) NOT NULL,
FOREIGN KEY (creator_id) REFERENCES USER (colaborator_id),
FOREIGN KEY (parent_label_id) REFERENCES LABEL (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE R_LABEL_MINDMAP (
mindmap_id INTEGER NOT NULL,
label_id INTEGER NOT NULL,
PRIMARY KEY (mindmap_id, label_id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id),
FOREIGN KEY (label_id) REFERENCES LABEL (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE MINDMAP_HISTORY
(id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
xml MEDIUMBLOB NOT NULL,
mindmap_id INTEGER NOT NULL,
creation_date DATETIME,
editor_id INTEGER NOT NULL,
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE COLLABORATION_PROPERTIES (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
starred BOOL NOT NULL DEFAULT 0,
mindmap_properties VARCHAR(512)
CHARACTER SET utf8
)
CHARACTER SET utf8;
CREATE TABLE COLLABORATION (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
colaborator_id INTEGER NOT NULL,
properties_id INTEGER NOT NULL,
mindmap_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
FOREIGN KEY (colaborator_id) REFERENCES COLLABORATOR (id),
FOREIGN KEY (mindmap_id) REFERENCES MINDMAP (id)
ON DELETE CASCADE
ON UPDATE NO ACTION,
FOREIGN KEY (properties_id) REFERENCES COLLABORATION_PROPERTIES (id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE TAG (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255)
CHARACTER SET utf8 NOT NULL,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES USER (colaborator_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
CREATE TABLE ACCESS_AUDITORY (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
login_date DATE,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES USER (colaborator_id)
ON DELETE CASCADE
ON UPDATE NO ACTION
)
CHARACTER SET utf8;
COMMIT;

View File

@@ -0,0 +1,13 @@
#
# Command: mysql -u root -p < apopulate_schemas.sql
#
INSERT INTO COLLABORATOR (id, email, creation_date) VALUES (1, 'test@wisemapping.org', CURRENT_DATE());
INSERT INTO USER (colaborator_id, firstname, lastname, password, activation_code, activation_date, allow_send_email,authentication_type)
VALUES (1, 'Test', 'User', 'ENC:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', 1237, CURRENT_DATE(), 1,'D');
INSERT INTO COLLABORATOR (id, email, creation_date) VALUES (2, 'admin@wisemapping.org', CURRENT_DATE());
INSERT INTO USER (colaborator_id, firstname, lastname, password, activation_code, activation_date, allow_send_email,authentication_type)
VALUES (2, 'Admin', 'User', 'ENC:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', 1237, CURRENT_DATE(), 1,'D');
COMMIT;

View File

@@ -1,4 +0,0 @@
ALTER TABLE USER
ADD COLUMN `google_sync` TINYINT(1) NULL,
ADD COLUMN `sync_code` VARCHAR(255) NULL,
ADD COLUMN `google_token` VARCHAR(255) NULL;

View File

@@ -1,4 +0,0 @@
ALTER TABLE "user"
ADD COLUMN `google_sync` BOOLEAN NULL,
ADD COLUMN `sync_code` VARCHAR(255) NULL,
ADD COLUMN `google_token` VARCHAR(255) NULL;

View File

@@ -1,22 +0,0 @@
version: '3'
services:
wise-api:
container_name: wise-api
hostname: wise-api
image: wise-api:latest
build:
context: ./wise-api
dockerfile: Dockerfile
ports:
- "8080:8080"
wise-ui:
container_name: wise-ui
image: wise-ui:latest
build:
context: ./wise-ui
dockerfile: Dockerfile
depends_on:
- wise-api
ports:
- "80:80"

15
license.txt Normal file
View File

@@ -0,0 +1,15 @@
Copyright [2014] [wisemapping]
Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
"powered by wisemapping" text requirement on every single page;
you may not use this file except in compliance with the License.
You may obtain a copy of the license at
http://www.wisemapping.org/license
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.

155
pom.xml Normal file
View File

@@ -0,0 +1,155 @@
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<properties>
<com.wisemapping.version>5.0.10</com.wisemapping.version>
<superpom.dir>${project.basedir}/wise-webapps</superpom.dir>
</properties>
<scm>
<developerConnection>scm:git:git@bitbucket.org:wisemapping/wisemapping-open-source.git</developerConnection>
</scm>
<modelVersion>4.0.0</modelVersion>
<groupId>org.wisemapping</groupId>
<artifactId>wisemapping</artifactId>
<name>WiseMapping Project</name>
<version>5.0.10</version>
<packaging>pom</packaging>
<licenses>
<license>
<name>WiseMapping Public License Version 1.0</name>
<url>http://www.wisemapping.org/wisemapping-public-license-version-1-0-wpl</url>
<comments>A business-friendly OSS license</comments>
</license>
</licenses>
<pluginRepositories>
<pluginRepository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Maven 2 Repository</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</pluginRepository>
</pluginRepositories>
<organization>
<name>WiseMapping</name>
<url>http://www.wisemapping.org/</url>
</organization>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12</version>
</plugin>
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<version>3.0.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.10</version>
</plugin>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>yuicompressor-maven-plugin</artifactId>
<version>1.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>native2ascii-maven-plugin</artifactId>
<version>1.0-beta-1</version>
</plugin>
<plugin>
<groupId>com.github.searls</groupId>
<artifactId>jasmine-maven-plugin</artifactId>
<version>1.3.1.5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.2</version>
<configuration>
<descriptors>
<descriptor>distribution/assembly/standalone-editor.xml</descriptor>
</descriptors>
</configuration>
</plugin>
</plugins>
</build>
<distributionManagement>
<site>
<id>www.wisemapping.org</id>
<url>scp://www.wisemapping.org/docs/project/</url>
</site>
</distributionManagement>
<!-- Module Dependencies -->
<modules>
<module>wise-ui</module>
<module>wise-webapp</module>
</modules>
</project>

View File

@@ -1,7 +0,0 @@
FROM amazoncorretto:21.0.2
LABEL maintainer="Paulo Gustavo Veiga <pveiga@wisemapping.com>"
VOLUME /tmp
COPY target/wisemapping-api.jar wisemapping-api.jar
ENTRYPOINT ["sh", "-c", "java ${JAVA_OPTS} -jar /wisemapping-api.jar ${0} ${@}"]

View File

@@ -1,232 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
</parent>
<groupId>org.wisemapping</groupId>
<artifactId>wise-api</artifactId>
<version>6.0.0-SNAPSHOT</version>
<name>WiseMapping API</name>
<url>https://www.wisemapping.org</url>
<properties>
<com.wisemapping.version>6.0.0-SNAPSHOT</com.wisemapping.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>6.1.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.intellij</groupId>
<artifactId>annotations</artifactId>
<version>12.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.3</version>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>8.0.1.Final</version>
</dependency>
<dependency>
<groupId>jakarta.mail</groupId>
<artifactId>jakarta.mail-api</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.angus</groupId>
<artifactId>jakarta.mail</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.20.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.7</version>
</dependency>
<!-- Connection Pool-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>5.1.0</version>
</dependency>
<!-- Only for test purposes -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.7.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.4</version>
</dependency>
<dependency>
<groupId>jakarta.transaction</groupId>
<artifactId>jakarta.transaction-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.15.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>4.5.14</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>6.2.1</version>
<scope>test</scope>
</dependency>
<!-- JWT dependencies -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<finalName>wisemapping-api</finalName>
</configuration>
</execution>
</executions>
<!-- <configuration>-->
<!-- <jvmArguments>-->
<!-- -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005-->
<!-- </jvmArguments>-->
<!-- </configuration>-->
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>https://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>

View File

@@ -1,26 +0,0 @@
package com.wisemapping;
import com.wisemapping.config.common.CommonConfig;
import com.wisemapping.config.rest.RestAppConfig;
import com.wisemapping.config.rest.WebConfig;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.security.web.firewall.StrictHttpFirewall;
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder()
.parent(CommonConfig.class).web(WebApplicationType.NONE)
.child(RestAppConfig.class, WebConfig.class).web(WebApplicationType.SERVLET)
.run(args);
}
@Bean
public StrictHttpFirewall httpFirewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowSemicolon(true);
return firewall;
}
}

View File

@@ -1,48 +0,0 @@
package com.wisemapping.config.common;
import com.wisemapping.dao.LabelManagerImpl;
import com.wisemapping.model.Account;
import com.wisemapping.security.AuthenticationProvider;
import com.wisemapping.security.Utils;
import com.wisemapping.service.MindmapServiceImpl;
import com.wisemapping.util.VelocityEngineUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import java.util.Locale;
@ComponentScan(basePackageClasses = {AuthenticationProvider.class, MindmapServiceImpl.class, LabelManagerImpl.class, VelocityEngineUtils.class})
@Import({JPAConfig.class, SecurityConfig.class})
@EnableAutoConfiguration
public class CommonConfig {
@Bean
public LocaleResolver localeResolver() {
return new AcceptHeaderLocaleResolver() {
@Override
public Locale resolveLocale(@NotNull HttpServletRequest request) {
final Account user = Utils.getUser();
Locale result;
if (user != null && user.getLocale() != null) {
String locale = user.getLocale();
final String locales[] = locale.split("_");
Locale.Builder builder = new Locale.Builder().setLanguage(locales[0]);
if (locales.length > 1) {
builder.setVariant(locales[1]);
}
result = builder.build();
} else {
result = super.resolveLocale(request);
}
return result;
}
};
}
}

View File

@@ -1,16 +0,0 @@
package com.wisemapping.config.common;
import com.wisemapping.dao.MindmapManagerImpl;
import com.wisemapping.model.Account;
import com.wisemapping.service.MindmapServiceImpl;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories(basePackageClasses={MindmapServiceImpl.class, MindmapManagerImpl.class})
@EntityScan(basePackageClasses= Account.class)
public class JPAConfig {
}

View File

@@ -1,76 +0,0 @@
package com.wisemapping.config.common;
import com.wisemapping.security.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(
securedEnabled = true,
jsr250Enabled = true)
public class SecurityConfig {
@Autowired
private ReadSecurityAdvise readAdvice;
@Autowired
private UpdateSecurityAdvise updateAdvice;
@Autowired
private UserDetailsService userDetailsService;
@Bean
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler =
new DefaultMethodSecurityExpressionHandler();
final MapAccessPermissionEvaluation permissionEvaluator = new MapAccessPermissionEvaluation(readAdvice, updateAdvice);
expressionHandler.setPermissionEvaluator(permissionEvaluator);
return expressionHandler;
}
@Bean
public PasswordEncoder passwordEncoder() {
return DefaultPasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
public AuthenticationProvider googleAuthenticationProvider() {
return new GoogleAuthenticationProvider(userDetailsService);
}
@Bean
public AuthenticationProvider dbAuthenticationProvider() {
final com.wisemapping.security.AuthenticationProvider provider =
new com.wisemapping.security.AuthenticationProvider();
provider.setEncoder(passwordEncoder());
provider.setUserDetailsService(userDetailsService);
return provider;
}
@Bean
public AuthenticationManager authenticationManager(@NotNull HttpSecurity http)
throws Exception {
final AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
builder.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
builder.authenticationProvider(dbAuthenticationProvider());
builder.authenticationProvider(googleAuthenticationProvider());
return builder.build();
}
}

View File

@@ -1,71 +0,0 @@
package com.wisemapping.config.rest;
import com.wisemapping.filter.JwtAuthenticationFilter;
import com.wisemapping.rest.MindmapController;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import static org.springframework.security.config.Customizer.withDefaults;
@SpringBootApplication(scanBasePackageClasses = {MindmapController.class, JwtAuthenticationFilter.class})
@EnableWebSecurity
public class RestAppConfig {
@Value("${app.api.http-basic-enabled:false}")
private boolean enableHttpBasic;
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Bean
MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) {
return new MvcRequestMatcher.Builder(introspector);
}
@Bean
SecurityFilterChain apiSecurityFilterChain(@NotNull final HttpSecurity http, @NotNull final MvcRequestMatcher.Builder mvc) throws Exception {
http
.securityMatcher("/**")
.addFilterAfter(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.authorizeHttpRequests(auth -> auth
.requestMatchers(mvc.pattern("/error")).permitAll()
.requestMatchers(mvc.pattern("/api/restful/authenticate")).permitAll()
.requestMatchers(mvc.pattern("/api/restful/users/")).permitAll()
.requestMatchers(mvc.pattern("/api/restful/app/config")).permitAll()
.requestMatchers(mvc.pattern("/api/restful/maps/*/metadata")).permitAll()
.requestMatchers(mvc.pattern("/api/restful/maps/*/document/xml-pub")).permitAll()
.requestMatchers(mvc.pattern("/api/restful/users/resetPassword")).permitAll()
.requestMatchers(mvc.pattern("/api/restful/oauth2/googlecallback")).permitAll()
.requestMatchers(mvc.pattern("/api/restful/oauth2/confirmaccountsync")).permitAll()
.requestMatchers(mvc.pattern("/api/restful/admin/**")).hasAnyRole("ADMIN")
.requestMatchers(mvc.pattern("/**")).hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
)
.logout(logout -> logout.permitAll()
.logoutSuccessHandler((request, response, authentication) -> {
response.setStatus(HttpServletResponse.SC_OK);
}))
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
// Http basic is mainly used by automation tests.
if (enableHttpBasic) {
http.httpBasic(withDefaults());
}
return http.build();
}
}

View File

@@ -1,27 +0,0 @@
package com.wisemapping.config.rest;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Value("${app.security.corsAllowedOrigins:}")
private String corsAllowedOrigins;
@Override
public void addCorsMappings(@NotNull CorsRegistry registry) {
if (!corsAllowedOrigins.isEmpty()) {
registry.addMapping("/api/**")
.exposedHeaders("*")
.allowedHeaders("*")
.allowedMethods("*")
.allowedOrigins(corsAllowedOrigins)
.maxAge(3600);
}
}
}

View File

@@ -1,26 +0,0 @@
package com.wisemapping.dao;
import com.wisemapping.model.MindmapLabel;
import com.wisemapping.model.Account;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public interface LabelManager {
void addLabel(@NotNull final MindmapLabel label);
void saveLabel(@NotNull final MindmapLabel label);
@NotNull
List<MindmapLabel> getAllLabels(@NotNull final Account user);
@Nullable
MindmapLabel getLabelById(int id, @NotNull final Account user);
@Nullable
MindmapLabel getLabelByTitle(@NotNull final String title, @NotNull final Account user);
void removeLabel(@NotNull final MindmapLabel label);
}

View File

@@ -1,89 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.dao;
import com.wisemapping.model.MindmapLabel;
import com.wisemapping.model.Account;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("labelManager")
public class LabelManagerImpl
implements LabelManager {
@Autowired
private EntityManager entityManager;
@Override
public void addLabel(@NotNull final MindmapLabel label) {
saveLabel(label);
}
@Override
public void saveLabel(@NotNull final MindmapLabel label) {
entityManager.persist(label);
}
@NotNull
@Override
public List<MindmapLabel> getAllLabels(@NotNull final Account user) {
final TypedQuery<MindmapLabel> query = entityManager.createQuery("from com.wisemapping.model.MindmapLabel wisemapping where creator=:creatorId", MindmapLabel.class);
query.setParameter("creatorId", user);
return query.getResultList();
}
@Nullable
@Override
public MindmapLabel getLabelById(int id, @NotNull final Account user) {
final TypedQuery<MindmapLabel> query = entityManager.createQuery("from com.wisemapping.model.MindmapLabel wisemapping where id=:id and creator=:creator", MindmapLabel.class);
query.setParameter("id", id);
query.setParameter("creator", user);
final List<MindmapLabel> resultList = query.getResultList();
return getFirst(resultList);
}
@Nullable
@Override
public MindmapLabel getLabelByTitle(@NotNull String title, @NotNull final Account user) {
final TypedQuery<MindmapLabel> query = entityManager.createQuery("from com.wisemapping.model.MindmapLabel wisemapping where title=:title and creator=:creator", MindmapLabel.class);
query.setParameter("title", title);
query.setParameter("creator", user);
return query.getResultList().stream().findFirst().orElse(null);
}
@Override
public void removeLabel(@NotNull MindmapLabel label) {
entityManager.remove(label);
}
@Nullable
private MindmapLabel getFirst(final List<MindmapLabel> labels) {
MindmapLabel result = null;
if (labels != null && !labels.isEmpty()) {
result = labels.get(0);
}
return result;
}
}

View File

@@ -1,188 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.dao;
import com.wisemapping.model.*;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Calendar;
import java.util.List;
@Repository("mindmapManager")
public class MindmapManagerImpl
implements MindmapManager {
@Autowired
private EntityManager entityManager;
@Override
public Collaborator findCollaborator(@NotNull final String email) {
final Collaborator collaborator;
final TypedQuery<Collaborator> query = entityManager.createQuery("from com.wisemapping.model.Collaborator collaborator where email=:email", Collaborator.class);
query.setParameter("email", email);
final List<Collaborator> collaborators = query.getResultList();
if (collaborators != null && !collaborators.isEmpty()) {
assert collaborators.size() == 1 : "More than one user with the same email!";
collaborator = collaborators.get(0);
} else {
collaborator = null;
}
return collaborator;
}
@Override
public List<MindMapHistory> getHistoryFrom(int mindmapId) {
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<MindMapHistory> cr = cb.createQuery(MindMapHistory.class);
final Root<MindMapHistory> root = cr.from(MindMapHistory.class);
final CriteriaQuery<MindMapHistory> select = cr.select(root)
.where(cb.equal(root.get("mindmapId"), mindmapId))
.orderBy(cb.desc(root.get("creationTime")));
return entityManager.
createQuery(select)
.setMaxResults(30)
.getResultList();
}
@Override
public MindMapHistory getHistory(int historyId) {
return entityManager.find(MindMapHistory.class, historyId);
}
@Override
public void updateCollaboration(@NotNull Collaboration collaboration) {
entityManager.persist(collaboration);
}
@Override
public List<Mindmap> findMindmapByUser(@NotNull Account user) {
final TypedQuery<Mindmap> query = entityManager
.createQuery("from com.wisemapping.model.Mindmap m where m.id in (select c.mindMap.id from com.wisemapping.model.Collaboration as c where c.collaborator.id=:collabId )", Mindmap.class);
query.setParameter("collabId", user.getId());
return query.getResultList();
}
@Override
public List<Collaboration> findCollaboration(final int collaboratorId) {
final TypedQuery<Collaboration> query = entityManager.createQuery("from com.wisemapping.model.Collaboration c where c.collaborator.id=:collaboratorId", Collaboration.class);
query.setParameter("collaboratorId", collaboratorId);
return query.getResultList();
}
@Override
public void addCollaborator(@NotNull Collaborator collaborator) {
assert collaborator != null : "ADD MINDMAP COLLABORATOR: Collaborator is required!";
entityManager.persist(collaborator);
}
@Override
public void removeCollaboration(Collaboration collaboration) {
entityManager.remove(collaboration);
}
@Override
public void removeCollaborator(@NotNull Collaborator collaborator) {
entityManager.remove(collaborator);
}
@Override
@Nullable
public Mindmap getMindmapById(int id) {
return entityManager.find(Mindmap.class, id);
}
@Override
public Mindmap getMindmapByTitle(final String title, final Account user) {
final TypedQuery<Mindmap> query = entityManager.createQuery("from com.wisemapping.model.Mindmap wisemapping where title=:title and creator=:creator", Mindmap.class);
query.setParameter("title", title);
query.setParameter("creator", user);
List<Mindmap> mindMaps = query.getResultList();
Mindmap result = null;
if (mindMaps != null && !mindMaps.isEmpty()) {
result = mindMaps.get(0);
}
return result;
}
@Override
public void addMindmap(Account user, Mindmap mindMap) {
saveMindmap(mindMap);
}
@Override
public void saveMindmap(Mindmap mindMap) {
assert mindMap != null : "Save Mindmap: Mindmap is required!";
entityManager.persist(mindMap);
}
@Override
public void updateMindmap(@NotNull Mindmap mindMap, boolean saveHistory) {
assert mindMap != null : "Save Mindmap: Mindmap is required!";
entityManager.merge(mindMap);
if (saveHistory) {
saveHistory(mindMap);
}
}
@Override
public void removeMindmap(@NotNull final Mindmap mindmap) {
// Delete history first ...
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaDelete<MindMapHistory> cr = cb.createCriteriaDelete(MindMapHistory.class);
final Root<MindMapHistory> root = cr.from(MindMapHistory.class);
final CriteriaDelete<MindMapHistory> deleteStatement = cr.where(cb.equal(root.get("mindmapId"), mindmap.getId()));
entityManager.createQuery(deleteStatement).executeUpdate();
// Remove collaborations ...
mindmap.removedCollaboration(mindmap.getCollaborations());
// Delete mindmap ....
entityManager.remove(mindmap);
}
private void saveHistory(@NotNull final Mindmap mindMap) {
final MindMapHistory history = new MindMapHistory();
history.setZippedXml(mindMap.getZippedXml());
history.setCreationTime(Calendar.getInstance());
history.setEditor(mindMap.getLastEditor());
history.setMindmapId(mindMap.getId());
entityManager.merge(history);
}
}

View File

@@ -1,13 +0,0 @@
package com.wisemapping.exceptions;
import com.wisemapping.service.google.http.HttpInvokerException;
import jakarta.validation.constraints.NotNull;
public class OAuthAuthenticationException extends WiseMappingException {
public OAuthAuthenticationException(@NotNull HttpInvokerException exception) {
super(exception.getMessage());
}
}

View File

@@ -1,37 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.exceptions;
import jakarta.validation.constraints.NotNull;
public class PasswordTooLongException
extends ClientException {
private static final String PASSWORD_TOO_LONG = "PASSWORD_TOO_LONG";
public PasswordTooLongException() {
super("Password length must be less than 40 characters", Severity.WARNING);
}
@NotNull
@Override
protected String getMsgBundleKey() {
return PASSWORD_TOO_LONG;
}
}

View File

@@ -1,87 +0,0 @@
package com.wisemapping.filter;
import com.wisemapping.security.JwtTokenUtil;
import com.wisemapping.security.UserDetails;
import com.wisemapping.security.UserDetailsService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Optional;
import static com.wisemapping.security.JwtTokenUtil.BEARER_TOKEN_PREFIX;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
final private static Logger logger = LogManager.getLogger();
@Override
protected void doFilterInternal(@NotNull final HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain)
throws ServletException, IOException {
final Optional<String> token = getJwtTokenFromRequest(request);
if (token.isPresent() && SecurityContextHolder.getContext().getAuthentication() == null) {
// Extract email from token ...
final Optional<String> email = extractEmailFromToken(token.get());
if (email.isPresent() && jwtTokenUtil.validateJwtToken(token.get())) {
// Is it an existing user ?
try {
final UserDetails userDetails = userDetailsService.loadUserByUsername(email.get());
final UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
} catch (UsernameNotFoundException e) {
logger.trace("User " + email.get() + " could not be found");
}
}
}
filterChain.doFilter(request, response);
}
private Optional<String> extractEmailFromToken(final @NotNull String token) {
Optional<String> result = Optional.empty();
try {
result = Optional.ofNullable(jwtTokenUtil.extractFromJwtToken(token));
} catch (Exception e) {
// Handle token extraction/validation errors
logger.debug("Error extracting email from token: " + e.getMessage());
}
logger.trace("JWT token email:" + result);
return result;
}
private static Optional<String> getJwtTokenFromRequest(@NotNull HttpServletRequest request) {
Optional<String> result = Optional.empty();
final String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
if (authorizationHeader != null) {
if (authorizationHeader.startsWith(BEARER_TOKEN_PREFIX)) {
logger.trace("JWT Bearer token found.");
final String token = authorizationHeader.substring(BEARER_TOKEN_PREFIX.length());
result = Optional.of(token);
}
}
return result;
}
}

View File

@@ -1,67 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.model;
import org.jetbrains.annotations.NotNull;
import jakarta.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "COLLABORATION_PROPERTIES")
public class CollaborationProperties implements Serializable {
public static final String DEFAULT_JSON_PROPERTIES = "{\"zoom\":0.8}";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private boolean starred;
@Column(name = "mindmap_properties")
private String mindmapProperties;
public CollaborationProperties() {
}
public boolean getStarred() {
return starred;
}
public void setStarred(boolean starred) {
this.starred = starred;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@NotNull
public String getMindmapProperties() {
return mindmapProperties == null ? DEFAULT_JSON_PROPERTIES : mindmapProperties;
}
public void setMindmapProperties(@NotNull String mindmapProperties) {
this.mindmapProperties = mindmapProperties;
}
}

View File

@@ -1,139 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.rest;
import com.wisemapping.exceptions.PasswordTooLongException;
import com.wisemapping.exceptions.WiseMappingException;
import com.wisemapping.model.Collaboration;
import com.wisemapping.model.MindmapLabel;
import com.wisemapping.model.Mindmap;
import com.wisemapping.model.Account;
import com.wisemapping.rest.model.RestUser;
import com.wisemapping.security.Utils;
import com.wisemapping.service.LabelService;
import com.wisemapping.service.MindmapService;
import com.wisemapping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/restful/account")
@PreAuthorize("isAuthenticated() and hasRole('ROLE_USER')")
public class AccountController extends BaseController {
@Qualifier("userService")
@Autowired
private UserService userService;
@Qualifier("mindmapService")
@Autowired
private MindmapService mindmapService;
@Qualifier("labelService")
@Autowired
private LabelService labelService;
@RequestMapping(method = RequestMethod.PUT, value = "/password", consumes = {"text/plain"})
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void changePassword(@RequestBody String password) throws PasswordTooLongException {
if (password == null) {
throw new IllegalArgumentException("Password can not be null");
}
if (password.length() > Account.MAX_PASSWORD_LENGTH_SIZE) {
throw new PasswordTooLongException();
}
final Account user = Utils.getUser(true);
user.setPassword(password);
userService.changePassword(user);
}
@RequestMapping(method = RequestMethod.GET, value = "", produces = {"application/json"})
public RestUser fetchAccount() {
final Account user = Utils.getUser(true);
return new RestUser(user);
}
@RequestMapping(method = RequestMethod.PUT, value = "/firstname", consumes = {"text/plain"})
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void changeFirstname(@RequestBody String firstname) {
if (firstname == null) {
throw new IllegalArgumentException("Firstname can not be null");
}
final Account user = Utils.getUser(true);
user.setFirstname(firstname);
userService.updateUser(user);
}
@RequestMapping(method = RequestMethod.PUT, value = "/lastname", consumes = {"text/plain"})
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void changeLastName(@RequestBody String lastname) {
if (lastname == null) {
throw new IllegalArgumentException("lastname can not be null");
}
final Account user = Utils.getUser(true);
user.setLastname(lastname);
userService.updateUser(user);
}
@RequestMapping(method = RequestMethod.PUT, value = "/locale", consumes = {"text/plain"})
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void changeLanguage(@RequestBody String language) {
if (language == null) {
throw new IllegalArgumentException("language can not be null");
}
final Account user = Utils.getUser(true);
user.setLocale(language);
userService.updateUser(user);
}
@ResponseStatus(value = HttpStatus.NO_CONTENT)
@RequestMapping(method = RequestMethod.DELETE, value = "")
public void deleteUser() throws WiseMappingException {
// Delete collaborations ...
final Account user = Utils.getUser(true);
final List<Collaboration> collaborations = mindmapService.findCollaborations(user);
for (Collaboration collaboration : collaborations) {
final Mindmap mindmap = collaboration.getMindMap();
mindmapService.removeMindmap(mindmap, user);
}
// Delete labels ....
final List<MindmapLabel> labels = labelService.getAll(user);
labels.forEach(l -> {
try {
labelService.removeLabel(l, user);
} catch (WiseMappingException e) {
throw new IllegalStateException(e);
}
});
// Finally, delete user ...
userService.removeUser(user);
}
}

View File

@@ -1,110 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.rest;
import com.wisemapping.rest.model.RestAppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/restful/app")
public class AppController extends BaseController {
@Value("${app.security.oauth2.google.url:}")
private String googleOauth2Url;
@Value("${app.registration.enabled:true}")
private Boolean isRegistrationEnabled;
@Value("${app.registration.captcha.enabled:false}")
private Boolean isCaptchaEnabled;
@Value("${app.registration.captcha.siteKey:}")
private String captchaSiteKey;
@Value("${app.site.api-base-url:}")
private String apiBaseUrl;
@Value("${app.site.ui-base-url:}")
private String uiBaseUrl;
@Value("${app.analytics.account:}")
private String analyticsAccount;
@Value("${app.jwt.expirationMin:10080}")
private int jwtExpirationMin;
@RequestMapping(method = RequestMethod.GET, value = "/config")
@ResponseStatus(value = HttpStatus.OK)
public RestAppConfig appConfig() {
return new RestAppConfig.RestAppConfigBuilder()
.setApiUrl(apiBaseUrl)
.setUiUrl(uiBaseUrl)
.setCaptchaSiteKey(captchaSiteKey)
.setGoogleOauth2Url(googleOauth2Url)
.setAnalyticsAccount(analyticsAccount)
.setRegistrationEnabled(isRegistrationEnabled)
.setJwtExpirationMin(jwtExpirationMin)
.build();
}
public String getGoogleOauth2Url() {
return googleOauth2Url;
}
public void setGoogleOauth2Url(String googleOauth2Url) {
this.googleOauth2Url = googleOauth2Url;
}
public Boolean getRegistrationEnabled() {
return isRegistrationEnabled;
}
public void setRegistrationEnabled(Boolean registrationEnabled) {
isRegistrationEnabled = registrationEnabled;
}
public Boolean getCaptchaEnabled() {
return isCaptchaEnabled;
}
public void setCaptchaEnabled(Boolean captchaEnabled) {
isCaptchaEnabled = captchaEnabled;
}
public String getCaptchaSiteKey() {
return captchaSiteKey;
}
public void setCaptchaSiteKey(String captchaSiteKey) {
this.captchaSiteKey = captchaSiteKey;
}
public String getApiBaseUrl() {
return apiBaseUrl;
}
public void setApiBaseUrl(String apiBaseUrl) {
this.apiBaseUrl = apiBaseUrl;
}
}

View File

@@ -1,60 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.rest;
import com.wisemapping.exceptions.WiseMappingException;
import com.wisemapping.rest.model.RestJwtUser;
import com.wisemapping.security.JwtTokenUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/restful")
public class JwtAuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ResponseEntity<String> createAuthenticationToken(@RequestBody RestJwtUser user, @NotNull HttpServletResponse response) throws WiseMappingException {
// Is a valid user ?
authenticate(user.getEmail(), user.getPassword());
final String result = jwtTokenUtil.doLogin(response, user.getEmail());
return ResponseEntity.ok(result);
}
private void authenticate(@NotNull String username, @NotNull String password) throws WiseMappingException {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException | BadCredentialsException e) {
throw new WiseMappingException(e.getMessage(), e);
}
}
}

View File

@@ -1,91 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.rest;
import com.wisemapping.exceptions.WiseMappingException;
import com.wisemapping.model.Account;
import com.wisemapping.rest.model.RestOath2CallbackResponse;
import com.wisemapping.security.JwtTokenUtil;
import com.wisemapping.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/restful/oauth2/")
@CrossOrigin
public class OAuth2Controller extends BaseController {
final private static Logger logger = LogManager.getLogger();
@Qualifier("userService")
@Autowired
private UserService userService;
@Qualifier("authenticationManager")
@Autowired
private AuthenticationManager authManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@RequestMapping(method = RequestMethod.POST, value = "googlecallback", produces = {"application/json"})
@ResponseStatus(value = HttpStatus.OK)
public RestOath2CallbackResponse processGoogleCallback(@NotNull @RequestParam String code, @NotNull HttpServletResponse response, @NotNull HttpServletRequest request) throws WiseMappingException {
logger.debug("ProcessGoogleCallback:" + code);
if (code == null) {
throw new WiseMappingException("Illegal argument exception: " + code);
}
final Account user = userService.createAndAuthUserFromGoogle(code);
String jwtToken = null;
if (user.getGoogleSync()) {
jwtToken = jwtTokenUtil.doLogin(response, user.getEmail());
}
// Response ...
return new RestOath2CallbackResponse(user, jwtToken);
}
@RequestMapping(method = RequestMethod.PUT, value = "confirmaccountsync", produces = {"application/json"})
@ResponseStatus(value = HttpStatus.OK)
public RestOath2CallbackResponse confirmAccountSync(@NotNull @RequestParam String email, @NotNull @RequestParam String code, @NotNull HttpServletResponse response) throws WiseMappingException {
logger.debug("ConfirmAccountSync:" + email + " - " + code);
if (code == null) {
throw new WiseMappingException("Illegal argument exception: " + email + " - " + code);
}
// Update login
final Account user = userService.confirmGoogleAccountSync(email, code);
// Add header ...
final String jwtToken = jwtTokenUtil.doLogin(response, email);
// Response ...
return new RestOath2CallbackResponse(user, jwtToken);
}
}

View File

@@ -1,177 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.rest.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.jetbrains.annotations.NotNull;
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY,
isGetterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RestAppConfig {
private String apiBaseUrl;
private String uiBaseUrl;
private String googleOauth2Url;
private boolean registrationEnabled;
private boolean recaptcha2Enabled;
private String recaptcha2SiteKey;
private String analyticsAccount;
private int jwtExpirationMin = 10080;
RestAppConfig() {
}
public String getApiBaseUrl() {
return apiBaseUrl;
}
public void setApiBaseUrl(String apiBaseUrl) {
this.apiBaseUrl = apiBaseUrl;
}
public String getGoogleOauth2Url() {
return googleOauth2Url;
}
public void setGoogleOauth2Url(String googleOauth2Url) {
this.googleOauth2Url = googleOauth2Url;
}
public boolean isRegistrationEnabled() {
return registrationEnabled;
}
public void setRegistrationEnabled(boolean registrationEnabled) {
this.registrationEnabled = registrationEnabled;
}
public boolean isRecaptcha2Enabled() {
return recaptcha2Enabled;
}
public void setRecaptcha2Enabled(boolean recaptcha2Enabled) {
this.recaptcha2Enabled = recaptcha2Enabled;
}
public String getRecaptcha2SiteKey() {
return recaptcha2SiteKey;
}
public void setRecaptcha2SiteKey(String recaptcha2SiteKey) {
this.recaptcha2SiteKey = recaptcha2SiteKey;
}
public String getAnalyticsAccount() {
return analyticsAccount;
}
public void setAnalyticsAccount(String analyticsAccount) {
this.analyticsAccount = analyticsAccount;
}
public int getJwtExpirationMin() {
return jwtExpirationMin;
}
public void setJwtExpirationMin(int jwtExpirationMin) {
this.jwtExpirationMin = jwtExpirationMin;
}
public String getUiBaseUrl() {
return uiBaseUrl;
}
public void setUiBaseUrl(String uiBaseUrl) {
this.uiBaseUrl = uiBaseUrl;
}
public static class RestAppConfigBuilder {
private String apiBaseUrl;
private String uiBaseUrl;
private String googleOauth2Url;
private boolean registrationEnabled;
private boolean isCatchaEnabled = false;
private String captchaSiteKey;
private String analyticsAccount;
private int jwtExpirationMin;
public RestAppConfigBuilder setCaptchaSiteKey(@NotNull String captchaSiteKey) {
this.captchaSiteKey = captchaSiteKey;
this.isCatchaEnabled = true;
return this;
}
public RestAppConfigBuilder setApiUrl(@NotNull String url) {
this.apiBaseUrl = url;
return this;
}
public RestAppConfigBuilder setUiUrl(@NotNull String url) {
this.uiBaseUrl = url;
return this;
}
public RestAppConfigBuilder setJwtExpirationMin(@NotNull int value) {
this.jwtExpirationMin = value;
return this;
}
public RestAppConfigBuilder setGoogleOauth2Url(@NotNull String googleOauth2Url) {
this.googleOauth2Url = googleOauth2Url;
return this;
}
private void setGoogleAnalyticsAccount(@NotNull String analyticsAccount) {
this.analyticsAccount = analyticsAccount;
}
public RestAppConfigBuilder setRegistrationEnabled(@NotNull boolean registrationEnabled) {
this.registrationEnabled = registrationEnabled;
return this;
}
public RestAppConfigBuilder setAnalyticsAccount(@NotNull String analyticsAccount) {
this.analyticsAccount = analyticsAccount;
return this;
}
@NotNull
public RestAppConfig build() {
final RestAppConfig result = new RestAppConfig();
result.googleOauth2Url = googleOauth2Url;
result.recaptcha2SiteKey = captchaSiteKey;
result.recaptcha2Enabled = isCatchaEnabled;
result.uiBaseUrl = uiBaseUrl;
result.apiBaseUrl = apiBaseUrl;
result.registrationEnabled = registrationEnabled;
result.analyticsAccount = analyticsAccount;
return result;
}
}
}

View File

@@ -1,59 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.rest.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.jetbrains.annotations.NotNull;
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY,
isGetterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RestJwtUser {
private String email;
private String password;
public RestJwtUser(@NotNull String email, @NotNull String password) {
this.setEmail(email);
this.setPassword(password);
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@@ -1,89 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.rest.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY
)
@JsonIgnoreProperties(ignoreUnknown = true)
public class RestMindmapMetadata {
private String jsonProps;
private boolean locked;
private String title;
private String isLockedBy;
private String creatorFullName;
public RestMindmapMetadata(@NotNull String title, @NotNull String jsonProps, @NotNull String creatorFullName, boolean locked, @Nullable String isLockedBy) {
this.jsonProps = jsonProps;
this.title = title;
this.locked = locked;
this.isLockedBy = isLockedBy;
this.creatorFullName = creatorFullName;
}
public String getJsonProps() {
return jsonProps;
}
public void setJsonProps(String jsonProps) {
this.jsonProps = jsonProps;
}
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsLockedBy() {
return isLockedBy;
}
public void setIsLockedBy(String isLockedBy) {
this.isLockedBy = isLockedBy;
}
public String getCreatorFullName() {
return creatorFullName;
}
public void setCreatorFullName(String creatorFullName) {
this.creatorFullName = creatorFullName;
}
}

View File

@@ -1,61 +0,0 @@
package com.wisemapping.rest.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.wisemapping.model.Account;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY
)
@JsonIgnoreProperties(ignoreUnknown = true)
public class RestOath2CallbackResponse {
private String email;
private Boolean googleSync;
private String syncCode;
private String jwtToken;
public RestOath2CallbackResponse(@NotNull Account user, @Nullable String jwtToken) {
this.setEmail(user.getEmail());
this.setGoogleSync(user.getGoogleSync());
this.setSyncCode(user.getSyncCode());
this.setJwtToken(jwtToken);
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getGoogleSync() {
return googleSync;
}
public void setGoogleSync(Boolean googleSync) {
this.googleSync = googleSync;
}
public String getSyncCode() {
return syncCode;
}
public void setSyncCode(String syncCode) {
this.syncCode = syncCode;
}
public String getJwtToken() {
return jwtToken;
}
public void setJwtToken(String jwtToken) {
this.jwtToken = jwtToken;
}
}

View File

@@ -1,7 +0,0 @@
package com.wisemapping.rest.model;
public enum RestResetPasswordAction {
EMAIL_SENT, OAUTH2_USER
}

View File

@@ -1,15 +0,0 @@
package com.wisemapping.rest.model;
public class RestResetPasswordResponse {
RestResetPasswordAction action;
public RestResetPasswordAction getAction() {
return action;
}
public void setAction(RestResetPasswordAction action) {
this.action = action;
}
}

View File

@@ -1,59 +0,0 @@
package com.wisemapping.security;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import com.wisemapping.model.Account;
public class GoogleAuthenticationProvider implements org.springframework.security.authentication.AuthenticationProvider {
private UserDetailsService userDetailsService;
public GoogleAuthenticationProvider(@NotNull UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* Authenticate the given PreAuthenticatedAuthenticationToken.
* <p>
* If the principal contained in the authentication object is null, the request will
* be ignored to allow other providers to authenticate it.
*/
@Override
public Authentication authenticate(Authentication inputToken) throws AuthenticationException {
if (!supports(inputToken.getClass())) {
return null;
}
if (inputToken.getPrincipal() == null) {
throw new BadCredentialsException("No pre-authenticated principal found in request.");
}
UserDetails userDetails = userDetailsService.loadUserByUsername(inputToken.getName());
final Account user = userDetails.getUser();
if (!user.isActive()) {
throw new BadCredentialsException("User has been disabled for login " + inputToken.getName());
}
PreAuthenticatedAuthenticationToken resultToken = new PreAuthenticatedAuthenticationToken(userDetails,
inputToken.getCredentials(), userDetails.getAuthorities());
resultToken.setDetails(userDetails);
userDetailsService.getUserService().auditLogin(user);
return resultToken;
}
/**
* Indicate that this provider only supports PreAuthenticatedAuthenticationToken
* (sub)classes.
*/
@Override
public final boolean supports(Class<?> authentication) {
return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication);
}
}

View File

@@ -1,87 +0,0 @@
package com.wisemapping.security;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.security.Key;
import java.util.Date;
@Component
public class JwtTokenUtil implements Serializable {
final private Logger logger = LogManager.getLogger();
public final static String BEARER_TOKEN_PREFIX = "Bearer ";
@Value("${app.jwt.secret}")
private String jwtSecret;
@Value("${app.jwt.expirationMin}")
private int jwtExpirationMin;
@Autowired
private UserDetailsService userDetailsService;
public String generateJwtToken(@NotNull final UserDetails user) {
return Jwts.builder()
.setSubject((user.getUsername()))
.setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + jwtExpirationMin * 1000L * 60))
.signWith(key(), SignatureAlgorithm.HS256)
.compact();
}
private Key key() {
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtSecret));
}
@Nullable
public String extractFromJwtToken(String token) {
return Jwts.parserBuilder().setSigningKey(key()).build()
.parseClaimsJws(token).getBody().getSubject();
}
public boolean validateJwtToken(@NotNull String authToken) {
boolean result = false;
try {
Jwts.parserBuilder().setSigningKey(key()).build().parse(authToken);
result = true;
} catch (MalformedJwtException e) {
logger.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
logger.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
logger.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("JWT claims string is empty: {}", e.getMessage());
}
logger.trace("Is JWT token valid:" + result);
return result;
}
@NotNull
public String doLogin(@NotNull HttpServletResponse response, @NotNull String email) {
logger.debug("Performing login:" + email);
final UserDetails userDetails = userDetailsService.loadUserByUsername(email);
// Add JWT in the HTTP header ...
final String token = generateJwtToken(userDetails);
response.addHeader(HttpHeaders.AUTHORIZATION, BEARER_TOKEN_PREFIX + token);
return token;
}
}

View File

@@ -1,6 +0,0 @@
package com.wisemapping.security;
public enum MapAccessPermission {
READ,
WRITE
}

View File

@@ -1,91 +0,0 @@
package com.wisemapping.security;
import com.wisemapping.model.Collaborator;
import com.wisemapping.model.Mindmap;
import com.wisemapping.model.Account;
import jakarta.validation.constraints.NotNull;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import java.io.Serializable;
public class MapAccessPermissionEvaluation implements PermissionEvaluator {
final private static Logger logger = LogManager.getLogger();
private MapPermissionsSecurityAdvice readAdvice;
private MapPermissionsSecurityAdvice updateAdvice;
public MapAccessPermissionEvaluation(final @NotNull MapPermissionsSecurityAdvice readAdvice, final @NotNull MapPermissionsSecurityAdvice updateAdvice) {
this.readAdvice = readAdvice;
this.updateAdvice = updateAdvice;
}
@Override
public boolean hasPermission(
@NotNull Authentication auth, @NotNull Object targetDomainObject, @NotNull Object permission) {
logger.log(Level.DEBUG, "auth: " + auth + ",targetDomainObject:" + targetDomainObject + ",permission:" + permission);
if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)) {
logger.debug("Permissions could not be validated, illegal parameters.");
return false;
}
boolean result;
final Account user = Utils.getUser();
final MapAccessPermission perm = MapAccessPermission.valueOf((permission.toString().toUpperCase()));
if (targetDomainObject instanceof Integer) {
// Checking permissions by mapId ...
final int mapId = (Integer) targetDomainObject;
result = hasPrivilege(mapId, perm);
} else if (targetDomainObject instanceof Mindmap) {
final Mindmap map = (Mindmap) targetDomainObject;
result = hasPrivilege(map, perm);
} else if (targetDomainObject instanceof Collaborator collab) {
// Read only operations checks ...
result = user.identityEquality(collab) || readAdvice.getMindmapService().isAdmin(user);
} else {
throw new IllegalArgumentException("Unsupported check control of permissions");
}
if (!result) {
logger.debug("User '" + (user != null ? user.getEmail() : "none") + "' not allowed to invoke");
}
return result;
}
@Override
public boolean hasPermission(
@NotNull Authentication auth, Serializable targetId, @NotNull String targetType, @NotNull Object
permission) {
logger.log(Level.FATAL, "Unsupported privilege: auth: " + auth + ",targetId:" + targetType + ",targetType:" + targetType + ", permission:" + permission);
return false;
}
private boolean hasPrivilege(@NotNull int mapId, @NotNull MapAccessPermission permission) {
boolean result;
final Account user = Utils.getUser();
if (MapAccessPermission.READ == permission) {
result = readAdvice.isAllowed(user, mapId);
} else {
result = updateAdvice.isAllowed(user, mapId);
}
return result;
}
private boolean hasPrivilege(@NotNull Mindmap map, @NotNull MapAccessPermission permission) {
boolean result;
final Account user = Utils.getUser();
if (MapAccessPermission.READ == permission) {
result = readAdvice.isAllowed(user, map);
} else {
result = updateAdvice.isAllowed(user, map);
}
return result;
}
}

View File

@@ -1,48 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.security;
import com.wisemapping.model.CollaborationRole;
import com.wisemapping.model.Mindmap;
import com.wisemapping.model.Account;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;
@Component
public class UpdateSecurityAdvise
extends MapPermissionsSecurityAdvice {
@Override
protected boolean isAllowed(@Nullable Account user, @NotNull Mindmap map) {
boolean result;
if (map.getCreator() == null) {
// This means that the map is new and is an add operation.
result = true;
} else {
result = getMindmapService().hasPermissions(user, map, CollaborationRole.EDITOR);
}
return result;
}
@Override
protected boolean isAllowed(@Nullable Account user, int mapId) {
return getMindmapService().hasPermissions(user, mapId, CollaborationRole.EDITOR);
}
}

View File

@@ -1,73 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.security;
import com.wisemapping.model.Account;
import com.wisemapping.service.UserService;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class UserDetailsService
implements org.springframework.security.core.userdetails.UserDetailsService {
@Autowired
private UserService userService;
@Value("${app.admin.user}")
private String adminUser;
@Override
public UserDetails loadUserByUsername(@NotNull String email) throws UsernameNotFoundException, DataAccessException {
final Account user = userService.getUserBy(email);
if (user != null) {
return new UserDetails(user, isAdmin(email));
} else {
throw new UsernameNotFoundException(email);
}
}
private boolean isAdmin(@Nullable String email) {
return email != null && adminUser != null && email.trim().endsWith(adminUser);
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userManager) {
this.userService = userManager;
}
public String getAdminUser() {
return adminUser;
}
public void setAdminUser(String adminUser) {
this.adminUser = adminUser;
}
}

View File

@@ -1,66 +0,0 @@
package com.wisemapping.service.google;
public class GoogleAccountBasicData {
private String email;
private String accountId;
private String name;
private String lastName;
private String accessToken;
private String refreshToken;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
@Override
public String toString() {
return "GoogleAccountBasicData [email=" + email + ", accountId=" + accountId + ", name=" + name + ", lastName="
+ lastName + ", accessToken=" + accessToken + ", refreshToken=" + refreshToken + "]";
}
}

View File

@@ -1,130 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.service.google;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.JsonNode;
import com.wisemapping.service.google.http.HttpInvoker;
import com.wisemapping.service.google.http.HttpInvokerContentType;
import com.wisemapping.service.google.http.HttpInvokerException;
@Service
public class GoogleService {
@Autowired
private HttpInvoker httpInvoker;
@Value("${app.security.oauth2.google.confirmUrl:}")
private String optinConfirmUrl;
@Value("${app.security.oauth2.google.userinfoUrl:}")
private String accountBasicDataUrl;
@Value("${app.security.oauth2.google.clientId:}")
private String clientId;
@Value("${app.security.oauth2.google.clientSecret:}")
private String clientSecret;
@Value("${app.security.oauth2.google.callbackUrl:}")
private String callbackUrl;
public void setHttpInvoker(HttpInvoker httpInvoker) {
this.httpInvoker = httpInvoker;
}
public void setOptinConfirmUrl(String optinConfirmUrl) {
this.optinConfirmUrl = optinConfirmUrl;
}
public void setAccountBasicDataUrl(String accountBasicDataUrl) {
this.accountBasicDataUrl = accountBasicDataUrl;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
private String getNodeAsString(JsonNode node, String fieldName) {
return getNodeAsString(node, fieldName, null);
}
private String getNodeAsString(JsonNode node, String fieldName, String defaultValue) {
JsonNode subNode = node.get(fieldName);
return subNode != null ? subNode.asText() : defaultValue;
}
private Map<String, String> getHeaders(String token) {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-type", "application/json");
headers.put("Authorization", "Bearer " + token);
return headers;
}
private GoogleAccountBasicData getAccountBasicData(String token) throws HttpInvokerException {
JsonNode response = httpInvoker.invoke(accountBasicDataUrl, null, HttpMethod.GET, this.getHeaders(token), null,
null);
GoogleAccountBasicData data = new GoogleAccountBasicData();
data.setEmail(getNodeAsString(response, "email"));
data.setAccountId(getNodeAsString(response, "id"));
data.setName(getNodeAsString(response, "given_name", data.getEmail()));
data.setLastName(getNodeAsString(response, "family_name"));
return data;
}
private Map<String, String> getOptinConfirmBody(String code) {
Map<String, String> result = new HashMap<String, String>();
result.put("client_id", clientId);
result.put("client_secret", clientSecret);
result.put("code", code);
result.put("redirect_uri", callbackUrl);
result.put("grant_type", "authorization_code");
return result;
}
public GoogleAccountBasicData processCallback(final String code)
throws HttpInvokerException {
final Map<String, String> body = this.getOptinConfirmBody(code);
final JsonNode optionConfirmResponse = httpInvoker.invoke(
optinConfirmUrl,
HttpInvokerContentType.FORM_ENCODED,
HttpMethod.POST,
null,
null,
body);
final String accessToken = getNodeAsString(optionConfirmResponse, "access_token");
final String refreshToken = getNodeAsString(optionConfirmResponse, "refresh_token");
final GoogleAccountBasicData data = this.getAccountBasicData(accessToken);
data.setAccessToken(accessToken);
data.setRefreshToken(refreshToken);
return data;
}
}

View File

@@ -1,167 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.service.google.http;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.constraints.NotNull;
@Service
public class HttpInvoker {
protected static Logger logger = LogManager.getLogger(HttpInvoker.class);
private final ObjectMapper mapper = new ObjectMapper();
public HttpInvoker() {
super();
}
public JsonNode invoke(
@NotNull String url,
HttpInvokerContentType requestContentType,
HttpMethod method,
Map<String, String> headers,
String jsonPayload,
Map<String, String> formData)
throws HttpInvokerException {
String responseBody = null;
try {
if (logger.isDebugEnabled()) {
logger.debug("finalUrl: " + url);
logger.debug("method: " + method);
logger.debug("payload: " + jsonPayload);
logger.debug("header: " + headers);
}
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpRequestBase httpRequest;
// build request
if (method.equals(HttpMethod.POST))
httpRequest = new HttpPost(url);
else if (method.equals(HttpMethod.PUT))
httpRequest = new HttpPut(url);
else if (method.equals(HttpMethod.GET))
httpRequest = new HttpGet(url);
else if (method.equals(HttpMethod.DELETE))
httpRequest = new HttpDelete(url);
else
throw new HttpInvokerException("Method " + method + " not supported by http connector");
if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) {
HttpEntity entity = null;
if (requestContentType.equals(HttpInvokerContentType.JSON)) {
if (jsonPayload == null)
throw new HttpInvokerException("Json content is required");
entity = new StringEntity(jsonPayload, StandardCharsets.UTF_8);
((HttpEntityEnclosingRequestBase) httpRequest).setEntity(entity);
}
if (requestContentType.equals(HttpInvokerContentType.FORM_ENCODED)) {
List<NameValuePair> nameValuePairs = new ArrayList<>();
Set<String> keys = formData.keySet();
for (String key : keys) {
nameValuePairs.add(new BasicNameValuePair(key, formData.get(key).toString()));
}
entity = new UrlEncodedFormEntity(nameValuePairs);
((HttpEntityEnclosingRequestBase) httpRequest).setEntity(entity);
}
if (entity == null)
throw new HttpInvokerException("Cant build entity to send");
}
if (headers != null) {
Set<String> keys = headers.keySet();
for (String key : keys) {
httpRequest.setHeader(key, headers.get(key));
}
}
if (requestContentType != null)
httpRequest.setHeader("Content-Type", requestContentType.getHttpContentType());
// invoke
CloseableHttpResponse response = httpClient.execute(httpRequest);
// response process
JsonNode root = null;
responseBody = response.getEntity() != null && response.getEntity().getContent() != null
? IOUtils.toString(response.getEntity().getContent(), (String) null)
: null;
if (responseBody != null) {
if (logger.isDebugEnabled()) {
logger.debug("response plain: " + responseBody);
}
try {
root = mapper.readTree(responseBody);
} catch (Exception e) {
int returnCode = response.getStatusLine().getStatusCode();
throw new HttpInvokerException("cant transform response to JSON. RQ: " + jsonPayload + ", RS: "
+ responseBody + ", status: " + returnCode, e);
}
}
if (response.getStatusLine().getStatusCode() >= 400) {
logger.error("error response: " + responseBody);
throw new HttpInvokerException("error invoking " + url + ", response: " + responseBody + ", status: "
+ response.getStatusLine().getStatusCode(), HttpStatus.SC_BAD_REQUEST);
}
httpRequest.releaseConnection();
response.close();
httpClient.close();
return root;
} catch (HttpInvokerException e) {
throw e;
} catch (Exception e) {
logger.error("cant invoke service " + url);
logger.error("response: " + responseBody, e);
throw new HttpInvokerException("cant invoke service " + url, e);
}
}
}

View File

@@ -1,18 +0,0 @@
package com.wisemapping.service.google.http;
public enum HttpInvokerContentType {
JSON("application/json"),
FORM_ENCODED("application/x-www-form-urlencoded");
private String httpContentType;
HttpInvokerContentType(String type) {
this.httpContentType = type;
}
public String getHttpContentType() {
return httpContentType;
}
}

View File

@@ -1,44 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.service.google.http;
import org.apache.http.HttpStatus;
public class HttpInvokerException extends Exception {
private final int statusCode;
public HttpInvokerException(String message) {
this(message, HttpStatus.SC_INTERNAL_SERVER_ERROR, null);
}
public HttpInvokerException(String message, int statusCode) {
this(message, statusCode, null);
}
public HttpInvokerException(String message, Throwable cause) {
this(message, HttpStatus.SC_INTERNAL_SERVER_ERROR, cause);
}
public HttpInvokerException(String message, int statusCode, Throwable cause) {
super(message, cause);
this.statusCode = statusCode;
}
public int getStatusCode() {
return statusCode;
}
}

View File

@@ -1 +0,0 @@
# Solves error Can't find bundle for base name jakarta.xml.bind.Messages, locale en_US

View File

@@ -1,116 +0,0 @@
#
# This file contains all the defaults that it will be used when the application is started.
# There are two main sections: SpringBoot Config and Application Config
#
#
# SpringBoot Config: WiseMapping Backend is based on SpringBoot. Additional configurations documentation could be found https://docs.spring.io/spring-boot/3.3/reference/features/external-config.html.
#
spring:
# SMTP server configuration used for password recovery and notifications.
mail:
host: smtp.example.com
port: 25
username: setusername
password: setpassword
properties:
mail:
smtp:
connectiontimeout: 5000
timeout: 3000
writetimeout: 5000
# Database configuration options. Examples can be found: https://github.com/wisemapping/wisemapping-open-source/tree/develop/config/database
datasource:
url: jdbc:hsqldb:mem:wisemapping
driver-class-name: org.hsqldb.jdbc.JDBCDriver
password: ''
username: sa
jpa:
hibernate:
ddl-auto: none
open-in-view: true
properties:
hibernate:
current_session_context_class: thread
default_batch_fetch_size: 200
dialect: org.hibernate.dialect.HSQLDialect
format_sql: true
sql:
init:
mode: always
platform: hsqldb
# General Config: Do no touch.
main:
allow-circular-references: true
output:
ansi:
enabled: always
application:
name: wisemapping-api
title: wisemapping-api
#
# Log Level
#
logging:
level:
org:
apache:
tomcat: INFO
root: INFO
#
# Application Config related options:
#
app:
# This information is mainly used by the frontend to connect to the backend. It must match the deployment topology used.
site:
ui-base-url: http://localhost
api-base-url: http://localhost
# Enable API basic authentication.
api:
http-basic-enabled: false
# JSON Web Token configuration options. Secret must be configured.
jwt:
secret: dlqxKAg685SaKhsQXIMeM=JWCw3bkl3Ei3Tb7LMlnd19oMd66burPNlJ0Po1qguyjgpakQTk2CN3
expirationMin: 10080 # One week
# Admin account with super admin permissions on the API.
admin:
user: admin@wisemapping.org
# STMP email configurations
mail:
sender-email: root@localhost
support-email: root@localhost
enabled: false
accounts:
max-inactive: 20
# Google OAuth Authentication
security:
# corsAllowedOrigins: https://dev.wisemapping.com
oauth2:
google:
clientSecret: <google-oath>
confirmUrl: https://oauth2.googleapis.com/token
userinfoUrl: https://www:googleapis.com/oauth2/v3/userinfo
callbackUrl: https://app.wisemapping.com/c/registration-google
clientId: 625682766634-cocbbbbb403iuvps1evecdk6d7phvbkf.apps.googleusercontent.com
url: https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${app.security.oauth2.google.callbackUrl}&prompt=consent&response_type=code&client_id=${app.security.oauth2.google.clientId}&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&access_type=offline&state=wisemapping&include_granted_scopes=true
# accounts:
# exclusion:
# domain:
# Account registration options dialog
registration:
enabled: true
captcha:
enabled: false
siteKey: some-key
secretKey: some-secret
# Behind reverse proxy configuration
server:
tomcat:
remote-ip-header: x-forwarded-for
protocol-header: x-forwarded-proto

View File

@@ -1,6 +0,0 @@
| | |' |\ /| ' /\ |~~\~|~
| | ||(~/~/| \/ |/~~||~~\|~~\||/~\ /~~| /__\ |__/ |
\/ \/ |_)\/_| |\__||__/|__/|| |\__| / \| _|_
| | \__|
${application.title} ${application.version}
Powered by Spring Boot ${spring-boot.version}

View File

@@ -1 +0,0 @@
SET DATABASE SQL SYNTAX MYS TRUE;

View File

@@ -1 +0,0 @@
INSERT IGNORE INTO COLLABORATOR (id, email, creation_date) VALUES (1, 'test@wisemapping.org', CURRENT_DATE());

View File

@@ -1,15 +0,0 @@
INSERT INTO COLLABORATOR (id, email, creation_date) VALUES (1, 'test@wisemapping.org', CURRENT_DATE)
ON CONFLICT DO NOTHING;
INSERT INTO ACCOUNT (collaborator_id, firstname, lastname, password, activation_code, activation_date, allow_send_email,authentication_type)
VALUES (1, 'Test', 'User', 'ENC:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', 1237, CURRENT_DATE, 1,'D')
ON CONFLICT DO NOTHING;
INSERT INTO COLLABORATOR (id, email, creation_date) VALUES (2, 'admin@wisemapping.org', CURRENT_DATE)
ON CONFLICT DO NOTHING;
INSERT INTO ACCOUNT (collaborator_id, firstname, lastname, password, activation_code, activation_date, allow_send_email,authentication_type)
VALUES (2, 'Admin', 'User', 'ENC:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', 1237, CURRENT_DATE, 1,'D')
ON CONFLICT DO NOTHING;

View File

@@ -1,29 +0,0 @@
<html>
<body>
<div>
<h3>Welcome to WiseMapping!</h3>
<p>
To active your account and verify your e-mail address, please click on the following link.
</p>
<a href="${emailcheck}">${emailcheck}</a>
</p>
<p>
If you have received this mail by error, you do not need to take any action to cancel the account. The account will
not be activated, and you will not receive any further emails.
</p>
<p>
If clicking the link above does not work, copy and paste the URL in a new browser window instead.
</p>
<p>
For questions or concerns regarding your account, send us an email to support@wisemapping.com.
</p>
<p style="color: #898989;">
<a href="https://www.wisemapping.com/">The WiseMapping Team</a><br/>
</p>
<div>
</body>
</html>

View File

@@ -1,73 +0,0 @@
# Default German Support.
DESCRIPTION=Beschreibung
SITE.TITLE=WiseMapping
FIELD_REQUIRED=Ein benötigtes Feld kann nicht leer gelassen werden
EMAIL_ALREADY_EXIST=Die E-Mail-Adresse existiert bereits.
NO_VALID_EMAIL_ADDRESS=Ungültige E-Mail-Adresse
CREATOR=Urheber
WELCOME=Willkommen
SHARE=Veröffentlichen
UNEXPECTED_ERROR=Ein unerwarteter Fehler ist aufgetreten.
MAP_TITLE_ALREADY_EXISTS=Du hast bereits eine Mindmap mit demselben Namen
LABEL_TITLE_ALREADY_EXISTS=Du hast bereits ein Label mit demselben Namen
TUTORIAL.MULTIPLE_TEXT_STYLES=Mehrfache Textstile
TUTORIAL.DIFFERENT_SHAPES=Verschiedene Formen
TUTORIAL.FANCY_ICONS=Ausgefallene Symbole
TUTORIAL.MOVE_WITH_ARROWS=Mit Pfeiltasten zwischen Themen wechseln
TUTORIAL.START_TYPING_TO_EDIT_TEXT=Einfach mit dem tippen beginnen, um Text zu bearbeiten
TUTORIAL.CTRL_TO_ADD_CHILD=Dröcke Strg/Meta+Enter um ein Unterthema einzufögen
TUTORIAL.ENTER_TO_ADD_SIBLING=Drücke Return um ein Schwesterthema einzufögen
TUTORIAL.MORE_KEY_TIPS=Mehr? Drücke auf obige Tastenkürzel
TUTORIAL.DOUBLE_CLICK_TO_ADD=Doppelklick auf die Arbeitsfläche, um Themen zu erzeugen
TUTORIAL.DRAG_AND_DROP_TO_POSITION=Thema per ziehen und fallen lassen positionieren
TUTORIAL.DOUBLE_CLICK_TO_EDIT_TEXT=Doppelklick auf ein Thema, um den Text zu bearbeiten
TUTORIAL.ADD_NOTES=Füge Notizen hinzu
TUTORIAL.USER_THE_TOOLBAR=Benutze die Werkzeugleiste
TUTORIAL.PUBLISH_YOUR_MAPS=Veröffentliche deine Mindmap
TUTORIAL.EMBED_IN_BLOGS=In Blog einbinden
TUTORIAL.INVITE_FRIEND=Freunde zur Zusammenarbeit einladen
TUTORIAL.SHARING=Mitbenutzung
TUTORIAL.EDITION_USING_MOUSE=Bearbeiten mit der Maus
TUTORIAL.EDITION_USING_KEYBOARD=Bearbeiten mit der Tastatur
TUTORIAL.ADD_LINKS_WEBPAGES=Verknüpfungen zu Internetseiten hinzufögen
TUTORIAL.TOPIC_PROPERTIES=Themen Eigenschaften
TUTORIAL.HOW_TO_START=Wie fange ich an?
TUTORIAL.FONT_COLOR=Farbe
TUTORIAL.FONT_STYLE=Stil
TUTORIAL.FONT_TYPE=Typ
TUTORIAL.SAMPLE_NOTE=Das ist eine einfache Notiz \!.
CAPTCHA_LOADING_ERROR=ReCaptcha konnte nicht geladen werden. Du musst Zugriff auf den Google ReCaptcha Dienst haben.
ACCESS_HAS_BEEN_REVOKED=Deine Zugriffsrechte auf diese Mindmap sind zuröckgesetzt worden. Bitte kontaktiere den Besitzer dieser Mindmap.
MAP_CAN_NOT_BE_FOUND=Die Mindmap kann nicht gefunden werden. Sie muss gelöscht worden sein.
LABEL_CAN_NOT_BE_FOUND=Das Label kann nicht gefunden werden. Es muss gelöscht worden sein.
MINDMAP_TIMESTAMP_OUTDATED=Es ist nicht möglich, deine Änderungen zu speichern, da deine Mindmap von {0} geändert wurde. Aktualisiere die Seite und versuche es erneut.
MINDMAP_LOCKED=Mindmap wird bearbeitet von {0} <{1}>. Die Mindmap wird im schreibgeschützten Modus geöffnet.
MINDMAP_IS_LOCKED=Mindmap ist für die Bearbeitung gesperrt.
# Confirmed
RESET_PASSWORD_INVALID_EMAIL=Die angegebene E-Mail-Adresse ist kein gültiges Benutzerkonto. Bitte versuche es erneut mit einer gültigen E-Mail-Adresse.
TRY_WELCOME=Dieser Ausgabebereich zeigt einige der Mindmap-Editor-Funktionen \!.
UNEXPECTED_ERROR_DETAILS=Unerwarteter Fehler bei der Verarbeitung der Anforderung.
NO_ENOUGH_PERMISSIONS=Diese Mindmap ist nicht mehr verfögbar.
NO_ENOUGH_PERMISSIONS_DETAILS=Du hast nicht die erforderlichen Rechte, um dir diese Mindmap anzusehen. Diese Mindmap ist entweder privat oder wurde gelöscht.
REGISTRATION.EMAIL_SUBJECT=Willkommen bei WiseMapping!
REGISTRATION.EMAIL_TITLE=Dein Konto wurde erfolgreich erstellt
REGISTRATION.EMAIL_BODY=<p>Vielen Dank för dein Interesse an WiseMapping. Klicke <a href='https://app.wisemapping.com/c/login'>hier</a>, um mit dem Erstellen und Teilen neuer Mindmaps zu beginnen. Wenn du eine Rückmeldung oder Ideen hast, sende uns eine E-Mail an <a href=\"mailto:feedback@wisemapping.com\">feedback@wisemapping.com</a>. Wir würden uns freuen, von dir zu hören.</p >
CHANGE_PASSWORD.EMAIL_SUBJECT=Dein Passwort wurde zurückgesetzt
CHANGE_PASSWORD.EMAIL_TITLE=Ein temporäres Passwort wurde generiert
CHANGE_PASSWORD.EMAIL_BODY=<p>Jemand, höchstwahrscheinlich du selbst, hat ein neues Passwort für dein WiseMapping-Konto angefordert. </p><p><strong>Hier ist dein neues Passwort: {0} </strong></p><p>Du kannst dich anmelden, indem du <a href="{1}/c/login">hier klickst</a>. Wir empfehlen dir dringend, das Passwort so schnell wie möglich zu ändern.</p>
PASSWORD_CHANGED.EMAIL_SUBJECT=Dein Passwort wurde geändert
PASSWORD_CHANGED.EMAIL_TITLE=Dein Passwort wurde erfolgreich geändert
PASSWORD_CHANGED.EMAIL_BODY=<p>Dies ist nur eine Benachrichtigung, dass dein Passwort geändert wurde. Es sind keine weiteren Maßnahmen erforderlich.</p>
CAPTCHA_TIMEOUT_OUT_DUPLICATE=Bitte aktualisiere die Seite und versuche es erneut.
CAPTCHA_INVALID_INPUT_RESPONSE=Antwort ungültig, aktualisiere die Seite und versuche es erneut.
MINDMAP_EMPTY_ERROR=Mindmap darf nicht leer sein.
INVALID_MINDMAP_FORMAT=Ungültiges Mindmap-Format.
TOO_BIG_MINDMAP=Du hast die Grenze von 5000 Themen in einer Mindmap erreicht.
SHARE_MAP.EMAIL_SUBJECT={0} hat eine Mindmap mit dir geteilt
EMAIL.DO_NOT_REPLAY=Wichtig: Antworte nicht auf diese E-Mail. Wenn du weitere Hilfe benötigst oder Bedenken bezüglich deines Kontos hast, kontaktiere uns <a href="mailto:{0}">hier</a>.
EMAIL.GREETINGS=Hallo
OWNER_ROLE_CAN_NOT_BE_CHANGED=Die Rolle des Besitzers kann nicht geändert werden. Bitte entferne den Besitzer aus der Änderungsliste.
ZOOM_TO_FIT=Einpassen
ZOOM_OUT=Verkleinern
ZOOM_IN=Vergrößern
PASSWORD_TOO_LONG=Passwort muss kürzer als 40 Zeichen sein.

View File

@@ -1 +0,0 @@
CREATE TABLE IF NOT EXISTS COLLABORATOR (

View File

@@ -1,144 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.test.rest;
import com.wisemapping.config.common.CommonConfig;
import com.wisemapping.config.rest.RestAppConfig;
import com.wisemapping.rest.AdminController;
import com.wisemapping.rest.MindmapController;
import com.wisemapping.rest.UserController;
import com.wisemapping.rest.model.RestUser;
import com.wisemapping.security.UserDetailsService;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.net.URI;
import static com.wisemapping.test.rest.RestHelper.*;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(
classes = {RestAppConfig.class, CommonConfig.class, MindmapController.class, AdminController.class, UserController.class},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"app.api.http-basic-enabled=true"}
)
@AutoConfigureMockMvc
public class RestAccountControllerTest {
private static final String ADMIN_USER = "admin@wisemapping.org";
private static final String ADMIN_PASSWORD = "test";
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private UserDetailsService service;
static public RestAccountControllerTest create(@NotNull TestRestTemplate restTemplate) {
final RestAccountControllerTest result = new RestAccountControllerTest();
result.restTemplate = restTemplate;
return result;
}
@Test
public void deleteAccount() {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate adminRestTemplate = this.restTemplate.withBasicAuth(ADMIN_USER, ADMIN_PASSWORD);
final RestUser newUser = createDummyUser();
createUser(requestHeaders, adminRestTemplate, newUser);
// Delete user ...
final TestRestTemplate newUserTemplate = this.restTemplate.withBasicAuth(newUser.getEmail(), newUser.getPassword());
final ResponseEntity<String> exchange = newUserTemplate.exchange(BASE_REST_URL + "/account", HttpMethod.DELETE, null, String.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful(), exchange.toString());
// Check that the account has been deleted ...
assertThrows(UsernameNotFoundException.class, () -> {
service.loadUserByUsername(newUser.getEmail());
});
}
@Test
public void accessAccount() {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate adminRestTemplate = this.restTemplate.withBasicAuth(ADMIN_USER, ADMIN_PASSWORD);
final RestUser newUser = createDummyUser();
createUser(requestHeaders, adminRestTemplate, newUser);
final TestRestTemplate newUserTemplate = this.restTemplate.withBasicAuth(newUser.getEmail(), newUser.getPassword());
final ResponseEntity<RestUser> exchange = newUserTemplate.exchange(BASE_REST_URL + "/account", HttpMethod.GET, null, RestUser.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful(), exchange.toString());
assertEquals(exchange.getBody().getEmail(), newUser.getEmail());
}
@Test
public RestUser createNewUser() {
// Configure media types ...
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate templateRest = this.restTemplate.withBasicAuth(ADMIN_USER, ADMIN_PASSWORD);
// Fill user data ...
final RestUser restUser = createDummyUser();
// Create a new user ...
final URI location = createUser(requestHeaders, templateRest, restUser);
// Check that the user has been created ...
ResponseEntity<RestUser> result = findUser(requestHeaders, templateRest, location);
assertEquals(result.getBody().getEmail(), restUser.getEmail(), "Returned object object seems not be the same.");
// Find by email and check ...
result = findUserByEmail(requestHeaders, templateRest, restUser.getEmail());
assertEquals(result.getBody().getEmail(), restUser.getEmail(), "Returned object object seems not be the same.");
// Assign generated id ...
restUser.setId(result.getBody().getId());
return restUser;
}
private ResponseEntity<RestUser> findUser(HttpHeaders requestHeaders, TestRestTemplate templateRest, URI location) {
HttpEntity<RestUser> findUserEntity = new HttpEntity<>(requestHeaders);
return templateRest.exchange(location.toString(), HttpMethod.GET, findUserEntity, RestUser.class);
}
private ResponseEntity<RestUser> findUserByEmail(HttpHeaders requestHeaders, TestRestTemplate templateRest, final String email) {
HttpEntity<RestUser> findUserEntity = new HttpEntity<>(requestHeaders);
// Add extension only to avoid the fact that the last part is extracted ...
final String url = BASE_REST_URL + "/admin/users/email/{email}";
return templateRest.exchange(url, HttpMethod.GET, findUserEntity, RestUser.class, email);
}
private URI createUser(@NotNull HttpHeaders requestHeaders, TestRestTemplate templateRest, RestUser restUser) {
final HttpEntity<RestUser> createUserEntity = new HttpEntity<>(restUser, requestHeaders);
return templateRest.postForLocation(BASE_REST_URL + "/admin/users", createUserEntity);
}
}

View File

@@ -1,69 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.test.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wisemapping.config.common.CommonConfig;
import com.wisemapping.config.rest.RestAppConfig;
import com.wisemapping.model.Account;
import com.wisemapping.rest.AppController;
import com.wisemapping.rest.UserController;
import com.wisemapping.rest.model.RestUser;
import com.wisemapping.rest.model.RestUserRegistration;
import com.wisemapping.service.UserService;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static com.wisemapping.test.rest.RestHelper.createDummyUser;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest(
classes = {RestAppConfig.class, CommonConfig.class, AppController.class},
properties = {"app.api.http-basic-enabled=true"}
)
@AutoConfigureMockMvc
public class RestAppControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void fetchProperties() throws Exception {
this.mockMvc.perform
(MockMvcRequestBuilders.get("/api/restful/app/config"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("\"jwtExpirationMin\":10080")));
}
}

View File

@@ -1,37 +0,0 @@
package com.wisemapping.test.rest;
import com.wisemapping.rest.model.RestUser;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
public class RestHelper {
public static final String BASE_REST_URL = "/api/restful";
static HttpHeaders createHeaders(@NotNull MediaType mediaType) {
List<MediaType> acceptableMediaTypes = new ArrayList<>();
acceptableMediaTypes.add(mediaType);
final HttpHeaders result = new HttpHeaders();
result.setAccept(acceptableMediaTypes);
result.setContentType(mediaType);
return result;
}
static RestUser createDummyUser() {
final RestUser restUser = new RestUser();
final String username = "foo-to-delete" + System.nanoTime();
final String email = username + "@example.org";
restUser.setEmail(email);
restUser.setFirstname("foo first name");
restUser.setLastname("foo last name");
restUser.setPassword("fooPassword");
return restUser;
}
}

View File

@@ -1,101 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.test.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wisemapping.config.common.CommonConfig;
import com.wisemapping.config.rest.RestAppConfig;
import com.wisemapping.rest.JwtAuthController;
import com.wisemapping.rest.model.RestJwtUser;
import com.wisemapping.security.JwtTokenUtil;
import com.wisemapping.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest(
classes = {RestAppConfig.class, CommonConfig.class, JwtAuthController.class},
properties = {"app.api.http-basic-enabled=true"}
)
@AutoConfigureMockMvc
public class RestJwtAuthControllerTest {
@Autowired
private ObjectMapper objectMapper;
@Autowired
JwtTokenUtil jwtTokenUtil;
@Autowired
private MockMvc mockMvc;
@Autowired
private UserService userService;
@Test
void generateTokenValidUser() throws Exception {
final RestJwtUser user = new RestJwtUser("test@wisemapping.org", "test");
final String userJson = objectMapper.writeValueAsString(user);
final MvcResult result = mockMvc.perform(
post("/api/restful/authenticate").
contentType(MediaType.APPLICATION_JSON)
.content(userJson))
.andExpect(status().isOk()).andReturn();
assertTrue(jwtTokenUtil.validateJwtToken(result.getResponse().getContentAsString()));
}
@Test
void generateTokenInvalidPassword() throws Exception {
final RestJwtUser user = new RestJwtUser("test@wisemapping.org", "test1");
final String userJson = objectMapper.writeValueAsString(user);
mockMvc.perform(
post("/api/restful/authenticate").
contentType(MediaType.APPLICATION_JSON)
.content(userJson))
.andExpect(status().is4xxClientError());
}
@Test
void generateTokenInvalidPasswordUser() throws Exception {
final RestJwtUser user = new RestJwtUser("test-not-exist@wisemapping.org", "test");
final String userJson = objectMapper.writeValueAsString(user);
mockMvc.perform(
post("/api/restful/authenticate").
contentType(MediaType.APPLICATION_JSON)
.content(userJson))
.andExpect(status().is4xxClientError());
}
}

View File

@@ -1,147 +0,0 @@
package com.wisemapping.test.rest;
import com.wisemapping.config.common.CommonConfig;
import com.wisemapping.config.rest.RestAppConfig;
import com.wisemapping.rest.AdminController;
import com.wisemapping.rest.LabelController;
import com.wisemapping.rest.UserController;
import com.wisemapping.rest.model.RestLabel;
import com.wisemapping.rest.model.RestLabelList;
import com.wisemapping.rest.model.RestUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.web.util.DefaultUriBuilderFactory;
import java.net.URI;
import java.util.List;
import java.util.Objects;
import static com.wisemapping.test.rest.RestHelper.BASE_REST_URL;
import static com.wisemapping.test.rest.RestHelper.createHeaders;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(
classes = {RestAppConfig.class, CommonConfig.class, LabelController.class, AdminController.class, UserController.class},
properties = {"app.api.http-basic-enabled=true"},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RestLabelControllerTest {
private static final String COLOR = "#000000";
private RestUser user;
@Autowired
private TestRestTemplate restTemplate;
@BeforeEach
void createUser() {
// Remote debug ...
if (restTemplate == null) {
this.restTemplate = new TestRestTemplate();
this.restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory("http://localhost:8081/"));
}
RestAccountControllerTest restAccount = RestAccountControllerTest.create(restTemplate);
this.user = restAccount.createNewUser();
}
static RestLabelList getLabels(HttpHeaders requestHeaders, @NotNull TestRestTemplate template) {
final HttpEntity<RestLabelList> findLabelEntity = new HttpEntity<>(requestHeaders);
final ResponseEntity<RestLabelList> response = template.exchange(BASE_REST_URL + "/labels/", HttpMethod.GET, findLabelEntity, RestLabelList.class);
return response.getBody();
}
@Test
public void createLabel() {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a new label
final String title1 = "Label 1 - ";
addNewLabel(requestHeaders, restTemplate, title1, COLOR);
// Create a new label
final String title2 = "Label 2 - ";
addNewLabel(requestHeaders, restTemplate, title2, COLOR);
// Check that the label has been created ...
final RestLabelList restLabelList = getLabels(requestHeaders, restTemplate);
// Validate that the two labels are there ...
final List<RestLabel> labels = restLabelList.getLabels();
long count = labels.stream().filter(l -> Objects.equals(l.getTitle(), title1) || Objects.equals(l.getTitle(), title2)).count();
assertEquals(2, count, "Labels could not be found");
}
@Test
public void createLabelWithoutRequiredField() {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
requestHeaders.set(HttpHeaders.ACCEPT_LANGUAGE, "en");
try {
addNewLabel(requestHeaders, restTemplate, null, COLOR);
fail("Wrong response");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("Required field cannot be left blank"), e.getMessage());
}
try {
addNewLabel(requestHeaders, restTemplate, "title12345", null);
fail("Wrong response");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("Required field cannot be left blank"), e.getMessage());
}
}
@Test
public void deleteLabel() {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
final String title = "title to delete";
final URI resourceUri = addNewLabel(requestHeaders, restTemplate, title, COLOR);
// Now remove it ...
restTemplate.delete(resourceUri.toString());
final RestLabelList restLabelList = getLabels(requestHeaders, restTemplate);
for (RestLabel restLabel : restLabelList.getLabels()) {
if (title.equals(restLabel.getTitle())) {
fail("Label could not be removed:" + resourceUri);
}
}
}
static URI addNewLabel(@NotNull HttpHeaders requestHeaders, @NotNull TestRestTemplate template, @Nullable String title, @Nullable String color) {
final RestLabel restLabel = new RestLabel();
if (title != null) {
restLabel.setTitle(title);
}
if (color != null) {
restLabel.setColor(color);
}
// Create a new label ...
final HttpEntity<RestLabel> createUserEntity = new HttpEntity<>(restLabel, requestHeaders);
final ResponseEntity<String> result = template.exchange("/api/restful/labels", HttpMethod.POST, createUserEntity, String.class);
if (!result.getStatusCode().is2xxSuccessful()) {
throw new IllegalStateException(result.toString());
}
;
return result.getHeaders().getLocation();
}
}

View File

@@ -1,839 +0,0 @@
package com.wisemapping.test.rest;
import com.wisemapping.config.common.CommonConfig;
import com.wisemapping.config.rest.RestAppConfig;
import com.wisemapping.exceptions.WiseMappingException;
import com.wisemapping.rest.AdminController;
import com.wisemapping.rest.MindmapController;
import com.wisemapping.rest.UserController;
import com.wisemapping.rest.model.*;
import jakarta.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.util.DefaultUriBuilderFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.wisemapping.test.rest.RestHelper.createHeaders;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(
classes = {RestAppConfig.class, CommonConfig.class, MindmapController.class, AdminController.class, UserController.class},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"app.api.http-basic-enabled=true"})
public class RestMindmapControllerTest {
private RestUser user;
@Autowired
private TestRestTemplate restTemplate;
@BeforeEach
void createUser() {
// Remote debug ...
if (restTemplate == null) {
this.restTemplate = new TestRestTemplate();
this.restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory("http://localhost:8081/"));
}
final RestAccountControllerTest restAccount = RestAccountControllerTest.create(restTemplate);
this.user = restAccount.createNewUser();
}
@Test
public void listMaps() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String title1 = "List Maps 1";
addNewMap(restTemplate, title1);
final String title2 = "List Maps 2";
addNewMap(restTemplate, title2);
// Validate that the two maps are there ...
final RestMindmapList body = fetchMaps(requestHeaders, restTemplate);
final List<RestMindmapInfo> mindmaps = body.getMindmapsInfo();
boolean found1 = false;
boolean found2 = false;
for (RestMindmapInfo mindmap : mindmaps) {
if (mindmap.getTitle().equals(title1)) {
found1 = true;
}
if (mindmap.getTitle().equals(title2)) {
found2 = true;
}
}
assertTrue(found1 && found2, "Map could not be found");
}
@Test
public void deleteMap() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String title1 = "Map to delete";
final URI resourceUri = addNewMap(restTemplate, title1);
// Now remove it ...
final ResponseEntity<String> exchange = restTemplate.exchange(resourceUri.toString(), HttpMethod.DELETE, null, String.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful(), "Status code:" + exchange.getStatusCode());
// Check that has been removed ...
try {
findMap(requestHeaders, restTemplate, resourceUri);
fail("Map could not be removed:" + resourceUri);
} catch (Exception e) {
// Ignore
}
}
@Test
public void changeMapTitle() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "Map to change title");
final String newTitle = changeMapTitle(requestHeaders, MediaType.APPLICATION_JSON, restTemplate, resourceUri);
// Load map again ..
final RestMindmap map = findMap(requestHeaders, restTemplate, resourceUri);
assertEquals(newTitle, map.getTitle());
}
@Test
public void validateMapsCreation() throws URISyntaxException { // Configure media types ...
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
requestHeaders.set(HttpHeaders.ACCEPT_LANGUAGE, "en");
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String title = "Map to Validate Creation";
addNewMap(restTemplate, title);
// Add map with same name ...
HttpEntity<RestMindmap> createUserEntity = new HttpEntity<>(requestHeaders);
final ResponseEntity<String> response = restTemplate.exchange("/api/restful/maps?title=" + title, HttpMethod.POST, createUserEntity, String.class);
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
assertTrue(Objects.requireNonNull(response.getBody()).contains("You have already a map with the same name"));
}
@Test
public void changeMapDescription() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "Map to change Description ");
// Change map title ...
requestHeaders.setContentType(MediaType.TEXT_PLAIN);
final String newDescription = "New map to change description ";
final HttpEntity<String> updateEntity = new HttpEntity<>(newDescription, requestHeaders);
restTemplate.put(resourceUri + "/description", updateEntity);
// Load map again ..
final RestMindmap map = findMap(requestHeaders, restTemplate, resourceUri);
assertEquals(newDescription, map.getDescription());
}
@Test
public void updateMapXml() throws IOException, URISyntaxException { // Configure media types ...
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String title = "Update XML sample";
final URI resourceUri = addNewMap(restTemplate, title);
// Update map xml content ...
final String resourceUrl = resourceUri.toString();
String newXmlContent = updateMapDocument(requestHeaders, restTemplate, resourceUrl, null);
// Check that the map has been updated ...
final RestMindmap response = findMap(requestHeaders, restTemplate, resourceUri);
assertEquals(response.getXml(), newXmlContent);
}
private String updateMapDocument(final HttpHeaders requestHeaders, final TestRestTemplate template, final String resourceUrl, final String content) throws RestClientException {
requestHeaders.setContentType(MediaType.TEXT_PLAIN);
final String newXmlContent = content != null ? content : "<map>this is not valid</map>";
HttpEntity<String> updateEntity = new HttpEntity<>(newXmlContent, requestHeaders);
template.put(resourceUrl + "/document/xml", updateEntity);
return newXmlContent;
}
@Test
public void cloneMap() throws IOException, URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String title = "Map to clone sample ";
final String xml = "<map><node text='this is a cloned map'></map>";
final URI newMapUri = addNewMap(restTemplate, title, xml);
// Clone map ...
final RestMindmapInfo restMindmap = new RestMindmapInfo();
restMindmap.setTitle("Cloned map but with previous content.");
restMindmap.setDescription("Cloned map desc");
// Create a new map ...
final HttpEntity<RestMindmapInfo> cloneEntity = new HttpEntity<>(restMindmap, requestHeaders);
final ResponseEntity<Void> exchange = restTemplate.exchange(newMapUri.toString(), HttpMethod.POST, cloneEntity, Void.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful());
URI clonedMapUri = exchange.getHeaders().getLocation();
// Check that the map has been updated ...
final RestMindmap response = findMap(requestHeaders, restTemplate, clonedMapUri);
assertEquals(response.getXml(), xml);
}
@Test
public void updateStarred() throws URISyntaxException { // Configure media types ...
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String title1 = "Stared Map user 1";
URI mapUri = addNewMap(restTemplate, title1);
// Update starred ...
final String resourceUrl = mapUri.toString() + "/starred";
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
final HttpHeaders textContentType = new HttpHeaders();
textContentType.setContentType(MediaType.TEXT_PLAIN);
final HttpEntity<String> updateEntity = new HttpEntity<>("true", textContentType);
restTemplate.put(resourceUrl, updateEntity);
// Has been updated ?.
final HttpEntity<String> findLabelEntity = new HttpEntity<>(createHeaders(MediaType.TEXT_PLAIN));
final ResponseEntity<String> response = restTemplate.exchange(resourceUrl, HttpMethod.GET, findLabelEntity, String.class);
assertTrue(Boolean.parseBoolean(response.getBody()), "Starred has been updated");
}
@Test
public void verifyMapOwnership() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate firstUser = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String title1 = "verifyMapOwnership Map user 1";
addNewMap(firstUser, title1);
//create another user
final RestUser secondUser = RestAccountControllerTest.create(this.restTemplate).createNewUser();
final TestRestTemplate secondTemplate = this.restTemplate.withBasicAuth(secondUser.getEmail(), secondUser.getPassword());
final String title2 = "verifyMapOwnership Map user 2";
addNewMap(secondTemplate, title2);
final TestRestTemplate superadminTemplate = this.restTemplate.withBasicAuth("admin@wisemapping.org", "test");
final ResponseEntity<String> exchange = superadminTemplate.exchange("/api/restful/admin/users/" + secondUser.getId(), HttpMethod.DELETE, null, String.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful(), "Status Code:" + exchange.getStatusCode() + "- " + exchange.getBody());
// Validate that the two maps are there ...
final RestMindmapList body = fetchMaps(requestHeaders, firstUser);
final List<RestMindmapInfo> mindmaps = body.getMindmapsInfo();
final Optional<RestMindmapInfo> any = mindmaps.stream().filter(m -> m.getTitle().equals(title1)).findAny();
assertTrue(any.isPresent(), "Map could not be found");
}
@Test
public void updateMap() throws IOException, WiseMappingException, URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String title = "Update sample ";
final URI resourceUri = addNewMap(restTemplate, title);
// Build map to update ...
final RestMindmap mapToUpdate = new RestMindmap();
mapToUpdate.setXml("<map>this is not valid</map>");
mapToUpdate.setProperties("{zoom:x}");
// Create lock ...
final HttpHeaders lockHeaders = createHeaders(MediaType.APPLICATION_JSON);
lockHeaders.setContentType(MediaType.TEXT_PLAIN);
// Update map ...
final String resourceUrl = resourceUri.toString() + "/document";
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
final HttpEntity<RestMindmap> updateEntity = new HttpEntity<>(mapToUpdate, requestHeaders);
restTemplate.put(resourceUrl, updateEntity);
// Check that the map has been updated ...
HttpEntity<RestUser> findMapEntity = new HttpEntity<>(requestHeaders);
final ResponseEntity<RestMindmap> response = restTemplate.exchange(resourceUri.toString(), HttpMethod.GET, findMapEntity, RestMindmap.class);
assertEquals(Objects.requireNonNull(response.getBody()).getXml(), mapToUpdate.getXml());
assertEquals(response.getBody().getProperties(), mapToUpdate.getProperties());
// Unlock ...
HttpEntity<String> lockEntity = new HttpEntity<>("false", lockHeaders);
restTemplate.exchange(resourceUri + "/lock", HttpMethod.PUT, lockEntity, RestLockInfo.class);
}
@Test
public void addCollabs() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "Map for addCollabs - ");
String newCollab = addNewCollaboration(requestHeaders, restTemplate, resourceUri);
// Has been added ?
RestCollaborationList responseCollbs = fetchAndGetCollabs(requestHeaders, restTemplate, resourceUri);
// Has been added ?
assertEquals(responseCollbs.getCount(), 2);
final Optional<RestCollaboration> addedCollab = responseCollbs.getCollaborations().stream().filter(c -> c.getEmail().equals(newCollab)).findAny();
assertTrue(addedCollab.isPresent());
assertEquals(addedCollab.get().getRole(), "editor");
}
@Test
public void updateCollabType() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "Map for updateCollabType");
// Add a new collaboration ...
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
final RestCollaborationList collabs = new RestCollaborationList();
collabs.setMessage("Adding new permission");
final String newCollab = "new-collab@example.com";
String role = "editor";
final RestCollaboration collab = addCollabToList(newCollab, role, collabs);
final HttpEntity<RestCollaborationList> updateEntity = new HttpEntity<>(collabs, requestHeaders);
restTemplate.put(resourceUri + "/collabs/", updateEntity);
// Has been added ?
RestCollaborationList responseCollbs = fetchAndGetCollabs(requestHeaders, restTemplate, resourceUri);
assertEquals(responseCollbs.getCount(), 2);
// Update the collaboration type ...
collab.setRole("viewer");
restTemplate.put(resourceUri + "/collabs/", updateEntity);
// Has been added ?
final ResponseEntity<RestCollaborationList> afterResponse = fetchCollabs(requestHeaders, restTemplate, resourceUri);
final Optional<RestCollaboration> updatedCollab = Objects.requireNonNull(afterResponse.getBody()).getCollaborations().stream().filter(c -> c.getEmail().equals(newCollab)).findAny();
assertTrue(updatedCollab.isPresent());
assertEquals(updatedCollab.get().getRole(), "viewer");
}
@Test
public void deleteCollabs() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "Map for deleteCollabs - ");
String newCollab = addNewCollaboration(requestHeaders, restTemplate, resourceUri);
// Has been added ?
RestCollaborationList responseCollbs = fetchAndGetCollabs(requestHeaders, restTemplate, resourceUri);
// Has been added ?
assertEquals(responseCollbs.getCount(), 2);
// Now, remove it ...
final ResponseEntity<String> exchange = restTemplate.exchange(resourceUri + "/collabs?email=" + newCollab, HttpMethod.DELETE, null, String.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful());
// Check that it has been removed ...
final ResponseEntity<RestCollaborationList> afterDeleteResponse = fetchCollabs(requestHeaders, restTemplate, resourceUri);
assertEquals(Objects.requireNonNull(afterDeleteResponse.getBody()).getCollaborations().size(), 1);
}
private String addNewCollaboration(final HttpHeaders requestHeaders, final TestRestTemplate template, final URI resourceUri) throws RestClientException {
// Add a new collaboration ...
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
final RestCollaborationList collabs = new RestCollaborationList();
collabs.setMessage("Adding new permission");
final String newCollab = "new-collab@example.com";
String role = "editor";
addCollabToList(newCollab, role, collabs);
final HttpEntity<RestCollaborationList> updateEntity = new HttpEntity<>(collabs, requestHeaders);
template.put(resourceUri + "/collabs/", updateEntity);
return newCollab;
}
@Test
public void deleteCollabsWithInvalidEmail() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "deleteCollabsWithInvalidEmail");
// Remove with invalid email ...
final ResponseEntity<String> exchange = restTemplate.exchange(resourceUri + "/collabs?email=invalidEmail", HttpMethod.DELETE, null, String.class);
assertTrue(exchange.getStatusCode().is4xxClientError());
assertTrue(Objects.requireNonNull(exchange.getBody()).contains("Invalid email exception:"));
// Check that it has been removed ...
final ResponseEntity<RestCollaborationList> afterDeleteResponse = fetchCollabs(requestHeaders, restTemplate, resourceUri);
assertEquals(Objects.requireNonNull(afterDeleteResponse.getBody()).getCollaborations().size(), 1);
}
@Test
public void deleteCollabsWithoutOwnerPermission() throws URISyntaxException {
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
final URI resourceUri = addNewMap(restTemplate, "deleteWithoutOwnerPermission");
// Create a new user ...
final RestAccountControllerTest restAccount = RestAccountControllerTest.create(restTemplate);
this.user = restAccount.createNewUser();
// Create template ...
final RestAccountControllerTest accountController = RestAccountControllerTest.create(restTemplate);
final RestUser anotherUser = accountController.createNewUser();
final TestRestTemplate anotherTemplate = this.restTemplate.withBasicAuth(anotherUser.getEmail(), anotherUser.getPassword());
// Try to delete but I'm not the owner ...
final ResponseEntity<String> exchange = anotherTemplate.exchange(resourceUri + "/collabs?email=" + anotherUser.getEmail(), HttpMethod.DELETE, null, String.class);
assertTrue(exchange.getStatusCode().is4xxClientError());
assertTrue(Objects.requireNonNull(exchange.getBody()).contains("You do not have enough right access to see this map. This map has been changed to private or deleted."));
}
@Test
public void deleteOwnerCollab() throws URISyntaxException {
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "Map for deleteOwnerCollab");
// Now, remove owner collab ...
final ResponseEntity<String> exchange = restTemplate.exchange(resourceUri + "/collabs?email=" + user.getEmail().replace(":admin", ""), HttpMethod.DELETE, null, String.class);
assertTrue(exchange.getStatusCode().is4xxClientError());
assertTrue(Objects.requireNonNull(exchange.getBody()).contains("Can not remove owner collab"));
}
@NotNull
private ResponseEntity<RestCollaborationList> fetchCollabs(HttpHeaders requestHeaders, TestRestTemplate template, URI resourceUri) {
final HttpEntity<RestCollaborationList> findCollabs = new HttpEntity<>(requestHeaders);
return template.exchange(resourceUri + "/collabs", HttpMethod.GET, findCollabs, RestCollaborationList.class);
}
@Test
public void addCollabsInvalidOwner() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...fetchAndGetCollabs(requestHeaders, template, resourceUri);
final URI resourceUri = addNewMap(restTemplate, "Map for Collaboration");
// Add a new collaboration ...
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
final RestCollaborationList collabs = new RestCollaborationList();
collabs.setMessage("Adding new permission");
// Validate that owner can not be added.
addCollabToList("newCollab@example", "owner", collabs);
final HttpEntity<RestCollaborationList> updateEntity = new HttpEntity<>(collabs, requestHeaders);
restTemplate.put(resourceUri + "/collabs/", updateEntity);
}
@Test
public void removeLabelFromMindmap() throws URISyntaxException { // Configure media types ...
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a new label
final String titleLabel = "removeLabelFromMindmap";
final URI labelUri = RestLabelControllerTest.addNewLabel(requestHeaders, restTemplate, titleLabel, "red");
// Create a sample map ...
final String mapTitle = "removeLabelFromMindmap";
final URI mindmapUri = addNewMap(restTemplate, mapTitle);
final String mapId = mindmapUri.getPath().replace("/api/restful/maps/", "");
// Assign label to map ...
String labelId = labelUri.getPath().replace("/api/restful/labels/", "");
HttpEntity<String> labelEntity = new HttpEntity<>(labelId, requestHeaders);
restTemplate.postForLocation("/api/restful/maps/" + mapId + "/labels", labelEntity);
// Remove label from map
final ResponseEntity<String> exchange = restTemplate.exchange("/api/restful//maps/" + mapId + "/labels/" + labelId, HttpMethod.DELETE, null, String.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful());
Optional<RestMindmapInfo> mindmapInfo = fetchMap(requestHeaders, restTemplate, mapId);
assertEquals(0, mindmapInfo.get().getLabels().size());
}
@NotNull
private Optional<RestMindmapInfo> fetchMap(HttpHeaders requestHeaders, TestRestTemplate template, @NotNull String mapId) {
// Check that the label has been removed ...
final List<RestMindmapInfo> mindmapsInfo = fetchMaps(requestHeaders, template).getMindmapsInfo();
return mindmapsInfo
.stream()
.filter(m -> m.getId() == Integer.parseInt(mapId))
.findAny();
}
@Test
@Disabled("missing test: delete map should not affects others labels")
public void deleteMapAndCheckLabels() { // Configure media types ...
}
@Test
public void addLabelToMindmap() throws URISyntaxException { // Configure media types ...
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a new label
final String titleLabel = "Label 1 - ";
final URI labelUri = RestLabelControllerTest.addNewLabel(requestHeaders, restTemplate, titleLabel, "COLOR");
// Create a sample map ...
final String mapTitle = "Maps 1 - ";
final URI mindmapUri = addNewMap(restTemplate, mapTitle);
final String mapId = mindmapUri.getPath().replace("/api/restful/maps/", "");
// Assign label to map ...
String labelId = labelUri.getPath().replace("/api/restful/labels/", "");
HttpEntity<String> labelEntity = new HttpEntity<>(labelId, requestHeaders);
restTemplate.postForLocation("/api/restful/maps/" + mapId + "/labels", labelEntity);
// Check that the label has been assigned ...
Optional<RestMindmapInfo> mindmapInfo = fetchMap(requestHeaders, restTemplate, mapId);
assertEquals(1, mindmapInfo.get().getLabels().size());
}
@Test
public void fetchMapMetadata() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String mapTitle = "Maps 1 !";
final URI mindmapUri = addNewMap(restTemplate, mapTitle);
final String mapId = mindmapUri.getPath().replace("/api/restful/maps/", "");
final ResponseEntity<RestMindmapMetadata> exchange = restTemplate.exchange(mindmapUri + "/metadata", HttpMethod.GET, null, RestMindmapMetadata.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful());
assertEquals(mapTitle, exchange.getBody().getTitle());
}
@Test
public void updateCollabs() throws URISyntaxException {
// Create a sample map ...
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
final URI resourceUri = addNewMap(restTemplate, "Map for updateCollabs");
// Add a new collaboration ...
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
RestCollaborationList collabs = new RestCollaborationList();
collabs.setMessage("Adding new permission");
String newCollab = "new-collab@example.com";
String role = "editor";
addCollabToList(newCollab, role, collabs);
HttpEntity<RestCollaborationList> updateEntity = new HttpEntity<>(collabs, requestHeaders);
restTemplate.put(resourceUri + "/collabs/", updateEntity);
collabs = fetchAndGetCollabs(requestHeaders, restTemplate, resourceUri);
//delete one collab
collabs.setCollaborations(collabs.getCollaborations().stream().filter(c -> c.getRole().equals("owner")).collect(Collectors.toList()));
//Add another collaborationMediaType
newCollab = "another-collab@example.com";
addCollabToList(newCollab, role, collabs);
//add owner to list
addCollabToList(user.getEmail().replace(":admin", ""), "owner", collabs);
updateEntity = new HttpEntity<>(collabs, requestHeaders);
restTemplate.postForLocation(resourceUri + "/collabs/", updateEntity);
final RestCollaborationList responseCollbs = fetchAndGetCollabs(requestHeaders, restTemplate, resourceUri);
// Has been another-collaboration list updated ?
assertTrue(responseCollbs.getCollaborations().stream().anyMatch(x -> x.getEmail().equals("another-collab@example.com")));
assertEquals(responseCollbs.getCount(), 2);
}
@Test
public void updateProperties() throws IOException, WiseMappingException, URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String title = "updateProperties map";
final URI resourceUri = addNewMap(restTemplate, title);
// Build map to update ...
final RestMindmap mapToUpdate = new RestMindmap();
mapToUpdate.setXml("<map>this is not valid</map>");
mapToUpdate.setProperties("{zoom:x}");
mapToUpdate.setTitle("new title for map");
mapToUpdate.setDescription("updated map description");
// Update map ...
final String resourceUrl = resourceUri.toString();
final HttpEntity<RestMindmap> updateEntity = new HttpEntity<>(mapToUpdate, requestHeaders);
restTemplate.put(resourceUrl, updateEntity);
// Check that the map has been updated ...
HttpEntity<RestUser> findMapEntity = new HttpEntity<>(requestHeaders);
final ResponseEntity<RestMindmap> response = restTemplate.exchange(resourceUri.toString(), HttpMethod.GET, findMapEntity, RestMindmap.class);
assertEquals(response.getBody().getTitle(), mapToUpdate.getTitle());
assertEquals(response.getBody().getDescription(), mapToUpdate.getDescription());
assertEquals(response.getBody().getXml(), mapToUpdate.getXml());
assertEquals(response.getBody().getProperties(), mapToUpdate.getProperties());
}
@Test
public void batchDelete() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String title1 = "Batch delete map 1";
addNewMap(restTemplate, title1);
final String title2 = "Batch delete map 2";
addNewMap(restTemplate, title2);
final String maps = fetchMaps(requestHeaders, restTemplate).getMindmapsInfo().stream().map(map -> String.valueOf(map.getId())).collect(Collectors.joining(","));
final ResponseEntity<String> exchange = restTemplate.exchange("/api/restful/maps/batch?ids=" + maps, HttpMethod.DELETE, null, String.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful(), "Status code:" + exchange.getStatusCode() + " - " + exchange.getBody());
// Validate that the two maps are there ...
final RestMindmapList body = fetchMaps(requestHeaders, restTemplate);
assertEquals(0, body.getMindmapsInfo().size());
}
@Test
public void updatePublishState() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final String mapTitle = "updatePublishState";
final URI mindmapUri = addNewMap(restTemplate, mapTitle);
// Change map status ...
requestHeaders.setContentType(MediaType.TEXT_PLAIN);
final HttpEntity<String> updateEntity = new HttpEntity<>(Boolean.TRUE.toString(), requestHeaders);
final ResponseEntity<String> exchange = restTemplate.exchange(mindmapUri + "/publish", HttpMethod.PUT, updateEntity, String.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful());
}
@Test
public void fetchMapHistory() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "Map to change title");
updateMapDocument(requestHeaders, restTemplate, resourceUri.toString(), null);
//fetch map history
final HttpEntity<RestMindmapHistoryList> findMapEntity = new HttpEntity<>(requestHeaders);
final ResponseEntity<RestMindmapHistoryList> maps = restTemplate.exchange(resourceUri + "/history/", HttpMethod.GET, findMapEntity, RestMindmapHistoryList.class);
assertTrue(maps.getStatusCode().is2xxSuccessful(), maps.toString());
assertEquals(1, Objects.requireNonNull(maps.getBody()).getCount());
}
@Test
public void updateRevertMindmap() throws IOException, URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "map to test revert changes");
updateMapDocument(requestHeaders, restTemplate, resourceUri.toString(), "<map><node text='this is an xml to test revert changes service'></map>");
updateMapDocument(requestHeaders, restTemplate, resourceUri.toString(), "<map><node text='this is an xml with modification to be reverted'></map>");
//fetch map history
final HttpEntity<RestMindmapHistoryList> findMapEntity = new HttpEntity<>(requestHeaders);
final ResponseEntity<RestMindmapHistoryList> mapHistories = restTemplate.exchange(resourceUri + "/history/", HttpMethod.GET, findMapEntity, RestMindmapHistoryList.class);
//aply revert
final HttpEntity<String> cloneEntity = new HttpEntity<>(requestHeaders);
restTemplate.postForLocation(resourceUri + "/history/latest", cloneEntity);
final RestMindmap latestStoredMap = findMap(requestHeaders, restTemplate, resourceUri);
restTemplate.postForLocation(resourceUri + "/history/" + mapHistories.getBody().getChanges().get(1).getId(), cloneEntity);
final RestMindmap firstVersionMap = findMap(requestHeaders, restTemplate, resourceUri);
//verify revert
assertEquals(firstVersionMap.getXml(), "<map><node text='this is an xml to test revert changes service'></map>");
assertEquals(latestStoredMap.getXml(), "<map><node text='this is an xml with modification to be reverted'></map>");
}
@Test
public void addCollabWhitoutOwnerPermission() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "MaddCollabWhitoutOwnerPermission");
// Add a new collaboration ...
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
final RestCollaborationList collabs = new RestCollaborationList();
collabs.setMessage("Adding new permission");
final RestAccountControllerTest restAccount = RestAccountControllerTest.create(restTemplate);
final RestUser newCollab = restAccount.createNewUser();
String role = "editor";
addCollabToList(newCollab.getEmail(), role, collabs);
final HttpEntity<RestCollaborationList> updateEntity = new HttpEntity<>(collabs, requestHeaders);
restTemplate.put(resourceUri + "/collabs/", updateEntity);
final TestRestTemplate newCollabTemplate = this.restTemplate.withBasicAuth(newCollab.getEmail(), newCollab.getPassword());
final ResponseEntity<Void> exchange = newCollabTemplate.exchange(resourceUri + "/collabs/", HttpMethod.PUT, updateEntity, Void.class);
assertTrue(exchange.getStatusCode().is4xxClientError(), exchange.toString());
}
@Test
public void addCollabWhitOwnerRole() throws URISyntaxException {
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_JSON);
final TestRestTemplate restTemplate = this.restTemplate.withBasicAuth(user.getEmail(), user.getPassword());
// Create a sample map ...
final URI resourceUri = addNewMap(restTemplate, "addCollabWhitOwnerRole");
// Add a new collaboration ...
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
final RestCollaborationList collabs = new RestCollaborationList();
collabs.setMessage("Adding new permission");
final String newCollab = "new-collaborator@mail.com";
String role = "owner";
addCollabToList(newCollab, role, collabs);
final HttpEntity<RestCollaborationList> updateEntity = new HttpEntity<>(collabs, requestHeaders);
final ResponseEntity<RestCollaborationList> collabsList = restTemplate.exchange(resourceUri + "/collabs/", HttpMethod.PUT, updateEntity, RestCollaborationList.class);
assertTrue(collabsList.getStatusCode().is4xxClientError());
}
private String changeMapTitle(final HttpHeaders requestHeaders, final MediaType mediaType, final TestRestTemplate template, final URI resourceUri) throws RestClientException {
requestHeaders.setContentType(MediaType.TEXT_PLAIN);
final String result = "New map to change title - " + mediaType;
final HttpEntity<String> updateEntity = new HttpEntity<>(result, requestHeaders);
template.put(resourceUri + "/title", updateEntity);
return result;
}
@NotNull
private RestMindmapList fetchMaps(final HttpHeaders requestHeaders, final TestRestTemplate template) throws RestClientException {
final HttpEntity<RestMindmapList> findMapEntity = new HttpEntity<>(requestHeaders);
final ResponseEntity<RestMindmapList> response = template.exchange("/api/restful/maps/", HttpMethod.GET, findMapEntity, RestMindmapList.class);
assertTrue(response.getStatusCode().is2xxSuccessful(), response.toString());
return Objects.requireNonNull(response.getBody());
}
private RestCollaborationList fetchAndGetCollabs(final HttpHeaders requestHeaders, final TestRestTemplate template, final URI resourceUri) {
final ResponseEntity<RestCollaborationList> response = fetchCollabs(requestHeaders, template, resourceUri);
return response.getBody();
}
private RestCollaboration addCollabToList(String newCollab, String role, RestCollaborationList collabs) {
RestCollaboration collab = new RestCollaboration();
collab.setEmail(newCollab);
collab.setRole(role);
collabs.addCollaboration(collab);
return collab;
}
private RestMindmap findMap(@NotNull HttpHeaders requestHeaders, @NotNull TestRestTemplate template, URI resourceUri) {
final HttpEntity<RestMindmap> findMapEntity = new HttpEntity<>(requestHeaders);
final ResponseEntity<RestMindmap> response = template.exchange(resourceUri.toString(), HttpMethod.GET, findMapEntity, RestMindmap.class);
if (!response.getStatusCode().is2xxSuccessful()) {
throw new IllegalArgumentException(response.toString());
}
return response.getBody();
}
//
private URI addNewMap(@NotNull TestRestTemplate template, @NotNull String title, @Nullable String xml) throws URISyntaxException {
// Create a new map ...
final HttpHeaders requestHeaders = createHeaders(MediaType.APPLICATION_XML);
final HttpEntity<String> createUserEntity = new HttpEntity<>(xml, requestHeaders);
final ResponseEntity<String> exchange = template.exchange("/api/restful/maps?title=" + title, HttpMethod.POST, createUserEntity, String.class);
assertTrue(exchange.getStatusCode().is2xxSuccessful());
final List<String> locations = exchange.getHeaders().get(HttpHeaders.LOCATION);
return new URI(locations.stream().findFirst().get());
}
private URI addNewMap(@NotNull TestRestTemplate template, @NotNull String title) throws URISyntaxException {
return addNewMap(template, title, null);
}
}

View File

@@ -1,119 +0,0 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.test.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wisemapping.config.common.CommonConfig;
import com.wisemapping.config.rest.RestAppConfig;
import com.wisemapping.model.Account;
import com.wisemapping.rest.UserController;
import com.wisemapping.rest.model.RestUser;
import com.wisemapping.rest.model.RestUserRegistration;
import com.wisemapping.service.UserService;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static com.wisemapping.test.rest.RestHelper.createDummyUser;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest(
classes = {RestAppConfig.class, CommonConfig.class, UserController.class},
properties = {"app.api.http-basic-enabled=true"}
)
@AutoConfigureMockMvc
public class RestUserControllerTest {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private MockMvc mockMvc;
@Autowired
private UserService userService;
private RestUser createUser() throws Exception {
final RestUser result = createDummyUser();
final String userJson = objectMapper.writeValueAsString(result);
mockMvc.perform(
post("/api/restful/admin/users").
contentType(MediaType.APPLICATION_JSON)
.content(userJson)
.with(user("test@wisemapping.org").roles("ADMIN")))
.andExpect(status().isCreated());
// Check dao ...
Account userBy = userService.getUserBy(result.getEmail());
assertNotNull(userBy);
return result;
}
@Test
void resetPasswordInvalidUser() throws Exception {
this.mockMvc.perform
(put("/api/restful/users/resetPassword?email=doesnotexist@example.com"))
.andDo(print())
.andExpect(status().is4xxClientError())
.andExpect(content().string(containsString("The email provided is not a valid user account.")));
}
@Test
void resetPasswordValidUser() throws Exception {
final RestUser user = createUser();
this.mockMvc.perform
(put("/api/restful/users/resetPassword?email=" + user.getEmail()))
.andDo(print())
.andExpect(status().isOk());
}
@Test
@Disabled
void registerNewUser() throws Exception {
final RestUserRegistration user = RestUserRegistration.create("some@example.com", "somepass", "Test", "registation");
final String userJson = objectMapper.writeValueAsString(user);
mockMvc.perform(
post("/api/restful/users/").
contentType(MediaType.APPLICATION_JSON)
.content(userJson))
.andExpect(status().isCreated());
// Check dao ...
Account userBy = userService.getUserBy(user.getEmail());
assertNotNull(userBy);
}
}

View File

@@ -1,25 +0,0 @@
FROM node:18.12.1-buster-slim AS builder
# Set the working directory in the container
WORKDIR /app
ARG VERSION="6.0.1"
# Install dependencies
RUN mkdir webapp && npm pack @wisemapping/webapp@${VERSION} && tar -xvzf wisemapping-webapp-${VERSION}.tgz -C webapp
# Use Nginx as the production server
FROM nginx:latest
LABEL maintainer="Paulo Gustavo Veiga <pveiga@wisemapping.com>"
## Copy the built React app to Nginx's web server directory
COPY --from=builder /app/webapp/package/dist/* /usr/share/nginx/html/
ADD nginx.conf .
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Expose port 80 for the Nginx server
EXPOSE 80
# Start Nginx when the container runs
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -1,29 +0,0 @@
server {
listen 80;
gzip on;
charset UTF-8;
server_name wise-ui;
# Change base URL to match the host URL.
sub_filter '<base>' '<base href="http://$host/">';
location / {
# This would be the directory where your React app's static files are stored at
root /usr/share/nginx/html;
try_files $uri /index.html;
}
location /c/ {
try_files $uri /usr/share/nginx/html/index.html;
}
location /api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://wise-api:8080/api/;
proxy_ssl_session_reuse off;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
proxy_redirect off;
}
}

78
wise-ui/pom.xml Normal file
View File

@@ -0,0 +1,78 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.wisemapping</groupId>
<artifactId>wise-ui</artifactId>
<packaging>war</packaging>
<name>WiseMapping Frontend</name>
<parent>
<groupId>org.wisemapping</groupId>
<artifactId>wisemapping</artifactId>
<relativePath>../pom.xml</relativePath>
<version>5.0.10</version>
</parent>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<tasks>
<!-- Download and unzip mindplot npm package -->
<mkdir dir="target/wisemapping-mindplot"/>
<exec executable="npm" dir="target" failonerror="true">
<arg value="pack"/>
<arg value="@wisemapping/mindplot@5.0.10"/>
</exec>
<exec executable="tar" dir="target" failonerror="true">
<arg value="-xvzf"/>
<arg value="wisemapping-mindplot-5.0.10.tgz"/>
<arg value="-C"/>
<arg value="wisemapping-mindplot"/>
</exec>
<!-- Download and unzip webapp npm package -->
<mkdir dir="target/wisemapping-webapp"/>
<exec executable="npm" dir="target" failonerror="true">
<arg value="pack"/>
<arg value="@wisemapping/webapp@5.0.11"/>
</exec>
<exec executable="tar" dir="target" failonerror="true">
<arg value="-xvzf"/>
<arg value="wisemapping-webapp-5.0.11.tgz"/>
<arg value="-C"/>
<arg value="wisemapping-webapp"/>
</exec>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<webResources>
<resource>
<directory>target</directory>
<!-- this is relative to the pom.xml directory -->
<includes>wisemapping-*/**/dist/*</includes>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>
</project>

1
wise-webapp/config Symbolic link
View File

@@ -0,0 +1 @@
../config/

View File

@@ -0,0 +1,4 @@
# Compilation and Execution
Your will find all the steps and required documentation here: http://www.wisemapping.org/downloads/source

View File

@@ -37,6 +37,6 @@ Template Path: /service/admin/users/{userId}/password
Creating a new user:
* Template Path: /service/admin/users/
* Method: Post
* curl "http://{host.name}:{host.port}/{context.path}/service/admin/users/" --request POST --basic -u "admin@wisemapping.org:test" -H "Content-Type:application/json" --data '{"email": "te2@mydomain.de", "lastname": "lastname", "firstname":"myfirstname","password":"password"}'
* curl "http://{host.name}:{host.port}/{context.path}/service/admin/users" --request POST --basic -u "admin@wisemapping.org:test" -H "Content-Type:application/json" --data '{"email": "te2@mydomain.de", "lastname": "lastname", "firstname":"myfirstname","password":"password"}'

541
wise-webapp/pom.xml Normal file
View File

@@ -0,0 +1,541 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>wise-webapp</artifactId>
<packaging>war</packaging>
<name>WiseMapping Webapp</name>
<url>http://www.wisemapping.org</url>
<parent>
<groupId>org.wisemapping</groupId>
<artifactId>wisemapping</artifactId>
<relativePath>../pom.xml</relativePath>
<version>5.0.10</version>
</parent>
<properties>
<org.springframework.version>5.3.14</org.springframework.version>
<org.springframework.addons>5.3.5.RELEASE</org.springframework.addons>
<hibernate.version>5.6.5.Final</hibernate.version>
<hibernate-validator.version>6.0.21.Final</hibernate-validator.version>
<spring-security-taglibs.version>5.6.1</spring-security-taglibs.version>
</properties>
<dependencies>
<dependency>
<groupId>org.wisemapping</groupId>
<artifactId>wise-ui</artifactId>
<version>${com.wisemapping.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.intellij</groupId>
<artifactId>annotations</artifactId>
<version>7.0.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>${org.springframework.addons}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-security-taglibs.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.15</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>3.0.8</version>
<scope>runtime</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${org.springframework.addons}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${org.springframework.addons}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${org.springframework.addons}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.9.9</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.7</version>
</dependency>
<!-- Only for test purposes -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>hsqldb</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<configuration>
<driver>org.hsqldb.jdbc.JDBCDriver</driver>
<url>jdbc:hsqldb:file:${project.build.directory}/db/wisemapping</url>
<username>sa</username>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.5</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.6.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>drop-schemas</id>
<phase>prepare-package</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<onError>continue</onError>
<orderFile>descending</orderFile>
<fileset>
<basedir>${project.basedir}</basedir>
<includes>
<include>config/database/hsql/drop-schemas.sql</include>
<include>config/database/hsql/create-schemas.sql</include>
<include>config/database/hsql/apopulate-schemas.sql</include>
</includes>
</fileset>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>mysqldb</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.5</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>init-schema</id>
<goals>
<goal>execute</goal>
</goals>
<phase>prepare-package</phase>
</execution>
</executions>
<configuration>
<driver>com.mysql.jdbc.Driver</driver>
<username>root</username>
<password></password>
<url>jdbc:mysql://127.0.0.1:3306/?useUnicode=true&amp;characterEncoding=UTF-8</url>
<autocommit>false</autocommit>
<srcFiles>
<srcFile>config/database/mysql/create-database.sql</srcFile>
<srcFile>config/database/mysql/create-schemas.sql</srcFile>
<srcFile>config/database/mysql/apopulate-schemas.sql</srcFile>
</srcFiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.hibernate.orm.tooling</groupId>
<artifactId>hibernate-enhance-maven-plugin</artifactId>
<version>${hibernate.version}</version>
<executions>
<execution>
<phase>compile</phase>
<configuration>
<failOnError>true</failOnError>
<enableLazyInitialization>true</enableLazyInitialization>
<enableDirtyTracking>true</enableDirtyTracking>
<enableAssociationManagement>true</enableAssociationManagement>
<enableExtendedEnhancement>false</enableExtendedEnhancement>
<enableExtendedEnhancement>false</enableExtendedEnhancement>
</configuration>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>native2ascii-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>native2ascii</goal>
</goals>
</execution>
</executions>
<configuration>
<encoding>UTF-8</encoding>
<includes>
<include>messages*.properties</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
<configuration>
<warName>wisemapping</warName>
<overlays>
<overlay>
<groupId>org.wisemapping</groupId>
<artifactId>wise-ui</artifactId>
<targetPath>/static/mindplot/</targetPath>
<includes>
<include>wisemapping-mindplot/package/dist/*</include>
</includes>
</overlay>
<overlay>
<groupId>org.wisemapping</groupId>
<artifactId>wise-ui</artifactId>
<targetPath>/static/webapp/</targetPath>
<includes>
<include>wisemapping-webapp/package/dist/*</include>
</includes>
</overlay>
</overlays>
<archiveClasses>true</archiveClasses>
<webResources>
<resource>
<directory>src/main/resources</directory>
<targetPath>WEB-INF</targetPath>
<includes>
<include>*.wsdl</include>
<include>*.xsd</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.0</version>
<configuration>
<path>/wisemapping</path>
<warFile>${project.build.directory}/wisemapping.war</warFile>
<mode>war</mode>
<update>true</update>
<systemProperties>
<database.base.url>${project.build.directory}</database.base.url>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.34.v20201102</version>
<configuration>
<stopKey>foo</stopKey>
<stopPort>9999</stopPort>
<war>${project.build.directory}/wisemapping.war</war>
<reload>automatic</reload>
<webAppConfig>
<overrideDescriptor>${project.basedir}/webdefault.xml</overrideDescriptor>
</webAppConfig>
<systemProperties>
<systemProperty>
<name>org.mortbay.util.FileResource.checkAliases</name>
<value>false</value>
</systemProperty>
<systemProperty>
<name>org.mortbay.util.FileResource.checkAliases</name>
<value>false</value>
</systemProperty>
<systemProperty>
<name>database.base.url</name>
<value>${project.build.directory}</value>
</systemProperty>
</systemProperties>
</configuration>
<executions>
<execution>
<id>run-forked</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run-forked</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<waitForChild>false</waitForChild>
<jvmArgs>-Ddatabase.base.url=${project.build.directory}</jvmArgs>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,26 @@
package com.wisemapping.dao;
import com.wisemapping.model.Label;
import com.wisemapping.model.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public interface LabelManager {
void addLabel(@NotNull final Label label);
void saveLabel(@NotNull final Label label);
@NotNull
List<Label> getAllLabels(@NotNull final User user);
@Nullable
Label getLabelById(int id, @NotNull final User user);
@Nullable
Label getLabelByTitle(@NotNull final String title, @NotNull final User user);
void removeLabel(@NotNull final Label label);
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.dao;
import com.wisemapping.model.Label;
import com.wisemapping.model.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import java.util.List;
public class LabelManagerImpl extends HibernateDaoSupport
implements LabelManager {
@Override
public void addLabel(@NotNull final Label label) {
saveLabel(label);
}
@Override
public void saveLabel(@NotNull final Label label) {
currentSession().save(label);
}
@NotNull
@Override
@SuppressWarnings("unchecked")
public List<Label> getAllLabels(@NotNull final User user) {
var query = currentSession().createQuery("from com.wisemapping.model.Label wisemapping where creator_id=:creatorId");
query.setParameter("creatorId", user.getId());
return query.list();
}
@Nullable
@Override
public Label getLabelById(int id, @NotNull final User user) {
var query = currentSession().createQuery("from com.wisemapping.model.Label wisemapping where id=:id and creator=:creator");
query.setParameter("id", id);
query.setParameter("creator", user);
return getFirst(query.list());
}
@Nullable
@Override
public Label getLabelByTitle(@NotNull String title, @NotNull final User user) {
var query = currentSession().createQuery("from com.wisemapping.model.Label wisemapping where title=:title and creator=:creator");
query.setParameter("title", title);
query.setParameter("creator", user);
return getFirst(query.list());
}
@Override
public void removeLabel(@NotNull Label label) {
getHibernateTemplate().delete(label);
}
@Nullable private Label getFirst(List<Label> labels) {
Label result = null;
if (labels != null && !labels.isEmpty()) {
result = labels.get(0);
}
return result;
}
}

View File

@@ -22,22 +22,31 @@ import com.wisemapping.model.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.List;
public interface MindmapManager {
Collaborator findCollaborator(@NotNull String email);
Collaborator findCollaborator(int id);
List<Collaboration> findCollaboration(final int collaboratorId);
List<Collaboration> findCollaboration(final CollaborationRole userRole);
Collaboration findCollaboration(final int mindmapId, final User user);
List<Mindmap> getAllMindmaps();
@Nullable
Mindmap getMindmapById(int mindmapId);
Mindmap getMindmapByTitle(final String name, final Account user);
Mindmap getMindmapByTitle(final String name, final User user);
void addCollaborator(Collaborator collaborator);
void addMindmap(Account user, Mindmap mindmap);
void addMindmap(User user, Mindmap mindmap);
void saveMindmap(Mindmap mindmap);
@@ -49,11 +58,17 @@ public interface MindmapManager {
void removeCollaboration(Collaboration collaboration);
List<Mindmap> search(MindMapCriteria criteria);
List<Mindmap> search(MindMapCriteria criteria, int maxResult);
List<MindMapHistory> getHistoryFrom(int mindmapId);
MindMapHistory getHistory(int historyId);
void updateCollaboration(@NotNull Collaboration collaboration);
List<Mindmap> findMindmapByUser(Account user);
void purgeHistory(int mapId) throws IOException;
List<Mindmap> findMindmapByUser(User user);
}

View File

@@ -0,0 +1,286 @@
/*
* Copyright [2022] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* 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.
*/
package com.wisemapping.dao;
import com.wisemapping.model.*;
import com.wisemapping.util.ZipUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Junction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import javax.persistence.Query;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
public class MindmapManagerImpl
extends HibernateDaoSupport
implements MindmapManager {
@Override
public Collaborator findCollaborator(@NotNull final String email) {
final Collaborator collaborator;
Query query = currentSession().createQuery("from com.wisemapping.model.Collaborator collaborator where email=:email");
query.setParameter("email", email);
final List<Collaborator> collaborators = query.getResultList();
if (collaborators != null && !collaborators.isEmpty()) {
assert collaborators.size() == 1 : "More than one user with the same email!";
collaborator = collaborators.get(0);
} else {
collaborator = null;
}
return collaborator;
}
@Override
public List<Mindmap> search(MindMapCriteria criteria) {
return search(criteria, -1);
}
@Override
public List<MindMapHistory> getHistoryFrom(int mindmapId) {
final Criteria hibernateCriteria = currentSession().createCriteria(MindMapHistory.class);
hibernateCriteria.add(Restrictions.eq("mindmapId", mindmapId));
hibernateCriteria.addOrder(Order.desc("creationTime"));
// This line throws errors in some environments, so getting all history and taking firsts 10 records
hibernateCriteria.setMaxResults(30);
return hibernateCriteria.list();
}
@Override
public MindMapHistory getHistory(int historyId) {
return getHibernateTemplate().get(MindMapHistory.class, historyId);
}
@Override
public void updateCollaboration(@NotNull Collaboration collaboration) {
getHibernateTemplate().save(collaboration);
}
@Override
public void purgeHistory(int mapId) throws IOException {
final Criteria hibernateCriteria = currentSession().createCriteria(MindMapHistory.class);
hibernateCriteria.add(Restrictions.eq("mindmapId", mapId));
hibernateCriteria.addOrder(Order.desc("creationTime"));
final List<MindMapHistory> historyList = hibernateCriteria.list();
final Mindmap mindmap = this.getMindmapById(mapId);
if (mindmap != null) {
final Calendar yearAgo = Calendar.getInstance();
yearAgo.add(Calendar.MONTH, -12);
// If the map has not been modified in the last months, it means that I don't need to keep all the history ...
int max = mindmap.getLastModificationTime().before(yearAgo) ? 10 : 25;
final HibernateTemplate hibernateTemplate = getHibernateTemplate();
for (MindMapHistory history : historyList) {
byte[] zippedXml = history.getZippedXml();
if (new String(zippedXml).startsWith("<map")) {
history.setZippedXml(ZipUtils.bytesToZip(zippedXml));
hibernateTemplate.update(history);
}
}
if (historyList.size() > max) {
for (int i = max; i < historyList.size(); i++) {
hibernateTemplate.delete(historyList.get(i));
}
}
}
}
@Override
public List<Mindmap> findMindmapByUser(@NotNull User user) {
final Mindmap collaborator;
final Query query = currentSession()
.createQuery("from com.wisemapping.model.Mindmap m where m.id in (select c.mindMap.id from com.wisemapping.model.Collaboration as c where c.collaborator.id=:collabId )");
query.setParameter("collabId", user.getId());
return query.getResultList();
}
@Override
public List<Mindmap> search(MindMapCriteria criteria, int maxResult) {
final Criteria hibernateCriteria = currentSession().createCriteria(Mindmap.class);
//always search public maps
hibernateCriteria.add(Restrictions.like("public", Boolean.TRUE));
if (criteria != null) {
final Junction junction;
if (criteria.isOrCriteria()) {
junction = Restrictions.disjunction();
} else {
junction = Restrictions.conjunction();
}
if (criteria.getTitle() != null && criteria.getTitle().length() > 0) {
final SimpleExpression titleRestriction = Restrictions.like("title", "%" + criteria.getTitle() + "%");
junction.add(titleRestriction);
}
if (criteria.getDescription() != null && criteria.getDescription().length() > 0) {
final SimpleExpression descriptionRestriction = Restrictions.like("description", "%" + criteria.getDescription() + "%");
junction.add(descriptionRestriction);
}
if (criteria.getTags().size() > 0) {
for (String tag : criteria.getTags()) {
final SimpleExpression tagRestriction = Restrictions.like("tags", "%" + tag + "%");
junction.add(tagRestriction);
}
}
hibernateCriteria.add(junction);
}
return hibernateCriteria.list();
}
@Override
public Collaborator findCollaborator(int id) {
return getHibernateTemplate().get(Collaborator.class, id);
}
@Override
public List<Collaboration> findCollaboration(final int collaboratorId) {
Query query = currentSession().createQuery("from com.wisemapping.model.Collaboration c where c.collaborator.id=:collaboratorId");
query.setParameter("collaboratorId", collaboratorId);
return query.getResultList();
}
@Override
public List<Collaboration> findCollaboration(final CollaborationRole collaborationRole) {
Query query = currentSession().createQuery("from com.wisemapping.model.Collaboration c where c.role=:roleId");
query.setParameter("roleId", collaborationRole.ordinal());
return query.getResultList();
}
@Override
public Collaboration findCollaboration(final int mindmapId, final User user) {
final Collaboration result;
Query query = currentSession().createQuery("from com.wisemapping.model.Collaboration c where c.mindMap.id=:mindmapId and c.id=:collaboratorId");
query.setParameter("mindmapId", mindmapId);
query.setParameter("collaboratorId", user.getId());
final List<Collaboration> mindMaps = query.getResultList();
if (mindMaps != null && !mindMaps.isEmpty()) {
result = mindMaps.get(0);
} else {
result = null;
}
return result;
}
@Override
public void addCollaborator(@NotNull Collaborator collaborator) {
assert collaborator != null : "ADD MINDMAP COLLABORATOR: Collaborator is required!";
getHibernateTemplate().save(collaborator);
}
@Override
public void removeCollaboration(Collaboration collaboration) {
getHibernateTemplate().delete(collaboration);
}
@Override
public void removeCollaborator(@NotNull Collaborator collaborator) {
getHibernateTemplate().delete(collaborator);
}
@Override
@SuppressWarnings("unchecked")
public List<Mindmap> getAllMindmaps() {
return currentSession().createQuery("from com.wisemapping.model.Mindmap wisemapping").list();
}
@Override
@Nullable
public Mindmap getMindmapById(int id) {
return getHibernateTemplate().get(Mindmap.class, id);
}
@Override
public Mindmap getMindmapByTitle(final String title, final User user) {
final Mindmap result;
Query query = currentSession().createQuery("from com.wisemapping.model.Mindmap wisemapping where title=:title and creator=:creator");
query.setParameter("title", title);
query.setParameter("creator", user);
List<Mindmap> mindMaps = query.getResultList();
if (mindMaps != null && !mindMaps.isEmpty()) {
result = mindMaps.get(0);
} else {
result = null;
}
return result;
}
@Override
public void addMindmap(User user, Mindmap mindMap) {
saveMindmap(mindMap);
}
@Override
public void saveMindmap(Mindmap mindMap) {
assert mindMap != null : "Save Mindmap: Mindmap is required!";
currentSession().save(mindMap);
}
@Override
public void updateMindmap(@NotNull Mindmap mindMap, boolean saveHistory) {
assert mindMap != null : "Save Mindmap: Mindmap is required!";
getHibernateTemplate().saveOrUpdate(mindMap);
if (saveHistory) {
saveHistory(mindMap);
}
}
@Override
public void removeMindmap(@NotNull final Mindmap mindMap) {
// Delete history first ...
final Criteria hibernateCriteria = currentSession().createCriteria(MindMapHistory.class);
hibernateCriteria.add(Restrictions.eq("mindmapId", mindMap.getId()));
List list = hibernateCriteria.list();
getHibernateTemplate().deleteAll(list);
// Delete mindmap ....
getHibernateTemplate().delete(mindMap);
}
private void saveHistory(@NotNull final Mindmap mindMap) {
final MindMapHistory history = new MindMapHistory();
history.setZippedXml(mindMap.getZippedXml());
history.setCreationTime(Calendar.getInstance());
history.setEditor(mindMap.getLastEditor());
history.setMindmapId(mindMap.getId());
getHibernateTemplate().saveOrUpdate(history);
}
}

View File

@@ -20,31 +20,31 @@ package com.wisemapping.dao;
import com.wisemapping.model.AccessAuditory;
import com.wisemapping.model.Collaborator;
import com.wisemapping.model.Account;
import com.wisemapping.model.User;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public interface UserManager {
List<Account> getAllUsers();
List<User> getAllUsers();
Account getUserBy(String email);
User getUserBy(String email);
Account getUserBy(int id);
User getUserBy(int id);
void createUser(Account user);
void createUser(User user);
void auditLogin(@NotNull AccessAuditory accessAuditory);
void updateUser(Account user);
void updateUser(User user);
Account getUserByActivationCode(long code);
User getUserByActivationCode(long code);
Collaborator getCollaboratorBy(String email);
Account createUser(Account user, Collaborator col);
User createUser(User user, Collaborator col);
void removeUser(@NotNull Account user);
void removeUser(@NotNull User user);
}

View File

@@ -18,49 +18,47 @@
package com.wisemapping.dao;
import com.wisemapping.model.*;
import com.wisemapping.model.AccessAuditory;
import com.wisemapping.model.Collaboration;
import com.wisemapping.model.Collaborator;
import com.wisemapping.model.User;
import com.wisemapping.security.DefaultPasswordEncoderFactories;
import com.wisemapping.security.LegacyPasswordEncoder;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import org.hibernate.ObjectNotFoundException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
@Repository
public class UserManagerImpl
extends HibernateDaoSupport
implements UserManager {
@Autowired
private EntityManager entityManager;
@Autowired
private PasswordEncoder passwordEncoder;
public UserManagerImpl() {
}
private PasswordEncoder passwordEncoder;
public void setEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
public List<Account> getAllUsers() {
return entityManager.createQuery("from com.wisemapping.model.Account user", Account.class).getResultList();
@SuppressWarnings("unchecked")
public List<User> getAllUsers() {
return currentSession().createQuery("from com.wisemapping.model.User user").list();
}
@Override
@Nullable
public Account getUserBy(@NotNull final String email) {
Account user = null;
TypedQuery<Account> query = entityManager.createQuery("from com.wisemapping.model.Account colaborator where email=:email", Account.class);
@Override
public User getUserBy(@NotNull final String email) {
User user = null;
var query = currentSession().createQuery("from com.wisemapping.model.User colaborator where email=:email");
query.setParameter("email", email);
final List<Account> users = query.getResultList();
final List<User> users = query.list();
if (users != null && !users.isEmpty()) {
assert users.size() == 1 : "More than one user with the same email!";
user = users.get(0);
@@ -71,73 +69,80 @@ public class UserManagerImpl
@Override
public Collaborator getCollaboratorBy(final String email) {
final Collaborator result;
final TypedQuery<Collaborator> query = entityManager.createQuery("from com.wisemapping.model.Collaborator colaborator where " +
"email=:email", Collaborator.class);
final Collaborator cola;
var query = currentSession().createQuery("from com.wisemapping.model.Collaborator colaborator where " +
"email=:email");
query.setParameter("email", email);
final List<Collaborator> cols = query.getResultList();
final List<User> cols = query.list();
if (cols != null && !cols.isEmpty()) {
assert cols.size() == 1 : "More than one colaborator with the same email!";
result = cols.get(0);
cola = cols.get(0);
} else {
result = null;
cola = null;
}
return result;
return cola;
}
@Nullable
@Override
public Account getUserBy(int id) {
return entityManager.find(Account.class, id);
}
@Override
public void createUser(Account user) {
assert user != null : "Trying to store a null user";
if (!AuthenticationType.GOOGLE_OAUTH2.equals(user.getAuthenticationType())) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
} else {
user.setPassword("");
public User getUserBy(int id) {
User user = null;
try {
user = getHibernateTemplate().get(User.class, id);
} catch (ObjectNotFoundException e) {
// Ignore ...
}
entityManager.persist(user);
}
@Override
public Account createUser(@NotNull Account user, @NotNull Collaborator collaborator) {
assert user != null : "Trying to store a null user";
// Migrate from previous temporal collab to new user ...
collaborator.setEmail(collaborator.getEmail() + "_toRemove");
entityManager.merge(collaborator);
entityManager.flush();
// Save all new...
this.createUser(user);
// Update mindmap ...
final Set<Collaboration> collaborations = new CopyOnWriteArraySet<>(collaborator.getCollaborations());
for (Collaboration collabs : collaborations) {
collabs.setCollaborator(user);
}
// Delete old user ...
entityManager.remove(collaborator);
return user;
}
@Override
public void removeUser(@NotNull final Account user) {
entityManager.remove(user);
public void createUser(User user) {
assert user != null : "Trying to store a null user";
user.setPassword(passwordEncoder.encode(user.getPassword()));
getHibernateTemplate().saveOrUpdate(user);
}
@Override
public User createUser(@NotNull User user, @NotNull Collaborator collaborator) {
assert user != null : "Trying to store a null user";
// Migrate from previous temporal collab to new user ...
List<Collaboration> newCollabs = new ArrayList<>();
final Set<Collaboration> collaborations = collaborator.getCollaborations();
for (Collaboration oldCollab : collaborations) {
Collaboration newCollab = new Collaboration();
newCollab.setRoleId(oldCollab.getRole().ordinal());
newCollab.setMindMap(oldCollab.getMindMap());
newCollab.setCollaborator(user);
user.addCollaboration(newCollab);
newCollabs.add(newCollab);
}
// Delete old collaboration
final HibernateTemplate template = getHibernateTemplate();
collaborations.forEach(c -> template.delete(c));
template.delete(collaborator);
template.flush();
// Save all new...
this.createUser(user);
newCollabs.forEach(c -> template.saveOrUpdate(c));
return user;
}
@Override
public void removeUser(@NotNull final User user) {
getHibernateTemplate().delete(user);
}
public void auditLogin(@NotNull AccessAuditory accessAuditory) {
assert accessAuditory != null : "accessAuditory is null";
entityManager.persist(accessAuditory);
getHibernateTemplate().save(accessAuditory);
}
public void updateUser(@NotNull Account user) {
public void updateUser(@NotNull User user) {
assert user != null : "user is null";
// Does the password need to be encrypted ?
@@ -146,21 +151,21 @@ public class UserManagerImpl
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
entityManager.merge(user);
getHibernateTemplate().update(user);
}
public Account getUserByActivationCode(long code) {
final Account user;
public User getUserByActivationCode(long code) {
final User user;
final TypedQuery<Account> query = entityManager.createQuery("from com.wisemapping.model.User user where " +
"activationCode=:activationCode", Account.class);
var query = currentSession().createQuery("from com.wisemapping.model.User user where " +
"activationCode=:activationCode");
query.setParameter("activationCode", code);
final List users = query.list();
final List<Account> users = query.getResultList();
if (users != null && !users.isEmpty()) {
assert users.size() == 1 : "More than one user with the same username!";
user = users.get(0);
user = (User) users.get(0);
} else {
user = null;
}

View File

@@ -19,6 +19,7 @@
package com.wisemapping.exceptions;
import com.wisemapping.model.Collaborator;
import com.wisemapping.model.User;
import org.jetbrains.annotations.NotNull;
public class AccessDeniedSecurityException
@@ -30,7 +31,7 @@ public class AccessDeniedSecurityException
}
public AccessDeniedSecurityException(@NotNull long mapId, Collaborator user) {
super("You do not have enough right access to see this map. This map has been changed to private or deleted.", Severity.FATAL);
super("No enough permissions to access map. Id: " + mapId + ", User: " + user, Severity.FATAL);
}
@NotNull

Some files were not shown because too many files have changed in this diff Show More