init
This commit is contained in:
Executable
+11
@@ -0,0 +1,11 @@
|
||||
bin/
|
||||
target/
|
||||
.settings/
|
||||
.project
|
||||
.classpath
|
||||
hs_err*.log
|
||||
application.properties
|
||||
usernames.txt
|
||||
lucene
|
||||
|
||||
.vscode
|
||||
@@ -0,0 +1,135 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>de.champonthis</groupId>
|
||||
<artifactId>buntspecht</artifactId>
|
||||
<version>${revision}</version>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>17</java.version>
|
||||
<querydsl.version>5.1.0</querydsl.version>
|
||||
<revision>0.1.0</revision>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.3.4</version>
|
||||
<relativePath />
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</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-webflux</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-mail</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.session</groupId>
|
||||
<artifactId>spring-session-jdbc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-client</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Query DSL -->
|
||||
<dependency>
|
||||
<groupId>com.querydsl</groupId>
|
||||
<artifactId>querydsl-apt</artifactId>
|
||||
<version>${querydsl.version}</version>
|
||||
<classifier>jakarta</classifier>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.querydsl</groupId>
|
||||
<artifactId>querydsl-jpa</artifactId>
|
||||
<version>${querydsl.version}</version>
|
||||
<classifier>jakarta</classifier>
|
||||
</dependency>
|
||||
|
||||
<!-- Utils -->
|
||||
<dependency>
|
||||
<groupId>commons-validator</groupId>
|
||||
<artifactId>commons-validator</artifactId>
|
||||
<version>1.9.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.78.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.passay</groupId>
|
||||
<artifactId>passay</artifactId>
|
||||
<version>1.6.5</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Datbase -->
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>de.champonthis.buntspecht.Application</mainClass>
|
||||
<finalName>buntspecht</finalName>
|
||||
<executable>true</executable>
|
||||
<layout>ZIP</layout>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>build-info</id>
|
||||
<goals>
|
||||
<goal>build-info</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package de.champonthis.buntspecht;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application extends SpringBootServletInitializer {
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package de.champonthis.buntspecht;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
|
||||
@Configuration
|
||||
@EnableJpaAuditing
|
||||
public class JPAConfig {
|
||||
|
||||
@Autowired
|
||||
private EntityManager em;
|
||||
|
||||
@Bean
|
||||
public JPAQueryFactory jpaQueryFactory() {
|
||||
return new JPAQueryFactory(em);
|
||||
}
|
||||
|
||||
}
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
package de.champonthis.buntspecht.businesslogic;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import de.champonthis.buntspecht.model.SystemProperty;
|
||||
import de.champonthis.buntspecht.repository.SystemPropertyRepository;
|
||||
|
||||
@Component
|
||||
public class SystemPropertyManager {
|
||||
|
||||
@Autowired
|
||||
private SystemPropertyRepository systemPropertyRepository;
|
||||
|
||||
public boolean has(String key) {
|
||||
return systemPropertyRepository.existsById(key);
|
||||
}
|
||||
|
||||
public String get(String key) {
|
||||
return systemPropertyRepository.findById(key).orElse(new SystemProperty()).getValue();
|
||||
}
|
||||
|
||||
public String get(String key, String defaultValue) {
|
||||
return systemPropertyRepository.findById(key).orElse(new SystemProperty(key, defaultValue)).getValue();
|
||||
}
|
||||
|
||||
public boolean getBoolean(String key) {
|
||||
return getBoolean(key, false);
|
||||
}
|
||||
|
||||
public boolean getBoolean(String key, boolean defaultValue) {
|
||||
return Boolean.valueOf(get(key, String.valueOf(defaultValue)));
|
||||
}
|
||||
|
||||
public int getInteger(String key) {
|
||||
return getInteger(key, 0);
|
||||
}
|
||||
|
||||
public int getInteger(String key, int defaultValue) {
|
||||
return Integer.valueOf(get(key, String.valueOf(defaultValue)));
|
||||
}
|
||||
|
||||
public long getLong(String key) {
|
||||
return getLong(key, 0L);
|
||||
}
|
||||
|
||||
public long getLong(String key, long defaultValue) {
|
||||
return Long.valueOf(get(key, String.valueOf(defaultValue)));
|
||||
}
|
||||
|
||||
public void add(String key, String value) {
|
||||
Assert.isTrue(!systemPropertyRepository.existsById(key),
|
||||
"System Property already exists, use update method to change value!");
|
||||
systemPropertyRepository.save(new SystemProperty(key, value));
|
||||
}
|
||||
|
||||
public void update(String key, String value) {
|
||||
Assert.isTrue(systemPropertyRepository.existsById(key),
|
||||
"System Property does not exists, use add method to add new!");
|
||||
SystemProperty systemProperty = systemPropertyRepository.findById(key).get();
|
||||
systemProperty.setValue(value);
|
||||
systemPropertyRepository.save(systemProperty);
|
||||
}
|
||||
|
||||
public void set(String key, String value) {
|
||||
if (systemPropertyRepository.existsById(key)) {
|
||||
update(key, value);
|
||||
} else {
|
||||
add(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package de.champonthis.buntspecht.businesslogic;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.querydsl.core.BooleanBuilder;
|
||||
import com.querydsl.core.QueryResults;
|
||||
import com.querydsl.core.Tuple;
|
||||
import com.querydsl.core.types.Order;
|
||||
import com.querydsl.core.types.OrderSpecifier;
|
||||
import com.querydsl.core.types.Path;
|
||||
import com.querydsl.core.types.Predicate;
|
||||
import com.querydsl.jpa.impl.JPAQuery;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
|
||||
import de.champonthis.buntspecht.controller.model.TurnoverFilterModel;
|
||||
import de.champonthis.buntspecht.model.QTurnover;
|
||||
import de.champonthis.buntspecht.model.Turnover;
|
||||
import de.champonthis.buntspecht.repository.TurnoverRepository;
|
||||
|
||||
@Service
|
||||
public class TurnoverManager {
|
||||
|
||||
@Autowired
|
||||
private TurnoverRepository turnoverRepository;
|
||||
@Autowired
|
||||
private JPAQueryFactory jpaQueryFactory;
|
||||
|
||||
private QTurnover qTurnover = QTurnover.turnover;
|
||||
|
||||
public QueryResults<Turnover> fetch(long limit, long offset, String sortBy, boolean descending,
|
||||
TurnoverFilterModel filter) {
|
||||
return fetch(null, limit, offset, sortBy, descending, filter);
|
||||
}
|
||||
|
||||
public QueryResults<Turnover> fetch(String username, long limit, long offset, String sortBy, boolean descending,
|
||||
TurnoverFilterModel filter) {
|
||||
BooleanBuilder builder = new BooleanBuilder();
|
||||
|
||||
if (StringUtils.hasText(username)) {
|
||||
builder.and(qTurnover.username.eq(username));
|
||||
}
|
||||
|
||||
builder.and(buildFilter(filter));
|
||||
|
||||
JPAQuery<Turnover> query = jpaQueryFactory.from(qTurnover).where(builder.getValue()).select(qTurnover);
|
||||
Long total = query.clone().select(qTurnover.id.countDistinct()).fetchOne();
|
||||
|
||||
if (StringUtils.hasText(sortBy)) {
|
||||
Path<? extends Comparable<?>> path = null;
|
||||
switch (sortBy) {
|
||||
case "created":
|
||||
path = qTurnover.created;
|
||||
break;
|
||||
case "updated":
|
||||
path = qTurnover.updated;
|
||||
break;
|
||||
case "customer":
|
||||
path = qTurnover.customer;
|
||||
break;
|
||||
case "price":
|
||||
path = qTurnover.price;
|
||||
break;
|
||||
case "timeInvestment":
|
||||
path = qTurnover.timeInvestment;
|
||||
break;
|
||||
}
|
||||
if (path != null) {
|
||||
query.orderBy(new OrderSpecifier<>(descending ? Order.DESC : Order.ASC, path));
|
||||
}
|
||||
}
|
||||
|
||||
List<Turnover> result = query.limit(limit).offset(offset).fetch();
|
||||
return new QueryResults<Turnover>(result, limit, offset, total == null ? 0L : total);
|
||||
|
||||
}
|
||||
|
||||
protected Predicate buildFilter(TurnoverFilterModel filter) {
|
||||
BooleanBuilder builder = new BooleanBuilder();
|
||||
|
||||
if (filter != null) {
|
||||
if (filter.getCreated() != null) {
|
||||
if (filter.getCreated().getMin() != null) {
|
||||
builder.and(qTurnover.created.after(filter.getCreated().getMin()));
|
||||
}
|
||||
if (filter.getCreated().getMax() != null) {
|
||||
builder.and(qTurnover.created.before(filter.getCreated().getMax()));
|
||||
}
|
||||
}
|
||||
if (filter.getUpdated() != null) {
|
||||
if (filter.getUpdated().getMin() != null) {
|
||||
builder.and(qTurnover.updated.after(filter.getUpdated().getMin()));
|
||||
}
|
||||
if (filter.getUpdated().getMax() != null) {
|
||||
builder.and(qTurnover.updated.before(filter.getUpdated().getMax()));
|
||||
}
|
||||
}
|
||||
if (filter.getCustomer() != null) {
|
||||
builder.and(qTurnover.customer.contains(filter.getCustomer()));
|
||||
}
|
||||
if (filter.getMotif() != null) {
|
||||
builder.and(qTurnover.motif.contains(filter.getMotif()));
|
||||
}
|
||||
if (filter.getPrice() != null) {
|
||||
if (filter.getPrice().getMin() != null) {
|
||||
builder.and(qTurnover.price.goe(filter.getPrice().getMin()));
|
||||
}
|
||||
if (filter.getPrice().getMax() != null) {
|
||||
builder.and(qTurnover.price.loe(filter.getPrice().getMax()));
|
||||
}
|
||||
}
|
||||
if (filter.getTimeInvestment() != null) {
|
||||
if (filter.getTimeInvestment().getMin() != null) {
|
||||
builder.and(qTurnover.timeInvestment.goe(filter.getTimeInvestment().getMin()));
|
||||
}
|
||||
if (filter.getTimeInvestment().getMax() != null) {
|
||||
builder.and(qTurnover.timeInvestment.loe(filter.getTimeInvestment().getMax()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return builder.getValue();
|
||||
}
|
||||
|
||||
public Turnover get(Long id) {
|
||||
return turnoverRepository.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
public Turnover save(Turnover turnover) {
|
||||
return turnoverRepository.save(turnover);
|
||||
}
|
||||
|
||||
public boolean exists(Long id) {
|
||||
return turnoverRepository.existsById(id);
|
||||
}
|
||||
|
||||
public void delete(Turnover turnover) {
|
||||
turnoverRepository.delete(turnover);
|
||||
}
|
||||
|
||||
public void deleteById(Long id) {
|
||||
turnoverRepository.deleteById(id);
|
||||
}
|
||||
|
||||
public void deleteByUsername(String username) {
|
||||
turnoverRepository.deleteAllInBatch(turnoverRepository.findAll(qTurnover.username.eq(username)));
|
||||
}
|
||||
|
||||
public QueryResults<Tuple> overview(String username, long limit, long offset, String sortBy, boolean descending,
|
||||
TurnoverFilterModel filter) {
|
||||
BooleanBuilder builder = new BooleanBuilder();
|
||||
|
||||
if (StringUtils.hasText(username)) {
|
||||
builder.and(qTurnover.username.eq(username));
|
||||
}
|
||||
|
||||
builder.and(buildFilter(filter));
|
||||
|
||||
JPAQuery<Tuple> query = jpaQueryFactory.from(qTurnover).where(builder.getValue()).groupBy(qTurnover.username)
|
||||
.select(qTurnover.username.as("username"), qTurnover.price.sum().as("price"),
|
||||
qTurnover.timeInvestment.sum().as("timeInvestment"));
|
||||
Long total = query.clone().select(qTurnover.username.countDistinct()).fetchOne();
|
||||
|
||||
if (StringUtils.hasText(sortBy)) {
|
||||
Path<? extends Comparable<?>> path = null;
|
||||
switch (sortBy) {
|
||||
case "username":
|
||||
path = qTurnover.username;
|
||||
break;
|
||||
case "price":
|
||||
path = qTurnover.price;
|
||||
break;
|
||||
case "timeInvestment":
|
||||
path = qTurnover.timeInvestment;
|
||||
break;
|
||||
}
|
||||
if (path != null) {
|
||||
query.orderBy(new OrderSpecifier<>(descending ? Order.DESC : Order.ASC, path));
|
||||
}
|
||||
}
|
||||
|
||||
List<Tuple> result = query.limit(limit).offset(offset)
|
||||
.fetch();
|
||||
|
||||
return new QueryResults<Tuple>(result, limit, offset, total == null ? 0L : total);
|
||||
}
|
||||
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
package de.champonthis.buntspecht.businesslogic;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.querydsl.core.BooleanBuilder;
|
||||
import com.querydsl.core.QueryResults;
|
||||
import com.querydsl.core.types.Order;
|
||||
import com.querydsl.core.types.OrderSpecifier;
|
||||
import com.querydsl.core.types.Path;
|
||||
import com.querydsl.jpa.impl.JPAQuery;
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory;
|
||||
|
||||
import de.champonthis.buntspecht.model.QUser;
|
||||
import de.champonthis.buntspecht.model.User;
|
||||
import de.champonthis.buntspecht.repository.UserRepository;
|
||||
import de.champonthis.buntspecht.security.LocalUserDetails;
|
||||
import jakarta.transaction.Transactional;
|
||||
|
||||
@Service
|
||||
public class UserManager implements UserDetailsService, SmartInitializingSingleton {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(UserManager.class);
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
@Autowired
|
||||
private JPAQueryFactory jpaQueryFactory;
|
||||
@Autowired
|
||||
private TurnoverManager turnoverManager;
|
||||
private QUser qUser = QUser.user;
|
||||
|
||||
@Value("${admin.password:}")
|
||||
private String adminPassword;
|
||||
|
||||
public QueryResults<User> fetch(long limit, long offset, String sortBy, boolean descending, String usernameFilter) {
|
||||
BooleanBuilder builder = new BooleanBuilder();
|
||||
|
||||
if (StringUtils.hasText(usernameFilter)) {
|
||||
builder.and(qUser.username.contains(usernameFilter));
|
||||
}
|
||||
|
||||
JPAQuery<User> query = jpaQueryFactory.from(qUser).where(builder.getValue()).select(qUser);
|
||||
Long total = query.clone().select(qUser.username.countDistinct()).fetchOne();
|
||||
|
||||
if (StringUtils.hasText(sortBy)) {
|
||||
Path<? extends Comparable<?>> path = null;
|
||||
switch (sortBy) {
|
||||
case "username":
|
||||
path = qUser.username;
|
||||
break;
|
||||
case "name":
|
||||
path = qUser.name;
|
||||
break;
|
||||
}
|
||||
if (path != null) {
|
||||
query.orderBy(new OrderSpecifier<>(descending ? Order.DESC : Order.ASC, path));
|
||||
}
|
||||
}
|
||||
|
||||
List<User> result = query.limit(limit).offset(offset).fetch();
|
||||
return new QueryResults<User>(result, limit, offset, total == null ? 0L : total);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
User user = getByUsername(username);
|
||||
|
||||
if (user == null) {
|
||||
throw new UsernameNotFoundException(username);
|
||||
}
|
||||
|
||||
List<GrantedAuthority> authorities = new ArrayList<>();
|
||||
if (user.getRoles() != null) {
|
||||
for (String role : user.getRoles()) {
|
||||
authorities.add(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
}
|
||||
|
||||
String passwordHash = user.getPasswordHash();
|
||||
|
||||
if (passwordHash == null) {
|
||||
passwordHash = "";
|
||||
}
|
||||
|
||||
LocalUserDetails userDetails = new LocalUserDetails(username, passwordHash, authorities);
|
||||
return userDetails;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
if (!userRepository.exists(qUser.roles.contains("ROLE_ADMIN"))) {
|
||||
if (!StringUtils.hasText(adminPassword)) {
|
||||
adminPassword = RandomStringUtils.random(24, true, true);
|
||||
logger.error("password for 'admin': " + adminPassword);
|
||||
}
|
||||
User admin = new User();
|
||||
admin.setUsername("admin");
|
||||
admin.setRoles(List.of("ROLE_ADMIN", "ROLE_DEBUG"));
|
||||
admin.setPasswordHash(passwordEncoder.encode(adminPassword));
|
||||
admin.setLocale("de");
|
||||
userRepository.save(admin);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User getByUsername(String username) {
|
||||
return userRepository.findOne(qUser.username.equalsIgnoreCase(username)).orElse(null);
|
||||
}
|
||||
|
||||
public User getByExternalId(String externalId) {
|
||||
return userRepository.findOne(qUser.externalId.eq(externalId)).orElse(null);
|
||||
}
|
||||
|
||||
public User getByAuth(Authentication authentication) {
|
||||
if (authentication != null) {
|
||||
if (authentication instanceof UsernamePasswordAuthenticationToken) {
|
||||
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
|
||||
return getByUsername(token.getName());
|
||||
} else if (authentication instanceof OAuth2AuthenticationToken) {
|
||||
OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;
|
||||
String externalId = token.getAuthorizedClientRegistrationId() + "-" +
|
||||
token.getName();
|
||||
User user = getByExternalId(externalId);
|
||||
if (user == null) {
|
||||
user = new User();
|
||||
user.setExternalId(externalId);
|
||||
String tmpUsername = token.getPrincipal().getAttribute("preferred_username");
|
||||
if (!StringUtils.hasText(tmpUsername)) {
|
||||
tmpUsername = token.getPrincipal().getAttribute("username");
|
||||
}
|
||||
if (!StringUtils.hasText(tmpUsername)) {
|
||||
tmpUsername = token.getPrincipal().getAttribute("name");
|
||||
} else {
|
||||
user.setName(token.getPrincipal().getAttribute("name"));
|
||||
}
|
||||
if (!StringUtils.hasText(tmpUsername)) {
|
||||
tmpUsername = token.getName();
|
||||
}
|
||||
if (!StringUtils.hasText(tmpUsername)) {
|
||||
tmpUsername = "user";
|
||||
}
|
||||
int count = 1;
|
||||
String username = tmpUsername;
|
||||
while (userRepository.exists(qUser.username.equalsIgnoreCase(username))) {
|
||||
username = tmpUsername + "-" + count;
|
||||
count++;
|
||||
}
|
||||
|
||||
user.setUsername(username);
|
||||
user.setEmail(token.getPrincipal().getAttribute("email"));
|
||||
user = userRepository.save(user);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public User save(User user) {
|
||||
if (exists(user.getUsername())) {
|
||||
user.setPasswordHash(this.getPasswordHash(user.getUsername()));
|
||||
}
|
||||
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
public boolean exists(String username) {
|
||||
return userRepository.exists(qUser.username.equalsIgnoreCase(username));
|
||||
}
|
||||
|
||||
public void delete(User user) {
|
||||
turnoverManager.deleteByUsername(user.getUsername());
|
||||
userRepository.delete(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public String getPasswordHash(String username) {
|
||||
Assert.isTrue(userRepository.existsById(username), "User with username '" + username + "' not exists!");
|
||||
return userRepository.findById(username).get().getPasswordHash();
|
||||
}
|
||||
|
||||
public User setPassword(String username, String password) {
|
||||
Assert.isTrue(userRepository.existsById(username), "User with username '" + username + "' not exists!");
|
||||
User user = userRepository.findById(username).get();
|
||||
user.setPasswordHash(passwordEncoder.encode(password));
|
||||
return userRepository.save(user);
|
||||
}
|
||||
}
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
package de.champonthis.buntspecht.controller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import de.champonthis.buntspecht.controller.support.EntityResponseStatusException;
|
||||
import de.champonthis.buntspecht.security.LocalUserDetails;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
public class AuthenticationController extends BaseController {
|
||||
|
||||
private static String authorizationRequestBaseUri = "oauth2/authorization";
|
||||
|
||||
@Autowired(required = false)
|
||||
private ClientRegistrationRepository clientRegistrationRepository;
|
||||
|
||||
@GetMapping
|
||||
public Object me() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (auth != null && auth.getPrincipal() instanceof LocalUserDetails) {
|
||||
return (LocalUserDetails) auth.getPrincipal();
|
||||
}
|
||||
|
||||
throw new EntityResponseStatusException(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@GetMapping("external")
|
||||
public List<Client> getExternalLoginUrls() {
|
||||
List<Client> clients = new ArrayList<>();
|
||||
if (clientRegistrationRepository != null) {
|
||||
Iterable<ClientRegistration> clientRegistrations = null;
|
||||
ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class);
|
||||
if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
|
||||
clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository;
|
||||
clientRegistrations.forEach(registration -> clients.add(new Client(registration.getRegistrationId(),
|
||||
authorizationRequestBaseUri + "/" + registration.getRegistrationId())));
|
||||
}
|
||||
}
|
||||
|
||||
return clients;
|
||||
}
|
||||
|
||||
protected static class Client {
|
||||
|
||||
private String id;
|
||||
|
||||
private String loginUrl;
|
||||
|
||||
public Client(String id, String loginUrl) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.loginUrl = loginUrl;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getLoginUrl() {
|
||||
return loginUrl;
|
||||
}
|
||||
|
||||
public void setLoginUrl(String loginUrl) {
|
||||
this.loginUrl = loginUrl;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package de.champonthis.buntspecht.controller;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
import de.champonthis.buntspecht.security.LocalUserDetails;
|
||||
|
||||
public class BaseController {
|
||||
|
||||
protected boolean authenticated() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
return auth != null && auth.isAuthenticated();
|
||||
}
|
||||
|
||||
protected String getCurrentUsername() {
|
||||
LocalUserDetails userDetails = getLocalUserDetails();
|
||||
return userDetails != null ? userDetails.getUsername() : null;
|
||||
}
|
||||
|
||||
protected boolean hasRole(String role) {
|
||||
LocalUserDetails userDetails = getLocalUserDetails();
|
||||
return userDetails != null ? userDetails.getAuthorities().contains(new SimpleGrantedAuthority(role)) : false;
|
||||
}
|
||||
|
||||
protected LocalUserDetails getLocalUserDetails() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
return (auth != null && auth.getPrincipal() instanceof LocalUserDetails)
|
||||
? (LocalUserDetails) auth.getPrincipal()
|
||||
: null;
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package de.champonthis.buntspecht.controller;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.web.PagedModel;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.querydsl.core.QueryResults;
|
||||
|
||||
import de.champonthis.buntspecht.businesslogic.TurnoverManager;
|
||||
import de.champonthis.buntspecht.businesslogic.UserManager;
|
||||
import de.champonthis.buntspecht.controller.model.TurnoverFilterModel;
|
||||
import de.champonthis.buntspecht.controller.model.TurnoverFilterModel.MinMax;
|
||||
import de.champonthis.buntspecht.controller.support.EntityResponseStatusException;
|
||||
import de.champonthis.buntspecht.controller.support.RequestBodyErrors;
|
||||
import de.champonthis.buntspecht.controller.validation.TurnoverValidator;
|
||||
import de.champonthis.buntspecht.model.Turnover;
|
||||
import jakarta.transaction.Transactional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/turnovers")
|
||||
public class TurnoverController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private TurnoverManager turnoverManager;
|
||||
@Autowired
|
||||
private UserManager userManager;
|
||||
@Autowired
|
||||
private TurnoverValidator turnoverValidator;
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@GetMapping
|
||||
@Transactional
|
||||
public QueryResults<Turnover> fetch(
|
||||
@RequestParam("limit") Optional<Long> limitParameter,
|
||||
@RequestParam("offset") Optional<Long> offsetParameter,
|
||||
@RequestParam("sort") Optional<String> sort,
|
||||
@RequestParam("descending") Optional<Boolean> descending,
|
||||
@RequestParam("from") Optional<Instant> from,
|
||||
@RequestParam("to") Optional<Instant> to,
|
||||
@RequestParam("customer") Optional<String> customer,
|
||||
@RequestParam("motif") Optional<String> motif) {
|
||||
|
||||
TurnoverFilterModel filter = new TurnoverFilterModel();
|
||||
filter.setCreated(new MinMax<Instant>(from.orElse(null), to.orElse(null)));
|
||||
filter.setCustomer(customer.orElse(null));
|
||||
filter.setMotif(motif.orElse(null));
|
||||
|
||||
return turnoverManager.fetch(getCurrentUsername(), limitParameter.orElse(15L), offsetParameter.orElse(0L),
|
||||
sort.orElse("created"), descending.orElse(false), filter);
|
||||
}
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@GetMapping("/{id}")
|
||||
@Transactional
|
||||
public Turnover get(@PathVariable("id") Long id) {
|
||||
Turnover turnover = turnoverManager.get(id);
|
||||
|
||||
if (turnover == null || !getCurrentUsername().equals(turnover.getUsername())) {
|
||||
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
return turnover;
|
||||
}
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@PostMapping
|
||||
@Transactional
|
||||
public Turnover create(@RequestBody Turnover turnover) {
|
||||
Errors errors = new RequestBodyErrors(turnover);
|
||||
turnoverValidator.validate(turnover, errors);
|
||||
|
||||
if (errors.hasErrors()) {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
if (!hasRole("ROLE_ADMIN") || !StringUtils.hasText(turnover.getUsername())
|
||||
|| !userManager.exists(turnover.getUsername())) {
|
||||
turnover.setUsername(getCurrentUsername());
|
||||
}
|
||||
turnover.setCreated(Instant.now());
|
||||
turnover.setUpdated(turnover.getCreated());
|
||||
|
||||
return turnoverManager.save(turnover);
|
||||
}
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@PatchMapping
|
||||
@Transactional
|
||||
public Turnover update(@RequestBody Turnover turnover) {
|
||||
Errors errors = new RequestBodyErrors(turnover);
|
||||
turnoverValidator.validate(turnover, errors);
|
||||
|
||||
if (errors.hasErrors() || turnover.getId() == null || turnover.getId() == 0L
|
||||
|| !turnoverManager.exists(turnover.getId())) {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
if (!hasRole("ROLE_ADMIN")) {
|
||||
Turnover existing = turnoverManager.get(turnover.getId());
|
||||
if (!getCurrentUsername().equals(existing.getUsername())) {
|
||||
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
turnover.setUsername(getCurrentUsername());
|
||||
}
|
||||
|
||||
Turnover existing = turnoverManager.get(turnover.getId());
|
||||
|
||||
if (existing.equals(turnover)) {
|
||||
throw new EntityResponseStatusException(HttpStatus.NOT_MODIFIED);
|
||||
}
|
||||
|
||||
turnover.setUpdated(Instant.now());
|
||||
|
||||
return turnoverManager.save(turnover);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@DeleteMapping("/{id}")
|
||||
public void deleteById(@PathVariable("id") Long id) {
|
||||
if (!turnoverManager.exists(id)) {
|
||||
throw new EntityResponseStatusException(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
turnoverManager.deleteById(id);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package de.champonthis.buntspecht.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import de.champonthis.buntspecht.businesslogic.UserManager;
|
||||
import de.champonthis.buntspecht.controller.model.UserPasswordModel;
|
||||
import de.champonthis.buntspecht.controller.support.EntityResponseStatusException;
|
||||
import de.champonthis.buntspecht.controller.support.RequestBodyErrors;
|
||||
import de.champonthis.buntspecht.controller.validation.PasswordModelValidator;
|
||||
import de.champonthis.buntspecht.model.User;
|
||||
import jakarta.transaction.Transactional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/users")
|
||||
public class UserController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private UserManager userManager;
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
@Autowired
|
||||
private PasswordModelValidator passwordModelValidator;
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@GetMapping("/user")
|
||||
@Transactional
|
||||
public User get() {
|
||||
return userManager.getByUsername(getCurrentUsername());
|
||||
}
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@PatchMapping("/user")
|
||||
@Transactional
|
||||
public User updateUser(@RequestBody User user) {
|
||||
if (!getCurrentUsername().equals(user.getUsername())) {
|
||||
throw new EntityResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
|
||||
User orgUser = userManager.getByUsername(user.getUsername());
|
||||
|
||||
orgUser.setName(user.getName());
|
||||
orgUser.setAbout(user.getAbout());
|
||||
orgUser.setDarkTheme(user.isDarkTheme());
|
||||
orgUser.setEmail(user.getEmail());
|
||||
orgUser.setLocale(user.getLocale());
|
||||
|
||||
user = userManager.save(orgUser);
|
||||
return user;
|
||||
}
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@PostMapping("/password")
|
||||
public void changePassword(@RequestBody UserPasswordModel passwordModel) {
|
||||
|
||||
Errors errors = new RequestBodyErrors(passwordModel);
|
||||
|
||||
User user = userManager.getByUsername(getCurrentUsername());
|
||||
|
||||
if (!StringUtils.hasText(passwordModel.getOld())
|
||||
|| !passwordEncoder.matches(passwordModel.getOld(), userManager.getPasswordHash(user.getUsername()))) {
|
||||
errors.rejectValue("old", "UNAUTHORIZED");
|
||||
}
|
||||
|
||||
passwordModelValidator.validate(passwordModel, errors);
|
||||
|
||||
if (errors.hasErrors()) {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
userManager.setPassword(user.getUsername(), passwordModel.getPassword());
|
||||
}
|
||||
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package de.champonthis.buntspecht.controller.admin;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.SplittableRandom;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import de.champonthis.buntspecht.model.QUser;
|
||||
import de.champonthis.buntspecht.model.Turnover;
|
||||
import de.champonthis.buntspecht.model.User;
|
||||
import de.champonthis.buntspecht.repository.TurnoverRepository;
|
||||
import de.champonthis.buntspecht.repository.UserRepository;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/debug")
|
||||
public class DebugController {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(DebugController.class);
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
@Autowired
|
||||
private TurnoverRepository turnoverRepository;
|
||||
|
||||
SplittableRandom splittableRandom = new SplittableRandom();
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_DEBUG')")
|
||||
@GetMapping("/random")
|
||||
public void random(
|
||||
@RequestParam("users") Optional<Integer> usersParameter,
|
||||
@RequestParam("minEntries") Optional<Integer> minEntriesParameter,
|
||||
@RequestParam("maxEntries") Optional<Integer> maxEntriesParameter,
|
||||
@RequestParam("days") Optional<Integer> daysParameter) {
|
||||
logger.warn("start random generation");
|
||||
|
||||
long userCount = userRepository.count(QUser.user.username.startsWith("Tätowier"));
|
||||
|
||||
List<String> newUser = new ArrayList<>();
|
||||
|
||||
for (long i = userCount + 1; i <= userCount + usersParameter.orElse(5); i++) {
|
||||
User user = new User();
|
||||
String username = (splittableRandom.nextBoolean() ? "Tätowiererin " : "Tätowierer ") + i;
|
||||
String name = "Random " + RandomStringUtils.randomAlphanumeric(splittableRandom.nextInt(4, 8));
|
||||
user.setUsername(username);
|
||||
user.setName(name);
|
||||
user.setPasswordHash(passwordEncoder.encode(username));
|
||||
user = userRepository.save(user);
|
||||
logger.trace("Created user: '" + username + "'");
|
||||
newUser.add(user.getUsername());
|
||||
}
|
||||
|
||||
logger.info("Created " + usersParameter.orElse(5) + " users");
|
||||
|
||||
Instant startInclusive = Instant.now().minus(daysParameter.orElse(350), ChronoUnit.DAYS);
|
||||
Instant endExclusive = Instant.now();
|
||||
|
||||
for (String username : newUser) {
|
||||
long numEntries = splittableRandom.nextLong(minEntriesParameter.orElse(3), maxEntriesParameter.orElse(20));
|
||||
for (int i = 0; i < numEntries; i++) {
|
||||
Turnover turnover = new Turnover();
|
||||
turnover.setUsername(username);
|
||||
turnover.setCreated(randomDate(startInclusive, endExclusive));
|
||||
turnover.setUpdated(splittableRandom.nextBoolean() ? turnover.getCreated()
|
||||
: randomDate(turnover.getCreated(), endExclusive));
|
||||
turnover.setCustomer(RandomStringUtils.randomAlphabetic(splittableRandom.nextInt(3, 10)));
|
||||
|
||||
turnover.setMotif(RandomStringUtils.randomAlphabetic(splittableRandom.nextInt(5, 30)));
|
||||
|
||||
turnover.setPrice(Float.valueOf(String.format("%.2f", splittableRandom.nextFloat(0.01f, 2000f))));
|
||||
|
||||
if (splittableRandom.nextBoolean()) {
|
||||
turnover.setTimeInvestment(
|
||||
Float.valueOf(String.format("%.2f", splittableRandom.nextFloat(0.01f, 20f))));
|
||||
}
|
||||
|
||||
if (splittableRandom.nextBoolean()) {
|
||||
turnover.setRemark(RandomStringUtils.randomAlphabetic(splittableRandom.nextInt(10, 50)));
|
||||
}
|
||||
|
||||
if (splittableRandom.nextInt(5) < 3) {
|
||||
turnover.setMaterialConsumption(
|
||||
RandomStringUtils.randomAlphabetic(splittableRandom.nextInt(10, 250)));
|
||||
}
|
||||
|
||||
turnover = turnoverRepository.save(turnover);
|
||||
logger.trace("Created turnover: '" + turnover.getId() + "'");
|
||||
}
|
||||
logger.info("Created " + numEntries + " turnovers of '" + username + "'");
|
||||
}
|
||||
|
||||
logger.warn("finished random generation");
|
||||
}
|
||||
|
||||
protected Instant randomDate(Instant startInclusive, Instant endExclusive) {
|
||||
long startSeconds = startInclusive.getEpochSecond();
|
||||
long endSeconds = endExclusive.getEpochSecond();
|
||||
long random = splittableRandom.nextLong(startSeconds, endSeconds);
|
||||
|
||||
return Instant.ofEpochSecond(random);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package de.champonthis.buntspecht.controller.admin;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import de.champonthis.buntspecht.controller.BaseController;
|
||||
import de.champonthis.buntspecht.controller.support.EntityResponseStatusException;
|
||||
import de.champonthis.buntspecht.model.SystemProperty;
|
||||
import de.champonthis.buntspecht.repository.SystemPropertyRepository;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/system/properties")
|
||||
public class SystemPropertiesController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private SystemPropertyRepository systemPropertyRepository;
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping()
|
||||
public List<SystemProperty> getProperties(@RequestParam("page") Optional<Integer> pageParameter,
|
||||
@RequestParam("size") Optional<Integer> sizeParameter) {
|
||||
Sort sort = Sort.by("key").ascending();
|
||||
return systemPropertyRepository.findAll(PageRequest.of(pageParameter.orElse(0), sizeParameter.orElse(10), sort))
|
||||
.getContent();
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping("/{key}")
|
||||
public SystemProperty getProperty(@PathVariable("key") String key) {
|
||||
if (!systemPropertyRepository.existsById(key)) {
|
||||
throw new EntityResponseStatusException(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
return systemPropertyRepository.findById(key).get();
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("")
|
||||
public SystemProperty createOrUpdate(@RequestBody SystemProperty systemProperty) {
|
||||
return systemPropertyRepository.save(systemProperty);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/list")
|
||||
public List<SystemProperty> createOrUpdateList(@RequestBody List<SystemProperty> systemProperties) {
|
||||
List<SystemProperty> result = new ArrayList<>();
|
||||
for (SystemProperty systemProperty : systemProperties) {
|
||||
result.add(
|
||||
systemPropertyRepository.save(systemProperty));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@DeleteMapping("/{key}")
|
||||
public void deleteProperty(@PathVariable("key") String key) {
|
||||
if (!systemPropertyRepository.existsById(key)) {
|
||||
throw new EntityResponseStatusException(HttpStatus.NOT_MODIFIED);
|
||||
}
|
||||
|
||||
systemPropertyRepository.deleteById(key);
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package de.champonthis.buntspecht.controller.admin;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.querydsl.core.QueryResults;
|
||||
import com.querydsl.core.Tuple;
|
||||
|
||||
import de.champonthis.buntspecht.businesslogic.TurnoverManager;
|
||||
import de.champonthis.buntspecht.controller.BaseController;
|
||||
import de.champonthis.buntspecht.controller.model.TurnoverFilterModel;
|
||||
import de.champonthis.buntspecht.controller.model.TurnoverFilterModel.MinMax;
|
||||
import de.champonthis.buntspecht.controller.support.EntityResponseStatusException;
|
||||
import de.champonthis.buntspecht.controller.support.RequestBodyErrors;
|
||||
import de.champonthis.buntspecht.controller.validation.TurnoverValidator;
|
||||
import de.champonthis.buntspecht.model.Turnover;
|
||||
import jakarta.transaction.Transactional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/turnovers/manage")
|
||||
public class TurnoverManagementController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private TurnoverManager turnoverManager;
|
||||
@Autowired
|
||||
private TurnoverValidator turnoverValidator;
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping
|
||||
@Transactional
|
||||
public QueryResults<Turnover> fetch(
|
||||
@RequestParam("username") Optional<String> usernameParameter,
|
||||
@RequestParam("limit") Optional<Long> limitParameter,
|
||||
@RequestParam("offset") Optional<Long> offsetParameter,
|
||||
@RequestParam("sort") Optional<String> sort,
|
||||
@RequestParam("descending") Optional<Boolean> descending,
|
||||
@RequestParam("from") Optional<Instant> from,
|
||||
@RequestParam("to") Optional<Instant> to,
|
||||
@RequestParam("customer") Optional<String> customer,
|
||||
@RequestParam("motif") Optional<String> motif) {
|
||||
|
||||
TurnoverFilterModel filter = new TurnoverFilterModel();
|
||||
filter.setCreated(new MinMax<Instant>(from.orElse(null), to.orElse(null)));
|
||||
filter.setCustomer(customer.orElse(null));
|
||||
filter.setMotif(motif.orElse(null));
|
||||
|
||||
return turnoverManager.fetch(usernameParameter.orElse(null), limitParameter.orElse(15L),
|
||||
offsetParameter.orElse(0L), sort.orElse("created"), descending.orElse(false), filter);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping("/overview")
|
||||
@Transactional
|
||||
public QueryResults<Tuple> fetchGroup(
|
||||
@RequestParam("username") Optional<String> usernameParameter,
|
||||
@RequestParam("limit") Optional<Long> limitParameter,
|
||||
@RequestParam("offset") Optional<Long> offsetParameter,
|
||||
@RequestParam("sort") Optional<String> sort,
|
||||
@RequestParam("descending") Optional<Boolean> descending,
|
||||
@RequestParam("from") Optional<Instant> from,
|
||||
@RequestParam("to") Optional<Instant> to,
|
||||
@RequestParam("customer") Optional<String> customer,
|
||||
@RequestParam("motif") Optional<String> motif) {
|
||||
|
||||
TurnoverFilterModel filter = new TurnoverFilterModel();
|
||||
filter.setCreated(new MinMax<Instant>(from.orElse(null), to.orElse(null)));
|
||||
filter.setCustomer(customer.orElse(null));
|
||||
filter.setMotif(motif.orElse(null));
|
||||
return turnoverManager.overview(usernameParameter.orElse(null), limitParameter.orElse(15L),
|
||||
offsetParameter.orElse(0L), sort.orElse("username"),
|
||||
descending.orElse(false), filter);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping("/{id}")
|
||||
@Transactional
|
||||
public Turnover getById(@PathVariable("id") Long id) {
|
||||
if (!turnoverManager.exists(id)) {
|
||||
throw new EntityResponseStatusException(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
return turnoverManager.get(id);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PatchMapping
|
||||
@Transactional
|
||||
public Turnover update(@RequestBody Turnover turnover) {
|
||||
Errors errors = new RequestBodyErrors(turnover);
|
||||
turnoverValidator.validate(turnover, errors);
|
||||
|
||||
if (errors.hasErrors()) {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
turnover.setUpdated(Instant.now());
|
||||
|
||||
return turnoverManager.save(turnover);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@DeleteMapping("/{id}")
|
||||
@Transactional
|
||||
public void deleteById(@PathVariable("id") Long id) {
|
||||
if (!turnoverManager.exists(id)) {
|
||||
throw new EntityResponseStatusException(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
turnoverManager.deleteById(id);
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
package de.champonthis.buntspecht.controller.admin;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.querydsl.core.QueryResults;
|
||||
|
||||
import de.champonthis.buntspecht.businesslogic.UserManager;
|
||||
import de.champonthis.buntspecht.controller.BaseController;
|
||||
import de.champonthis.buntspecht.controller.admin.validation.UserValidator;
|
||||
import de.champonthis.buntspecht.controller.model.UserPasswordModel;
|
||||
import de.champonthis.buntspecht.controller.support.EntityResponseStatusException;
|
||||
import de.champonthis.buntspecht.controller.support.RequestBodyErrors;
|
||||
import de.champonthis.buntspecht.controller.validation.PasswordModelValidator;
|
||||
import de.champonthis.buntspecht.model.User;
|
||||
import jakarta.transaction.Transactional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/users/manage")
|
||||
public class UserManagementController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private UserManager userManager;
|
||||
@Autowired
|
||||
private UserValidator userValidator;
|
||||
@Autowired
|
||||
private PasswordModelValidator passwordModelValidator;
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping
|
||||
@Transactional
|
||||
public QueryResults<User> fetch(
|
||||
@RequestParam("limit") Optional<Long> limitParameter,
|
||||
@RequestParam("offset") Optional<Long> offsetParameter,
|
||||
@RequestParam("sort") Optional<String> sort,
|
||||
@RequestParam("descending") Optional<Boolean> descending,
|
||||
@RequestParam("filter") Optional<String> search) {
|
||||
return userManager.fetch(limitParameter.orElse(15L), offsetParameter.orElse(0L), sort.orElse("username"),
|
||||
descending.orElse(false), search.orElse(""));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping("/pick")
|
||||
@Transactional
|
||||
public List<User> pick(
|
||||
@RequestParam("filter") Optional<String> search) {
|
||||
return userManager.fetch(5L, 0L, "", false, search.orElse("")).getResults();
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@GetMapping("/{username}")
|
||||
@Transactional
|
||||
public User get(@PathVariable("username") String username) {
|
||||
User user = userManager.getByUsername(username);
|
||||
|
||||
if (user == null) {
|
||||
throw new EntityResponseStatusException(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping
|
||||
@Transactional
|
||||
public User create(@RequestBody User user) {
|
||||
Errors errors = new RequestBodyErrors(user);
|
||||
userValidator.validateNew(user, errors);
|
||||
|
||||
if (errors.hasErrors()) {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
if (user.getLocale() == null) {
|
||||
user.setLocale("de");
|
||||
}
|
||||
|
||||
return userManager.save(user);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PatchMapping
|
||||
@Transactional
|
||||
public User update(@RequestBody User user) {
|
||||
Errors errors = new RequestBodyErrors(user);
|
||||
userValidator.validate(user, errors);
|
||||
|
||||
if (errors.hasErrors()) {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
if (getCurrentUsername().equals(user.getUsername()) && user.getRoles().indexOf("ROLE_ADMIN") == -1) {
|
||||
user.getRoles().add("ROLE_ADMIN");
|
||||
}
|
||||
|
||||
return userManager.save(user);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@DeleteMapping("/{username}")
|
||||
@Transactional
|
||||
public void delete(@PathVariable("username") String username) {
|
||||
User user = userManager.getByUsername(username);
|
||||
|
||||
if (user == null || getCurrentUsername().equals(username)) {
|
||||
throw new EntityResponseStatusException(HttpStatus.NOT_MODIFIED);
|
||||
}
|
||||
|
||||
userManager.delete(user);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/{username}/password")
|
||||
public void password(@PathVariable("username") String username,
|
||||
@RequestBody UserPasswordModel passwordModel) {
|
||||
|
||||
Errors errors = new RequestBodyErrors(passwordModel);
|
||||
|
||||
User user = userManager.getByUsername(username);
|
||||
|
||||
if (user == null) {
|
||||
throw new EntityResponseStatusException(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
passwordModelValidator.validate(passwordModel, errors);
|
||||
|
||||
if (errors.hasErrors()) {
|
||||
throw new EntityResponseStatusException(errors.getAllErrors(), HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
userManager.setPassword(user.getUsername(), passwordModel.getPassword());
|
||||
}
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package de.champonthis.buntspecht.controller.admin.validation;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
|
||||
import de.champonthis.buntspecht.businesslogic.UserManager;
|
||||
import de.champonthis.buntspecht.model.User;
|
||||
|
||||
@Component
|
||||
public class UserValidator implements Validator {
|
||||
|
||||
@Autowired
|
||||
private UserManager userManager;
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return clazz.isAssignableFrom(User.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Object target, Errors errors) {
|
||||
User user = (User) target;
|
||||
if (!StringUtils.hasText(user.getUsername())) {
|
||||
errors.rejectValue("username", "REQUIRED");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public void validateNew(Object target, Errors errors) {
|
||||
validate(target, errors);
|
||||
|
||||
if (errors.hasErrors()) {
|
||||
return;
|
||||
}
|
||||
|
||||
User user = (User) target;
|
||||
if (userManager.exists(user.getUsername())) {
|
||||
errors.rejectValue("username", "ALREADY_EXISTS");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package de.champonthis.buntspecht.controller.model;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.springframework.boot.jackson.JsonComponent;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.querydsl.core.Tuple;
|
||||
|
||||
@JsonComponent
|
||||
public class TupleSerializer extends JsonSerializer<Tuple> {
|
||||
|
||||
@Override
|
||||
public void serialize(Tuple value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
|
||||
if (value.toArray().length > 1) {
|
||||
gen.writeStartArray();
|
||||
}
|
||||
for (Object object : value.toArray()) {
|
||||
gen.writeObject(object);
|
||||
}
|
||||
if (value.toArray().length > 1) {
|
||||
gen.writeEndArray();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package de.champonthis.buntspecht.controller.model;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class TurnoverFilterModel {
|
||||
|
||||
private MinMax<Instant> created;
|
||||
private MinMax<Instant> updated;
|
||||
private String customer;
|
||||
private String motif;
|
||||
private MinMax<Float> price;
|
||||
private MinMax<Float> timeInvestment;
|
||||
|
||||
public MinMax<Instant> getCreated() {
|
||||
return created;
|
||||
}
|
||||
|
||||
public void setCreated(MinMax<Instant> created) {
|
||||
this.created = created;
|
||||
}
|
||||
|
||||
public MinMax<Instant> getUpdated() {
|
||||
return updated;
|
||||
}
|
||||
|
||||
public void setUpdated(MinMax<Instant> updated) {
|
||||
this.updated = updated;
|
||||
}
|
||||
|
||||
public String getCustomer() {
|
||||
return customer;
|
||||
}
|
||||
|
||||
public void setCustomer(String customer) {
|
||||
this.customer = customer;
|
||||
}
|
||||
|
||||
public String getMotif() {
|
||||
return motif;
|
||||
}
|
||||
|
||||
public void setMotif(String motif) {
|
||||
this.motif = motif;
|
||||
}
|
||||
|
||||
public MinMax<Float> getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(MinMax<Float> price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public MinMax<Float> getTimeInvestment() {
|
||||
return timeInvestment;
|
||||
}
|
||||
|
||||
public void setTimeInvestment(MinMax<Float> timeInvestment) {
|
||||
this.timeInvestment = timeInvestment;
|
||||
}
|
||||
|
||||
public static class MinMax<T> {
|
||||
|
||||
private T min;
|
||||
private T max;
|
||||
|
||||
public MinMax(T min, T max) {
|
||||
this.min = min;
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
public T getMin() {
|
||||
return min;
|
||||
}
|
||||
|
||||
public void setMin(T min) {
|
||||
this.min = min;
|
||||
}
|
||||
|
||||
public T getMax() {
|
||||
return max;
|
||||
}
|
||||
|
||||
public void setMax(T max) {
|
||||
this.max = max;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package de.champonthis.buntspecht.controller.model;
|
||||
|
||||
public class UserPasswordModel {
|
||||
|
||||
private String old;
|
||||
private String password;
|
||||
private String password2;
|
||||
|
||||
public String getOld() {
|
||||
return old;
|
||||
}
|
||||
|
||||
public void setOld(String old) {
|
||||
this.old = old;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPassword2() {
|
||||
return password2;
|
||||
}
|
||||
|
||||
public void setPassword2(String password2) {
|
||||
this.password2 = password2;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package de.champonthis.buntspecht.controller.support;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
||||
|
||||
|
||||
@ControllerAdvice
|
||||
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
|
||||
|
||||
@ExceptionHandler(value = { EntityResponseStatusException.class })
|
||||
protected ResponseEntity<Object> handleResponseEntityStatusException(RuntimeException exception,
|
||||
WebRequest request) {
|
||||
EntityResponseStatusException entityResponseStatusException = (EntityResponseStatusException) exception;
|
||||
return handleExceptionInternal(exception, entityResponseStatusException.getBody(), new HttpHeaders(),
|
||||
entityResponseStatusException.getStatus(), request);
|
||||
}
|
||||
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package de.champonthis.buntspecht.controller.support;
|
||||
|
||||
import org.springframework.core.NestedRuntimeException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import jakarta.annotation.Nullable;
|
||||
|
||||
|
||||
public class EntityResponseStatusException extends NestedRuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final HttpStatus status;
|
||||
|
||||
@Nullable
|
||||
private final Object body;
|
||||
|
||||
|
||||
public EntityResponseStatusException(HttpStatus status) {
|
||||
this(null, status);
|
||||
}
|
||||
|
||||
|
||||
public EntityResponseStatusException(@Nullable Object body, HttpStatus status) {
|
||||
this(body, status, null);
|
||||
}
|
||||
|
||||
|
||||
public EntityResponseStatusException(@Nullable Object body, HttpStatus status, @Nullable Throwable cause) {
|
||||
super(null, cause);
|
||||
Assert.notNull(status, "HttpStatus is required");
|
||||
this.status = status;
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
|
||||
public HttpStatus getStatus() {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
|
||||
@Nullable
|
||||
public Object getBody() {
|
||||
return this.body;
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.core.NestedRuntimeException#getMessage()
|
||||
*/
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return this.status + (this.body != null ? " \"" + this.body + "\"" : "");
|
||||
}
|
||||
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package de.champonthis.buntspecht.controller.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpInputMessage;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
|
||||
|
||||
@ControllerAdvice
|
||||
public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, ResponseBodyAdvice<String> {
|
||||
|
||||
private Gson gson = new Gson();
|
||||
|
||||
/*
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
|
||||
* supports(org.springframework.core.MethodParameter, java.lang.reflect.Type,
|
||||
* java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
public boolean supports(MethodParameter methodParameter, Type targetType,
|
||||
Class<? extends HttpMessageConverter<?>> converterType) {
|
||||
return targetType instanceof Class && String.class.equals((Class<?>) targetType);
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
|
||||
* beforeBodyRead(org.springframework.http.HttpInputMessage,
|
||||
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
|
||||
* java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
|
||||
Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
|
||||
return inputMessage;
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
|
||||
* afterBodyRead(java.lang.Object, org.springframework.http.HttpInputMessage,
|
||||
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
|
||||
* java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
|
||||
Class<? extends HttpMessageConverter<?>> converterType) {
|
||||
body = ((String) body).replaceAll("^\"|\"$", "");
|
||||
return body;
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
|
||||
* handleEmptyBody(java.lang.Object, org.springframework.http.HttpInputMessage,
|
||||
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
|
||||
* java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
|
||||
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
|
||||
return body;
|
||||
}
|
||||
|
||||
/*
|
||||
* @see
|
||||
* org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#
|
||||
* supports(org.springframework.core.MethodParameter, java.lang.Class)
|
||||
*/
|
||||
@Override
|
||||
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
|
||||
return converterType == StringHttpMessageConverter.class;
|
||||
}
|
||||
|
||||
/*
|
||||
* @see
|
||||
* org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#
|
||||
* beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter,
|
||||
* org.springframework.http.MediaType, java.lang.Class,
|
||||
* org.springframework.http.server.ServerHttpRequest,
|
||||
* org.springframework.http.server.ServerHttpResponse)
|
||||
*/
|
||||
@Override
|
||||
public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType,
|
||||
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
|
||||
ServerHttpResponse response) {
|
||||
response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
|
||||
return gson.toJson(new JsonPrimitive(body));
|
||||
}
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package de.champonthis.buntspecht.controller.support;
|
||||
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.validation.AbstractBindingResult;
|
||||
|
||||
|
||||
public class RequestBodyErrors extends AbstractBindingResult {
|
||||
|
||||
@Nullable
|
||||
private final Object target;
|
||||
|
||||
|
||||
public RequestBodyErrors(@Nullable Object target) {
|
||||
super("request-body");
|
||||
this.target = target;
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.validation.AbstractBindingResult#getTarget()
|
||||
*/
|
||||
@Override
|
||||
public Object getTarget() {
|
||||
return target;
|
||||
}
|
||||
|
||||
/*
|
||||
* @see
|
||||
* org.springframework.validation.AbstractBindingResult#getActualFieldValue(java
|
||||
* .lang.String)
|
||||
*/
|
||||
@Override
|
||||
protected Object getActualFieldValue(String field) {
|
||||
// Not necessary
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package de.champonthis.buntspecht.controller.validation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.passay.CharacterRule;
|
||||
import org.passay.EnglishCharacterData;
|
||||
import org.passay.LengthRule;
|
||||
import org.passay.PasswordData;
|
||||
import org.passay.PasswordValidator;
|
||||
import org.passay.Rule;
|
||||
import org.passay.RuleResult;
|
||||
import org.passay.RuleResultDetail;
|
||||
import org.passay.WhitespaceRule;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
|
||||
import de.champonthis.buntspecht.businesslogic.SystemPropertyManager;
|
||||
import de.champonthis.buntspecht.controller.model.UserPasswordModel;
|
||||
|
||||
@Component
|
||||
public class PasswordModelValidator implements Validator {
|
||||
|
||||
@Autowired
|
||||
private SystemPropertyManager systemPropertyManager;
|
||||
|
||||
public static final String SYSTEM_PROPERTY_PASSWORD_RULE_WHITESPACE = "password.rule.whitespace";
|
||||
public static final String SYSTEM_PROPERTY_PASSWORD_RULE_LENGTH = "password.rule.length";
|
||||
public static final String SYSTEM_PROPERTY_PASSWORD_RULE_UPPERCASE = "password.rule.uppercase";
|
||||
public static final String SYSTEM_PROPERTY_PASSWORD_RULE_DIGIT = "password.rule.digit";
|
||||
public static final String SYSTEM_PROPERTY_PASSWORD_RULE_SPECIAL = "password.rule.special";
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return clazz.isAssignableFrom(UserPasswordModel.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Object target, Errors errors) {
|
||||
UserPasswordModel passwordModel = (UserPasswordModel) target;
|
||||
|
||||
List<Rule> rules = new ArrayList<Rule>();
|
||||
|
||||
if (systemPropertyManager.getBoolean(SYSTEM_PROPERTY_PASSWORD_RULE_WHITESPACE, true)) {
|
||||
rules.add(new WhitespaceRule());
|
||||
}
|
||||
|
||||
int length = systemPropertyManager.getInteger(SYSTEM_PROPERTY_PASSWORD_RULE_LENGTH, 8);
|
||||
if (length > 0) {
|
||||
rules.add(new LengthRule(length, 4096));
|
||||
}
|
||||
|
||||
int uppercase = systemPropertyManager.getInteger(SYSTEM_PROPERTY_PASSWORD_RULE_UPPERCASE, 1);
|
||||
if (uppercase > 0) {
|
||||
rules.add(new CharacterRule(EnglishCharacterData.UpperCase, uppercase));
|
||||
}
|
||||
|
||||
int digit = systemPropertyManager.getInteger(SYSTEM_PROPERTY_PASSWORD_RULE_DIGIT, 1);
|
||||
if (digit > 0) {
|
||||
rules.add(new CharacterRule(EnglishCharacterData.Digit, digit));
|
||||
}
|
||||
|
||||
int special = systemPropertyManager.getInteger(SYSTEM_PROPERTY_PASSWORD_RULE_SPECIAL, 1);
|
||||
if (special > 0) {
|
||||
rules.add(new CharacterRule(EnglishCharacterData.Special, special));
|
||||
}
|
||||
|
||||
PasswordValidator validator = new PasswordValidator(rules);
|
||||
PasswordData password = new PasswordData(passwordModel.getPassword());
|
||||
RuleResult result = validator.validate(password);
|
||||
|
||||
if (!result.isValid()) {
|
||||
for (RuleResultDetail ruleResultDetail : result.getDetails()) {
|
||||
errors.rejectValue("password", ruleResultDetail.getErrorCode());
|
||||
}
|
||||
}
|
||||
|
||||
if (!passwordModel.getPassword().equals(passwordModel.getPassword2())) {
|
||||
errors.rejectValue("password2", "NOT_MATCH");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package de.champonthis.buntspecht.controller.validation;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
|
||||
import de.champonthis.buntspecht.model.Turnover;
|
||||
|
||||
@Component
|
||||
public class TurnoverValidator implements Validator {
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return clazz.isAssignableFrom(Turnover.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Object target, Errors errors) {
|
||||
Turnover turnover = (Turnover) target;
|
||||
|
||||
if (!StringUtils.hasText(turnover.getCustomer())) {
|
||||
errors.rejectValue("customer", "REQUIRED");
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(turnover.getMotif())) {
|
||||
errors.rejectValue("motif", "REQUIRED");
|
||||
}
|
||||
|
||||
if (turnover.getPrice() == 0) {
|
||||
errors.rejectValue("price", "REQUIRED");
|
||||
}
|
||||
|
||||
if (turnover.getPrice() < 0) {
|
||||
errors.rejectValue("price", "POSITIVE_VALUE");
|
||||
}
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
package de.champonthis.buntspecht.i18n.businesslogic;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.ResourceLoader;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import de.champonthis.buntspecht.i18n.model.I18n;
|
||||
import de.champonthis.buntspecht.i18n.repository.I18nRepository;
|
||||
|
||||
|
||||
@Component
|
||||
public class I18nManager implements SmartInitializingSingleton {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(I18nManager.class);
|
||||
|
||||
@Autowired
|
||||
private I18nRepository i18nRepository;
|
||||
|
||||
@Autowired
|
||||
private ResourceLoader resourceLoader;
|
||||
|
||||
private Gson gson = new Gson();
|
||||
|
||||
|
||||
public I18n get(String locale) {
|
||||
return i18nRepository.findById(locale).orElse(null);
|
||||
}
|
||||
|
||||
|
||||
public JsonObject getLabel(String locale) {
|
||||
I18n i18n = get(locale);
|
||||
if (i18n != null && StringUtils.hasText(i18n.getLabel())) {
|
||||
JsonElement element = JsonParser.parseString(i18n.getLabel());
|
||||
if (element != null && element.isJsonObject()) {
|
||||
return element.getAsJsonObject();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public List<String> getLocales() {
|
||||
return i18nRepository.findAll().stream().map(I18n::getLocale).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
|
||||
protected void extendJsonObject(JsonObject dest, JsonObject src) {
|
||||
for (Entry<String, JsonElement> srcEntry : src.entrySet()) {
|
||||
String srcKey = srcEntry.getKey();
|
||||
JsonElement srcValue = srcEntry.getValue();
|
||||
if (dest.has(srcKey)) {
|
||||
JsonElement destValue = dest.get(srcKey);
|
||||
if (destValue.isJsonObject() && srcValue.isJsonObject()) {
|
||||
extendJsonObject(destValue.getAsJsonObject(), srcValue.getAsJsonObject());
|
||||
} else {
|
||||
dest.add(srcKey, srcValue);
|
||||
}
|
||||
} else {
|
||||
dest.add(srcKey, srcValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public I18n addLabel(String locale, JsonObject newLabel) {
|
||||
JsonObject label = getLabel(locale);
|
||||
|
||||
if (label == null || label.size() == 0 || label.entrySet().isEmpty()) {
|
||||
label = newLabel;
|
||||
} else {
|
||||
extendJsonObject(label, newLabel);
|
||||
}
|
||||
|
||||
I18n i18n = new I18n();
|
||||
i18n.setLocale(locale);
|
||||
i18n.setLabel(gson.toJson(label));
|
||||
|
||||
return i18nRepository.save(i18n);
|
||||
}
|
||||
|
||||
|
||||
public I18n setLabel(String locale, JsonObject label) {
|
||||
I18n i18n = new I18n();
|
||||
i18n.setLocale(locale);
|
||||
i18n.setLabel(gson.toJson(label));
|
||||
|
||||
return i18nRepository.save(i18n);
|
||||
}
|
||||
|
||||
|
||||
public void deleteLabel(String locale) {
|
||||
if (i18nRepository.existsById(locale)) {
|
||||
i18nRepository.deleteById(locale);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.beans.factory.SmartInitializingSingleton#
|
||||
* afterSingletonsInstantiated()
|
||||
*/
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
try {
|
||||
Resource resource = resourceLoader.getResource("classpath:label");
|
||||
|
||||
if (resource.exists()) {
|
||||
File labelFolder = resource.getFile();
|
||||
if (labelFolder.exists() && labelFolder.isDirectory()) {
|
||||
for (File labelFile : labelFolder.listFiles()) {
|
||||
JsonObject label = JsonParser.parseReader(new FileReader(labelFile, StandardCharsets.UTF_8))
|
||||
.getAsJsonObject();
|
||||
|
||||
String locale = labelFile.getName().replace(".json", "");
|
||||
addLabel(locale, label);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
logger.warn("cannot read in label folder", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package de.champonthis.buntspecht.i18n.controller;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonIOException;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import de.champonthis.buntspecht.controller.BaseController;
|
||||
import de.champonthis.buntspecht.i18n.businesslogic.I18nManager;
|
||||
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/i18n")
|
||||
public class I18nController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private I18nManager i18nManager;
|
||||
|
||||
private Gson gson = new Gson();
|
||||
|
||||
|
||||
@GetMapping
|
||||
public List<String> getLocales() {
|
||||
return i18nManager.getLocales();
|
||||
}
|
||||
|
||||
|
||||
@GetMapping("/{locale}")
|
||||
public void getLabel(@PathVariable("locale") String locale, HttpServletResponse response)
|
||||
throws JsonIOException, IOException {
|
||||
JsonObject label = i18nManager.getLabel(locale);
|
||||
if (label != null) {
|
||||
response.setCharacterEncoding("utf-8");
|
||||
gson.toJson(label, response.getWriter());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PostMapping("/{locale}")
|
||||
public void setLabel(@PathVariable("locale") String locale, @RequestBody Object label) {
|
||||
JsonElement element = gson.toJsonTree(label);
|
||||
|
||||
if (element != null && element.isJsonObject()) {
|
||||
i18nManager.setLabel(locale, element.getAsJsonObject());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@PutMapping("/{locale}")
|
||||
public void addLabel(@PathVariable("locale") String locale, @RequestBody Object label) {
|
||||
JsonElement element = gson.toJsonTree(label);
|
||||
|
||||
if (element != null && element.isJsonObject()) {
|
||||
i18nManager.addLabel(locale, element.getAsJsonObject());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')")
|
||||
@DeleteMapping("/{locale}")
|
||||
public void deleteLocale(@PathVariable("locale") String locale) {
|
||||
i18nManager.deleteLabel(locale);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package de.champonthis.buntspecht.i18n.model;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Lob;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.UniqueConstraint;
|
||||
|
||||
|
||||
@Entity
|
||||
@Table(name = "i18n", uniqueConstraints = @UniqueConstraint(columnNames = { "locale" }))
|
||||
public class I18n {
|
||||
|
||||
@Id
|
||||
@Column(name = "locale", unique = true, nullable = false)
|
||||
private String locale;
|
||||
|
||||
@Lob
|
||||
@Column(name = "label", length = 100000)
|
||||
private String label;
|
||||
|
||||
|
||||
public String getLocale() {
|
||||
return locale;
|
||||
}
|
||||
|
||||
|
||||
public void setLocale(String locale) {
|
||||
this.locale = locale;
|
||||
}
|
||||
|
||||
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
|
||||
|
||||
public void setLabel(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package de.champonthis.buntspecht.i18n.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import de.champonthis.buntspecht.i18n.model.I18n;
|
||||
|
||||
|
||||
@Repository
|
||||
public interface I18nRepository extends JpaRepository<I18n, String>, QuerydslPredicateExecutor<I18n> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package de.champonthis.buntspecht.model;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "persistent_logins")
|
||||
public class PersistentLogin {
|
||||
|
||||
@Column(name = "username", length = 64, nullable = false)
|
||||
private String username;
|
||||
@Id
|
||||
@Column(name = "series", length = 64)
|
||||
private String series;
|
||||
@Column(name = "token", length = 64, nullable = false)
|
||||
private String token;
|
||||
@Column(name = "last_used", nullable = false)
|
||||
private Instant last_used;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getSeries() {
|
||||
return series;
|
||||
}
|
||||
|
||||
public void setSeries(String series) {
|
||||
this.series = series;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public Instant getLast_used() {
|
||||
return last_used;
|
||||
}
|
||||
|
||||
public void setLast_used(Instant last_used) {
|
||||
this.last_used = last_used;
|
||||
}
|
||||
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package de.champonthis.buntspecht.model;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Lob;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
|
||||
@Entity
|
||||
@Table(name = "system_properties")
|
||||
public class SystemProperty {
|
||||
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private String key;
|
||||
@Lob
|
||||
@Column(name = "value", length = 100000)
|
||||
private String value;
|
||||
|
||||
|
||||
public SystemProperty() {
|
||||
super();
|
||||
}
|
||||
|
||||
|
||||
public SystemProperty(String key, String value) {
|
||||
super();
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
|
||||
public void setKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package de.champonthis.buntspecht.model;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Lob;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "turnovers")
|
||||
public class Turnover {
|
||||
|
||||
@Id
|
||||
@Column(name = "id", updatable = false, unique = true, nullable = false)
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "username", nullable = false)
|
||||
private String username;
|
||||
|
||||
@Column(name = "created", nullable = false, updatable = false)
|
||||
private Instant created;
|
||||
|
||||
@Column(name = "updated", nullable = false)
|
||||
private Instant updated;
|
||||
|
||||
@Column(name = "customer", nullable = false)
|
||||
private String customer;
|
||||
|
||||
@Column(name = "motif", nullable = false)
|
||||
private String motif;
|
||||
|
||||
@Column(name = "price", nullable = false)
|
||||
private float price;
|
||||
|
||||
@Column(name = "time_investment", nullable = true)
|
||||
private float timeInvestment;
|
||||
|
||||
@Lob
|
||||
@Column(name = "remark", nullable = true, length = 5000)
|
||||
private String remark;
|
||||
|
||||
@Lob
|
||||
@Column(name = "material_consumption", nullable = true, length = 5000)
|
||||
private String materialConsumption;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public Instant getCreated() {
|
||||
return created;
|
||||
}
|
||||
|
||||
public void setCreated(Instant created) {
|
||||
this.created = created;
|
||||
}
|
||||
|
||||
public Instant getUpdated() {
|
||||
return updated;
|
||||
}
|
||||
|
||||
public void setUpdated(Instant updated) {
|
||||
this.updated = updated;
|
||||
}
|
||||
|
||||
public String getCustomer() {
|
||||
return customer;
|
||||
}
|
||||
|
||||
public void setCustomer(String customer) {
|
||||
this.customer = customer;
|
||||
}
|
||||
|
||||
public String getMotif() {
|
||||
return motif;
|
||||
}
|
||||
|
||||
public void setMotif(String motif) {
|
||||
this.motif = motif;
|
||||
}
|
||||
|
||||
public float getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(float price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public float getTimeInvestment() {
|
||||
return timeInvestment;
|
||||
}
|
||||
|
||||
public void setTimeInvestment(float timeInvestment) {
|
||||
this.timeInvestment = timeInvestment;
|
||||
}
|
||||
|
||||
public String getRemark() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setRemark(String remark) {
|
||||
this.remark = remark;
|
||||
}
|
||||
|
||||
public String getMaterialConsumption() {
|
||||
return materialConsumption;
|
||||
}
|
||||
|
||||
public void setMaterialConsumption(String materialConsumption) {
|
||||
this.materialConsumption = materialConsumption;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof Turnover)) {
|
||||
return false;
|
||||
}
|
||||
Turnover turnover = (Turnover) obj;
|
||||
boolean equals = true;
|
||||
|
||||
equals &= id == null && turnover.getId() == null || id.equals(turnover.getId());
|
||||
|
||||
equals &= username == null && turnover.getUsername() == null || username.equals(turnover.getUsername());
|
||||
|
||||
equals &= customer == null && turnover.getCustomer() == null || customer.equals(turnover.getCustomer());
|
||||
|
||||
equals &= motif == null && turnover.getMotif() == null || motif.equals(turnover.getMotif());
|
||||
|
||||
equals &= price == turnover.getPrice();
|
||||
|
||||
equals &= timeInvestment == turnover.getTimeInvestment();
|
||||
|
||||
equals &= remark == null && turnover.getRemark() == null || remark.equals(turnover.getRemark());
|
||||
|
||||
equals &= materialConsumption == null && turnover.getMaterialConsumption() == null
|
||||
|| materialConsumption.equals(turnover.getMaterialConsumption());
|
||||
|
||||
return equals;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package de.champonthis.buntspecht.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
|
||||
import jakarta.persistence.CollectionTable;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.ElementCollection;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Lob;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.Transient;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
@JsonInclude(Include.NON_EMPTY)
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@Column(name = "username", nullable = false)
|
||||
private String username;
|
||||
@Column(name = "external_id", nullable = true)
|
||||
private String externalId;
|
||||
@Column(name = "name", nullable = true)
|
||||
private String name;
|
||||
@JsonIgnore
|
||||
@Column(name = "password_hash", nullable = true)
|
||||
private String passwordHash;
|
||||
@ElementCollection(fetch = FetchType.EAGER)
|
||||
@CollectionTable(name = "users_roles")
|
||||
private List<String> roles;
|
||||
@Lob
|
||||
@Column(name = "about", nullable = true, length = 100000)
|
||||
private String about;
|
||||
@Column(name = "email", nullable = true)
|
||||
private String email;
|
||||
@Column(name = "locale", nullable = true, columnDefinition = "varchar(255) default 'de'")
|
||||
private String locale;
|
||||
@Column(name = "dark_theme", nullable = true, columnDefinition = "boolean default false")
|
||||
private boolean darkTheme;
|
||||
@Transient
|
||||
private Map<String, Object> metadata;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getExternalId() {
|
||||
return externalId;
|
||||
}
|
||||
|
||||
public void setExternalId(String externalId) {
|
||||
this.externalId = externalId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getPasswordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public void setPasswordHash(String passwordHash) {
|
||||
this.passwordHash = passwordHash;
|
||||
}
|
||||
|
||||
public List<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(List<String> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public String getAbout() {
|
||||
return about;
|
||||
}
|
||||
|
||||
public void setAbout(String about) {
|
||||
this.about = about;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getLocale() {
|
||||
return locale;
|
||||
}
|
||||
|
||||
public void setLocale(String locale) {
|
||||
this.locale = locale;
|
||||
}
|
||||
|
||||
public boolean isDarkTheme() {
|
||||
return darkTheme;
|
||||
}
|
||||
|
||||
public void setDarkTheme(boolean darkTheme) {
|
||||
this.darkTheme = darkTheme;
|
||||
}
|
||||
|
||||
public Map<String, Object> getMetadata() {
|
||||
if (metadata == null) {
|
||||
metadata = Map.of();
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
|
||||
public void setMetadata(Map<String, Object> metadata) {
|
||||
this.metadata = metadata;
|
||||
}
|
||||
|
||||
}
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
package de.champonthis.buntspecht.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import de.champonthis.buntspecht.model.SystemProperty;
|
||||
|
||||
|
||||
@Repository
|
||||
public interface SystemPropertyRepository
|
||||
extends JpaRepository<SystemProperty, String>, QuerydslPredicateExecutor<SystemProperty> {
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package de.champonthis.buntspecht.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import de.champonthis.buntspecht.model.Turnover;
|
||||
|
||||
@Repository
|
||||
public interface TurnoverRepository extends JpaRepository<Turnover, Long>, QuerydslPredicateExecutor<Turnover> {
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package de.champonthis.buntspecht.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import de.champonthis.buntspecht.model.User;
|
||||
|
||||
|
||||
@Repository
|
||||
public interface UserRepository extends JpaRepository<User, String>, QuerydslPredicateExecutor<User> {
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package de.champonthis.buntspecht.security;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
|
||||
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
|
||||
|
||||
|
||||
public class LocalRememberMeServices extends PersistentTokenBasedRememberMeServices {
|
||||
|
||||
|
||||
public LocalRememberMeServices(String key, UserDetailsService userDetailsService,
|
||||
PersistentTokenRepository tokenRepository) {
|
||||
super(key, userDetailsService, tokenRepository);
|
||||
}
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.web.authentication.rememberme.
|
||||
* AbstractRememberMeServices#rememberMeRequested(javax.servlet.http.
|
||||
* HttpServletRequest, java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {
|
||||
Object value = request.getAttribute(parameter);
|
||||
if (value != null) {
|
||||
String paramValue = value.toString();
|
||||
if (paramValue.equalsIgnoreCase("true") || paramValue.equalsIgnoreCase("on")
|
||||
|| paramValue.equalsIgnoreCase("yes") || paramValue.equals("1")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return super.rememberMeRequested(request, parameter);
|
||||
}
|
||||
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package de.champonthis.buntspecht.security;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
|
||||
|
||||
public class LocalUserDetails extends User {
|
||||
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
|
||||
public LocalUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) {
|
||||
super(username, password, authorities);
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package de.champonthis.buntspecht.security;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class PasswordEncoderConfig {
|
||||
|
||||
|
||||
@Bean(name = "passwordEncoder")
|
||||
public Argon2PasswordEncoder passwordEncoder() {
|
||||
return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package de.champonthis.buntspecht.security;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
|
||||
import org.springframework.security.web.authentication.RememberMeServices;
|
||||
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
|
||||
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
|
||||
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
|
||||
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
|
||||
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import de.champonthis.buntspecht.businesslogic.UserManager;
|
||||
import de.champonthis.buntspecht.security.handler.FormAuthenticationFailureHandler;
|
||||
import de.champonthis.buntspecht.security.handler.OAuth2AuthenticationSuccessHandler;
|
||||
|
||||
@EnableWebSecurity
|
||||
@EnableMethodSecurity(prePostEnabled = true)
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
@Autowired
|
||||
private UserManager userManager;
|
||||
@Autowired
|
||||
private OAuth2AuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler;
|
||||
@Autowired
|
||||
private DataSource dataSource;
|
||||
@Value("${loginUrl:/login}")
|
||||
private String loginUrl;
|
||||
@Value("${loginTargetUrl:/}")
|
||||
private String loginTargetUrl;
|
||||
@Value("${spring.security.oauth2.client:false}")
|
||||
private boolean oauth2Enabled;
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
|
||||
if (oauth2Enabled) {
|
||||
oAuth2AuthenticationSuccessHandler.setDefaultTargetUrl(loginTargetUrl);
|
||||
oAuth2AuthenticationSuccessHandler.setRememberMeServices(rememberMeServices());
|
||||
}
|
||||
|
||||
http
|
||||
// crsf
|
||||
.csrf((csrf) -> csrf.disable())
|
||||
// cors
|
||||
// .cors().configurationSource(corsConfigurationSource()).and()
|
||||
// anonymous
|
||||
.anonymous((anonymous) -> anonymous.disable())
|
||||
// login
|
||||
.formLogin((formLogin) -> formLogin.loginPage("/login").defaultSuccessUrl(loginTargetUrl)
|
||||
.failureHandler(new FormAuthenticationFailureHandler(loginUrl)))
|
||||
// remember me
|
||||
.rememberMe((rememberMe) -> rememberMe.rememberMeServices(rememberMeServices()))
|
||||
// logout
|
||||
.logout((logout) -> logout.logoutUrl("/logout")
|
||||
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)))
|
||||
// exception
|
||||
.exceptionHandling((exceptionHandling) -> exceptionHandling
|
||||
.defaultAuthenticationEntryPointFor(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
|
||||
new AntPathRequestMatcher("/api/**")));
|
||||
|
||||
if (oauth2Enabled) {
|
||||
http.oauth2Login((oauth2Login) -> oauth2Login.successHandler(oAuth2AuthenticationSuccessHandler)
|
||||
.failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?externalError"))
|
||||
.loginPage("/login"));
|
||||
}
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistentTokenRepository persistentTokenRepository() {
|
||||
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
|
||||
tokenRepository.setDataSource(dataSource);
|
||||
return tokenRepository;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RememberMeServices rememberMeServices() {
|
||||
PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices("remember-me",
|
||||
userManager, persistentTokenRepository());
|
||||
return rememberMeServices;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowedOriginPatterns(List.of("*"));
|
||||
configuration.setAllowedMethods(Collections.singletonList("*"));
|
||||
configuration.setAllowCredentials(true);
|
||||
configuration.setAllowedHeaders(Collections.singletonList("*"));
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package de.champonthis.buntspecht.security.handler;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
|
||||
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
public class FormAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
|
||||
|
||||
private String failureUrl;
|
||||
|
||||
public FormAuthenticationFailureHandler(String failureUrl) {
|
||||
super(failureUrl);
|
||||
this.failureUrl = failureUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
|
||||
AuthenticationException exception) throws IOException, ServletException {
|
||||
setDefaultFailureUrl(failureUrl + "?error&username=" + request.getParameter("username"));
|
||||
super.onAuthenticationFailure(request, response, exception);
|
||||
setDefaultFailureUrl(failureUrl);
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package de.champonthis.buntspecht.security.handler;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.web.authentication.RememberMeServices;
|
||||
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import de.champonthis.buntspecht.businesslogic.UserManager;
|
||||
import de.champonthis.buntspecht.model.User;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
|
||||
@Component
|
||||
public class OAuth2AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
|
||||
|
||||
@Autowired
|
||||
private UserManager userManager;
|
||||
|
||||
private RememberMeServices rememberMeServices;
|
||||
|
||||
/*
|
||||
* @see org.springframework.security.web.authentication.
|
||||
* SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.
|
||||
* servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
|
||||
* org.springframework.security.core.Authentication)
|
||||
*/
|
||||
@Override
|
||||
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
|
||||
Authentication authentication) throws IOException, ServletException {
|
||||
User user = userManager.getByAuth(authentication);
|
||||
|
||||
UserDetails userDetails = userManager.loadUserByUsername(user.getUsername());
|
||||
|
||||
List<GrantedAuthority> authorities = new ArrayList<>();
|
||||
authorities.addAll(authentication.getAuthorities());
|
||||
authorities.addAll(userDetails.getAuthorities());
|
||||
|
||||
UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(userDetails,
|
||||
null, authorities);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(newAuthentication);
|
||||
|
||||
if (rememberMeServices != null) {
|
||||
request.setAttribute("remember-me", "true");
|
||||
rememberMeServices.loginSuccess(request, response, newAuthentication);
|
||||
}
|
||||
|
||||
handle(request, response, newAuthentication);
|
||||
clearAuthenticationAttributes(request);
|
||||
}
|
||||
|
||||
|
||||
public void setRememberMeServices(RememberMeServices rememberMeServices) {
|
||||
this.rememberMeServices = rememberMeServices;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
|
||||
# For additional information regarding the format and rule options, please see:
|
||||
# https://github.com/browserslist/browserslist#queries
|
||||
|
||||
# For the full list of supported browsers by the Angular framework, please see:
|
||||
# https://angular.io/guide/browser-support
|
||||
|
||||
# You can see what browsers were selected by your queries by running:
|
||||
# npx browserslist
|
||||
|
||||
last 1 Chrome version
|
||||
last 1 Firefox version
|
||||
last 2 Edge major versions
|
||||
last 2 Safari major versions
|
||||
last 2 iOS major versions
|
||||
Firefox ESR
|
||||
not IE 9-10 # Angular support for IE 9-10 has been deprecated and will be removed as of Angular v11. To opt-in, remove the 'not' prefix on this line.
|
||||
not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Editor configuration, see https://editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.ts]
|
||||
quote_type = single
|
||||
|
||||
[*.md]
|
||||
max_line_length = off
|
||||
trim_trailing_whitespace = false
|
||||
@@ -0,0 +1,49 @@
|
||||
# See http://help.github.com/ignore-files/ for more about ignoring files.
|
||||
|
||||
# compiled output
|
||||
/dist
|
||||
/tmp
|
||||
/out-tsc
|
||||
# Only exists if Bazel was run
|
||||
/bazel-out
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
|
||||
# profiling files
|
||||
chrome-profiler-events*.json
|
||||
speed-measure-plugin*.json
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
.history/*
|
||||
|
||||
# misc
|
||||
/.angular/cache
|
||||
/.sass-cache
|
||||
/connect.lock
|
||||
/coverage
|
||||
/libpeerconnection.log
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
testem.log
|
||||
/typings
|
||||
|
||||
# System Files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
.vscode
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,3 @@
|
||||
# buntspecht frontend
|
||||
|
||||
Frontend of buntspecht created with Angular Framework.
|
||||
@@ -0,0 +1,132 @@
|
||||
{
|
||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||
"version": 1,
|
||||
"newProjectRoot": "projects",
|
||||
"projects": {
|
||||
"buntspecht-frontent": {
|
||||
"projectType": "application",
|
||||
"schematics": {
|
||||
"@schematics/angular:component": {
|
||||
"style": "scss"
|
||||
}
|
||||
},
|
||||
"root": "",
|
||||
"sourceRoot": "src",
|
||||
"prefix": "app",
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular-devkit/build-angular:browser",
|
||||
"options": {
|
||||
"outputPath": "dist/buntspecht",
|
||||
"index": "src/index.html",
|
||||
"main": "src/main.ts",
|
||||
"polyfills": "src/polyfills.ts",
|
||||
"tsConfig": "tsconfig.app.json",
|
||||
"assets": [
|
||||
"src/.htaccess",
|
||||
"src/favicon.ico",
|
||||
"src/assets",
|
||||
"src/manifest.webmanifest"
|
||||
],
|
||||
"styles": [
|
||||
"src/styles.scss"
|
||||
],
|
||||
"scripts": [],
|
||||
"serviceWorker": true,
|
||||
"ngswConfigPath": "ngsw-config.json",
|
||||
"vendorChunk": true,
|
||||
"extractLicenses": false,
|
||||
"buildOptimizer": false,
|
||||
"sourceMap": true,
|
||||
"optimization": false,
|
||||
"namedChunks": true,
|
||||
"allowedCommonJsDependencies": [
|
||||
"moment"
|
||||
]
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"fileReplacements": [
|
||||
{
|
||||
"replace": "src/environments/environment.ts",
|
||||
"with": "src/environments/environment.prod.ts"
|
||||
}
|
||||
],
|
||||
"optimization": true,
|
||||
"outputHashing": "all",
|
||||
"sourceMap": false,
|
||||
"namedChunks": false,
|
||||
"extractLicenses": true,
|
||||
"vendorChunk": false,
|
||||
"buildOptimizer": true,
|
||||
"budgets": [
|
||||
{
|
||||
"type": "initial",
|
||||
"maximumWarning": "2mb",
|
||||
"maximumError": "5mb"
|
||||
},
|
||||
{
|
||||
"type": "anyComponentStyle",
|
||||
"maximumWarning": "6kb",
|
||||
"maximumError": "10kb"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": ""
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular-devkit/build-angular:dev-server",
|
||||
"options": {
|
||||
"buildTarget": "buntspecht-frontent:build",
|
||||
"port": 4201
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"buildTarget": "buntspecht-frontent:build:production"
|
||||
}
|
||||
}
|
||||
},
|
||||
"extract-i18n": {
|
||||
"builder": "@angular-devkit/build-angular:extract-i18n",
|
||||
"options": {
|
||||
"buildTarget": "buntspecht-frontent:build"
|
||||
}
|
||||
},
|
||||
"test": {
|
||||
"builder": "@angular-devkit/build-angular:karma",
|
||||
"options": {
|
||||
"main": "src/test.ts",
|
||||
"polyfills": "src/polyfills.ts",
|
||||
"tsConfig": "tsconfig.spec.json",
|
||||
"karmaConfig": "karma.conf.js",
|
||||
"assets": [
|
||||
"src/favicon.ico",
|
||||
"src/assets",
|
||||
"src/manifest.webmanifest"
|
||||
],
|
||||
"styles": [
|
||||
"src/styles.scss"
|
||||
],
|
||||
"scripts": []
|
||||
}
|
||||
},
|
||||
"e2e": {
|
||||
"builder": "@angular-devkit/build-angular:protractor",
|
||||
"options": {
|
||||
"protractorConfig": "e2e/protractor.conf.js",
|
||||
"devServerTarget": "buntspecht-frontent:serve"
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"devServerTarget": "buntspecht-frontent:serve:production"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"cli": {
|
||||
"analytics": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// @ts-check
|
||||
// Protractor configuration file, see link for more information
|
||||
// https://github.com/angular/protractor/blob/master/lib/config.ts
|
||||
|
||||
const { SpecReporter, StacktraceOption } = require('jasmine-spec-reporter');
|
||||
|
||||
|
||||
exports.config = {
|
||||
allScriptsTimeout: 11000,
|
||||
specs: [
|
||||
'./src/**/*.e2e-spec.ts'
|
||||
],
|
||||
capabilities: {
|
||||
browserName: 'chrome'
|
||||
},
|
||||
directConnect: true,
|
||||
baseUrl: 'http://localhost:4200/',
|
||||
framework: 'jasmine',
|
||||
jasmineNodeOpts: {
|
||||
showColors: true,
|
||||
defaultTimeoutInterval: 30000,
|
||||
print: function() {}
|
||||
},
|
||||
onPrepare() {
|
||||
require('ts-node').register({
|
||||
project: require('path').join(__dirname, './tsconfig.json')
|
||||
});
|
||||
jasmine.getEnv().addReporter(new SpecReporter({
|
||||
spec: {
|
||||
displayStacktrace: StacktraceOption.PRETTY
|
||||
}
|
||||
}));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import { AppPage } from './app.po';
|
||||
import { browser, logging } from 'protractor';
|
||||
|
||||
describe('workspace-project App', () => {
|
||||
let page: AppPage;
|
||||
|
||||
beforeEach(() => {
|
||||
page = new AppPage();
|
||||
});
|
||||
|
||||
it('should display welcome message', () => {
|
||||
page.navigateTo();
|
||||
expect(page.getTitleText()).toEqual('buntspecht-frontent app is running!');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Assert that there are no errors emitted from the browser
|
||||
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
|
||||
expect(logs).not.toContain(jasmine.objectContaining({
|
||||
level: logging.Level.SEVERE,
|
||||
} as logging.Entry));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { browser, by, element } from 'protractor';
|
||||
|
||||
export class AppPage {
|
||||
navigateTo(): Promise<unknown> {
|
||||
return browser.get(browser.baseUrl) as Promise<unknown>;
|
||||
}
|
||||
|
||||
getTitleText(): Promise<string> {
|
||||
return element(by.css('app-root .content span')).getText() as Promise<string>;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/* To learn more about this file see: https://angular.io/config/tsconfig. */
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../out-tsc/e2e",
|
||||
"module": "commonjs",
|
||||
"target": "es2018",
|
||||
"types": [
|
||||
"jasmine",
|
||||
"jasminewd2",
|
||||
"node"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Karma configuration file, see link for more information
|
||||
// https://karma-runner.github.io/1.0/config/configuration-file.html
|
||||
|
||||
module.exports = function (config) {
|
||||
config.set({
|
||||
basePath: '',
|
||||
frameworks: ['jasmine', '@angular-devkit/build-angular'],
|
||||
plugins: [
|
||||
require('karma-jasmine'),
|
||||
require('karma-chrome-launcher'),
|
||||
require('karma-jasmine-html-reporter'),
|
||||
require('karma-coverage-istanbul-reporter'),
|
||||
require('@angular-devkit/build-angular/plugins/karma')
|
||||
],
|
||||
client: {
|
||||
clearContext: false // leave Jasmine Spec Runner output visible in browser
|
||||
},
|
||||
coverageIstanbulReporter: {
|
||||
dir: require('path').join(__dirname, './coverage/buntspecht-frontent'),
|
||||
reports: ['html', 'lcovonly', 'text-summary'],
|
||||
fixWebpackSourcePaths: true
|
||||
},
|
||||
reporters: ['progress', 'kjhtml'],
|
||||
port: 9876,
|
||||
colors: true,
|
||||
logLevel: config.LOG_INFO,
|
||||
autoWatch: true,
|
||||
browsers: ['Chrome'],
|
||||
singleRun: false,
|
||||
restartOnFileChange: true
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
|
||||
"index": "/index.html",
|
||||
"appData": {
|
||||
"version": "1.5.5"
|
||||
},
|
||||
"assetGroups": [
|
||||
{
|
||||
"name": "app",
|
||||
"installMode": "prefetch",
|
||||
"resources": {
|
||||
"files": [
|
||||
"/favicon.ico",
|
||||
"/index.html",
|
||||
"/manifest.webmanifest",
|
||||
"/*.css",
|
||||
"/*.js"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "assets",
|
||||
"installMode": "prefetch",
|
||||
"resources": {
|
||||
"files": [
|
||||
"/assets/**",
|
||||
"/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"dataGroups": [
|
||||
{
|
||||
"name": "api",
|
||||
"urls": [
|
||||
"/api"
|
||||
],
|
||||
"cacheConfig": {
|
||||
"maxSize": 0,
|
||||
"maxAge": "0u",
|
||||
"strategy": "freshness"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Generated
+14693
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "buntspecht-web",
|
||||
"version": "0.1.0",
|
||||
"license": "AGPL3",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"build": "ng build",
|
||||
"test": "ng test",
|
||||
"lint": "ng lint",
|
||||
"e2e": "ng e2e"
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "^18.2.7",
|
||||
"@angular/cdk": "^18.2.6",
|
||||
"@angular/common": "^18.2.7",
|
||||
"@angular/compiler": "^18.2.7",
|
||||
"@angular/core": "^18.2.7",
|
||||
"@angular/forms": "^18.2.7",
|
||||
"@angular/material": "^18.2.6",
|
||||
"@angular/material-moment-adapter": "^18.2.6",
|
||||
"@angular/platform-browser": "^18.2.7",
|
||||
"@angular/platform-browser-dynamic": "^18.2.7",
|
||||
"@angular/router": "^18.2.7",
|
||||
"@angular/service-worker": "^18.2.7",
|
||||
"moment": "^2.30.1",
|
||||
"rxjs": "~7.8.1",
|
||||
"tslib": "^2.7.0",
|
||||
"zone.js": "~0.14.10"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular-devkit/build-angular": "^18.2.7",
|
||||
"@angular/cli": "^18.2.7",
|
||||
"@angular/compiler-cli": "^18.2.7",
|
||||
"@angular/localize": "^18.2.7",
|
||||
"@types/jasmine": "^5.1.4",
|
||||
"jasmine-core": "~5.3.0",
|
||||
"karma": "^6.4.4",
|
||||
"karma-chrome-launcher": "~3.2.0",
|
||||
"karma-coverage": "~2.2.1",
|
||||
"karma-jasmine": "~5.1.0",
|
||||
"karma-jasmine-html-reporter": "^2.1.0",
|
||||
"typescript": "~5.5.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
RewriteEngine On
|
||||
|
||||
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
|
||||
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
|
||||
RewriteCond %{REQUEST_URI} !^/api/.*$
|
||||
RewriteRule ^ - [L]
|
||||
|
||||
RewriteRule ^ /index.html [L]
|
||||
@@ -0,0 +1,42 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { RouterModule, Routes } from '@angular/router';
|
||||
|
||||
import { AnonymousGuard, AuthAdminGuard, AuthenticatedGuard } from './auth/auth.guard';
|
||||
import { PageLogin } from './pages/login/login.page';
|
||||
import { PageNotFound } from './pages/notfound/notfound.page';
|
||||
import { PageProfile } from './pages/profile/profile.page';
|
||||
|
||||
import { PageManagement } from './pages/management/management.page';
|
||||
import { PagePassword } from './pages/password/password.page';
|
||||
import { PageTurnover } from './pages/turnover/turnover.page';
|
||||
import { PageTurnoversManage } from './pages/turnovers/manage/manage.page';
|
||||
import { PageTurnovers } from './pages/turnovers/turnovers.page';
|
||||
import { PageUnavailable } from './pages/unavailable/unavailable.page';
|
||||
import { PageUsers } from './pages/users/users.page';
|
||||
import { UiMain } from './ui/main/main.ui';
|
||||
|
||||
|
||||
const routes: Routes = [
|
||||
{ path: 'login', component: PageLogin, canActivate: [AnonymousGuard] },
|
||||
{
|
||||
path: '', component: UiMain, children: [
|
||||
{ path: '', component: PageTurnovers, canActivate: [AuthenticatedGuard] },
|
||||
{ path: 'password', component: PagePassword, canActivate: [AuthenticatedGuard] },
|
||||
{ path: 'profile', component: PageProfile, canActivate: [AuthenticatedGuard] },
|
||||
{ path: 'create', component: PageTurnover, canActivate: [AuthenticatedGuard] },
|
||||
{ path: 't/:id', component: PageTurnover, canActivate: [AuthenticatedGuard] },
|
||||
{ path: 't', component: PageTurnoversManage, canActivate: [AuthAdminGuard] },
|
||||
{ path: 'm', component: PageManagement, canActivate: [AuthAdminGuard] },
|
||||
{ path: 'u', component: PageUsers, canActivate: [AuthAdminGuard] },
|
||||
{ path: 'u/:username', component: PageProfile, canActivate: [AuthAdminGuard] },
|
||||
{ path: 'unavailable', component: PageUnavailable },
|
||||
{ path: '**', component: PageNotFound, pathMatch: 'full', canActivate: [AuthenticatedGuard] }
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
@NgModule({
|
||||
imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
|
||||
exports: [RouterModule]
|
||||
})
|
||||
export class AppRoutingModule { }
|
||||
@@ -0,0 +1 @@
|
||||
<router-outlet></router-outlet>
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
import { I18nService } from './services/i18n.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
templateUrl: './app.component.html'
|
||||
})
|
||||
|
||||
export class AppComponent {
|
||||
|
||||
constructor(private i18n: I18nService) {
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
window.document.title = this.i18n.get('buntspecht', []);
|
||||
|
||||
if (localStorage.getItem("buntspecht.darkTheme") == "true") {
|
||||
window.document.body.classList.add("dark-theme");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
|
||||
import { DatePipe } from '@angular/common';
|
||||
import { HTTP_INTERCEPTORS, HttpHandler, HttpInterceptor, HttpRequest, provideHttpClient } from '@angular/common/http';
|
||||
import { APP_INITIALIZER, Injectable, NgModule } from '@angular/core';
|
||||
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
|
||||
import { MAT_DATE_LOCALE } from '@angular/material/core';
|
||||
import { MatPaginatorIntl } from '@angular/material/paginator';
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
|
||||
import * as moment from 'moment';
|
||||
import { AppRoutingModule } from './app-routing.module';
|
||||
import { MaterialModule } from './material/material.module';
|
||||
|
||||
import { AutofocusDirective } from './material/autofocus';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
import { PageLogin } from './pages/login/login.page';
|
||||
import { PageNotFound } from './pages/notfound/notfound.page';
|
||||
import { PageProfile } from './pages/profile/profile.page';
|
||||
import { PageUnavailable } from './pages/unavailable/unavailable.page';
|
||||
import { UiMain } from './ui/main/main.ui';
|
||||
import { I18nEmptyPipe, I18nPipe } from './utils/i18n.pipe';
|
||||
import { MomentPipe } from './utils/moment.pipe';
|
||||
|
||||
import { ServiceWorkerModule } from '@angular/service-worker';
|
||||
import { environment } from '../environments/environment';
|
||||
import { PagePassword } from './pages/password/password.page';
|
||||
import { PageTurnover } from './pages/turnover/turnover.page';
|
||||
import { PageTurnoversManage } from './pages/turnovers/manage/manage.page';
|
||||
import { PageTurnovers } from './pages/turnovers/turnovers.page';
|
||||
import { PageUsers } from './pages/users/users.page';
|
||||
import { I18nPaginatorIntl, I18nService } from './services/i18n.service';
|
||||
import { UiTurnovers } from './ui/turnovers/turnovers.ui';
|
||||
import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field';
|
||||
import { ConfirmDialog } from './ui/confirm/confirm.component';
|
||||
import { PageManagement } from './pages/management/management.page';
|
||||
|
||||
|
||||
export function fetchI18n(i18n: I18nService) {
|
||||
return () => i18n.fetch();
|
||||
}
|
||||
|
||||
|
||||
export function setMaterialDate(i18n: I18nService) {
|
||||
let locale = i18n.getLocale();
|
||||
|
||||
if (locale == 'de-informal') {
|
||||
locale = 'de';
|
||||
}
|
||||
|
||||
moment.locale(locale);
|
||||
return locale;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class XhrInterceptor implements HttpInterceptor {
|
||||
|
||||
intercept(req: HttpRequest<any>, next: HttpHandler) {
|
||||
const xhr = req.clone({
|
||||
headers: req.headers.set('X-Requested-With', 'XMLHttpRequest').set('Content-Type', 'application/json;charset=UTF-8'), withCredentials: true
|
||||
});
|
||||
return next.handle(xhr);
|
||||
}
|
||||
}
|
||||
|
||||
@NgModule({
|
||||
declarations: [
|
||||
AutofocusDirective,
|
||||
I18nPipe,
|
||||
I18nEmptyPipe,
|
||||
MomentPipe,
|
||||
AppComponent,
|
||||
PageTurnovers,
|
||||
PageTurnoversManage,
|
||||
PageTurnover,
|
||||
PageLogin,
|
||||
PageManagement,
|
||||
PageNotFound,
|
||||
PagePassword,
|
||||
PageProfile,
|
||||
PageUnavailable,
|
||||
PageUsers,
|
||||
UiMain,
|
||||
UiTurnovers,
|
||||
ConfirmDialog
|
||||
],
|
||||
imports: [
|
||||
BrowserModule,
|
||||
AppRoutingModule,
|
||||
BrowserAnimationsModule,
|
||||
MaterialModule,
|
||||
FormsModule,
|
||||
ReactiveFormsModule,
|
||||
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production, registrationStrategy: 'registerWhenStable:30000' }),
|
||||
],
|
||||
exports: [MaterialModule],
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
{ provide: APP_INITIALIZER, useFactory: fetchI18n, deps: [I18nService], multi: true },
|
||||
{ provide: MAT_DATE_LOCALE, useFactory: setMaterialDate, deps: [I18nService], multi: true },
|
||||
{ provide: HTTP_INTERCEPTORS, useClass: XhrInterceptor, multi: true },
|
||||
DatePipe,
|
||||
{
|
||||
provide: MatPaginatorIntl, useFactory: (i18n: I18nService) => {
|
||||
const service = new I18nPaginatorIntl();
|
||||
service.injectI18n(i18n)
|
||||
return service;
|
||||
}, deps: [I18nService]
|
||||
},
|
||||
{
|
||||
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
|
||||
useValue: {
|
||||
subscriptSizing: 'dynamic'
|
||||
}
|
||||
}],
|
||||
bootstrap: [AppComponent],
|
||||
})
|
||||
export class AppModule {
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
|
||||
import { AuthService } from '../services/auth.service';
|
||||
import { RequestError } from '../services/requesterror';
|
||||
import { UserService } from '../services/user.service';
|
||||
import { I18nService } from '../services/i18n.service';
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthUpdateGuard implements CanActivate {
|
||||
constructor(private authService: AuthService) { }
|
||||
|
||||
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
|
||||
this.authService.getAuth().catch(function (error) { });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(private authService: AuthService, private router: Router) { }
|
||||
|
||||
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
|
||||
const that = this;
|
||||
return this.authService.getAuth().then(response => {
|
||||
return true;
|
||||
}).catch(function (error) {
|
||||
if (error instanceof RequestError && (error as RequestError).getResponse().status == 401) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return that.router.navigateByUrl(that.router.parseUrl('/unavailable?target=' + encodeURIComponent(state.url)), { skipLocationChange: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthenticatedGuard implements CanActivate {
|
||||
constructor(private authService: AuthService, private userService: UserService, private i18nService: I18nService, private router: Router) { }
|
||||
|
||||
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
|
||||
const that = this;
|
||||
return this.authService.getAuth().then((data: any) => {
|
||||
this.userService.get().subscribe({
|
||||
next: (user: any) => {
|
||||
let updateLocale = false;
|
||||
let updateTheme = false;
|
||||
let darktheme = 'false';
|
||||
|
||||
if (user.darkTheme) {
|
||||
darktheme = 'true';
|
||||
}
|
||||
|
||||
if (darktheme != localStorage.getItem("buntspecht.darkTheme")) {
|
||||
localStorage.setItem("buntspecht.darkTheme", darktheme);
|
||||
updateTheme = true;
|
||||
}
|
||||
|
||||
if (this.i18nService.locales.indexOf(user.locale) != -1 && localStorage.getItem("buntspecht.locale") != user.locale) {
|
||||
if (this.i18nService.locale != user.locale) {
|
||||
localStorage.setItem("buntspecht.locale", user.locale);
|
||||
updateLocale = true;
|
||||
}
|
||||
}
|
||||
if (updateLocale || updateTheme) {
|
||||
window.location.reload();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
}).catch(function (error) {
|
||||
if (error instanceof RequestError && (error as RequestError).getResponse().status == 401) {
|
||||
return that.router.navigateByUrl(that.router.parseUrl('/login?target=' + encodeURIComponent(state.url)));
|
||||
}
|
||||
|
||||
return that.router.navigateByUrl(that.router.parseUrl('/unavailable?target=' + encodeURIComponent(state.url)), { skipLocationChange: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthAdminGuard implements CanActivate {
|
||||
constructor(private authService: AuthService, private router: Router) { }
|
||||
|
||||
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
|
||||
const that = this;
|
||||
return this.authService.getAuth().then(data => {
|
||||
if (data.authorities && data.authorities.find((role) => role.authority == 'ROLE_ADMIN') != undefined) {
|
||||
return true;
|
||||
}
|
||||
return that.router.navigateByUrl(that.router.parseUrl('/not-found'), { skipLocationChange: true });
|
||||
}).catch(function (error) {
|
||||
if (error instanceof RequestError && (error as RequestError).getResponse().status == 401) {
|
||||
return that.router.navigateByUrl(that.router.parseUrl('/login?target=' + encodeURIComponent(state.url)));
|
||||
}
|
||||
|
||||
return that.router.navigateByUrl(that.router.parseUrl('/not-found'), { skipLocationChange: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AnonymousGuard implements CanActivate {
|
||||
constructor(private authService: AuthService, private router: Router) { }
|
||||
|
||||
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
|
||||
const that = this;
|
||||
return this.authService.getAuth().then((data: any) => {
|
||||
this.router.navigateByUrl('/');
|
||||
return false;
|
||||
}).catch(function (error) {
|
||||
if (error instanceof RequestError && (error as RequestError).getResponse().status == 401) {
|
||||
return true;
|
||||
}
|
||||
return that.router.navigateByUrl(that.router.parseUrl('/unavailable?target=' + encodeURIComponent(state.url)), { replaceUrl: true });
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Directive, ElementRef, OnInit } from '@angular/core';
|
||||
|
||||
@Directive({
|
||||
selector: '[matAutofocus]',
|
||||
})
|
||||
export class AutofocusDirective implements OnInit {
|
||||
|
||||
constructor(private element: ElementRef) { }
|
||||
|
||||
ngOnInit() {
|
||||
setTimeout(() => {
|
||||
this.element.nativeElement.focus();
|
||||
this.element.nativeElement.scrollIntoView();
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import {NgModule} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
|
||||
// Material Form Controls
|
||||
import {MatAutocompleteModule} from '@angular/material/autocomplete';
|
||||
import {MatCheckboxModule} from '@angular/material/checkbox';
|
||||
import {MatDatepickerModule} from '@angular/material/datepicker';
|
||||
import {MatFormFieldModule} from '@angular/material/form-field';
|
||||
import {MatInputModule} from '@angular/material/input';
|
||||
import {MatRadioModule} from '@angular/material/radio';
|
||||
import {MatSelectModule} from '@angular/material/select';
|
||||
import {MatSliderModule} from '@angular/material/slider';
|
||||
import {MatSlideToggleModule} from '@angular/material/slide-toggle';
|
||||
// Material Navigation
|
||||
import {MatMenuModule} from '@angular/material/menu';
|
||||
import {MatSidenavModule} from '@angular/material/sidenav';
|
||||
import {MatToolbarModule} from '@angular/material/toolbar';
|
||||
// Material Layout
|
||||
import {MatCardModule} from '@angular/material/card';
|
||||
import {MatDividerModule} from '@angular/material/divider';
|
||||
import {MatExpansionModule} from '@angular/material/expansion';
|
||||
import {MatGridListModule} from '@angular/material/grid-list';
|
||||
import {MatListModule} from '@angular/material/list';
|
||||
import {MatStepperModule} from '@angular/material/stepper';
|
||||
import {MatTabsModule} from '@angular/material/tabs';
|
||||
import {MatTreeModule} from '@angular/material/tree';
|
||||
// Material Buttons & Indicators
|
||||
import {MatButtonModule} from '@angular/material/button';
|
||||
import {MatButtonToggleModule} from '@angular/material/button-toggle';
|
||||
import {MatBadgeModule} from '@angular/material/badge';
|
||||
import {MatChipsModule} from '@angular/material/chips';
|
||||
import {MatIconModule} from '@angular/material/icon';
|
||||
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
|
||||
import {MatProgressBarModule} from '@angular/material/progress-bar';
|
||||
import {MatRippleModule} from '@angular/material/core';
|
||||
// Material Popups & Modals
|
||||
import {MatBottomSheetModule} from '@angular/material/bottom-sheet';
|
||||
import {MatDialogModule} from '@angular/material/dialog';
|
||||
import {MatSnackBarModule} from '@angular/material/snack-bar';
|
||||
import {MatTooltipModule} from '@angular/material/tooltip';
|
||||
// Material Data tables
|
||||
import {MatPaginatorModule} from '@angular/material/paginator';
|
||||
import {MatSortModule} from '@angular/material/sort';
|
||||
import {MatTableModule} from '@angular/material/table';
|
||||
import {MatMomentDateModule} from '@angular/material-moment-adapter';
|
||||
|
||||
@NgModule({
|
||||
declarations: [],
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatAutocompleteModule,
|
||||
MatCheckboxModule,
|
||||
MatDatepickerModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
MatRadioModule,
|
||||
MatSelectModule,
|
||||
MatSliderModule,
|
||||
MatSlideToggleModule,
|
||||
MatMenuModule,
|
||||
MatSidenavModule,
|
||||
MatToolbarModule,
|
||||
MatCardModule,
|
||||
MatDividerModule,
|
||||
MatExpansionModule,
|
||||
MatGridListModule,
|
||||
MatListModule,
|
||||
MatStepperModule,
|
||||
MatTabsModule,
|
||||
MatTreeModule,
|
||||
MatButtonModule,
|
||||
MatButtonToggleModule,
|
||||
MatBadgeModule,
|
||||
MatChipsModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatProgressBarModule,
|
||||
MatRippleModule,
|
||||
MatBottomSheetModule,
|
||||
MatDialogModule,
|
||||
MatSnackBarModule,
|
||||
MatTooltipModule,
|
||||
MatPaginatorModule,
|
||||
MatSortModule,
|
||||
MatTableModule,
|
||||
MatMomentDateModule
|
||||
],
|
||||
exports: [
|
||||
MatAutocompleteModule,
|
||||
MatCheckboxModule,
|
||||
MatDatepickerModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
MatRadioModule,
|
||||
MatSelectModule,
|
||||
MatSliderModule,
|
||||
MatSlideToggleModule,
|
||||
MatMenuModule,
|
||||
MatSidenavModule,
|
||||
MatToolbarModule,
|
||||
MatCardModule,
|
||||
MatDividerModule,
|
||||
MatExpansionModule,
|
||||
MatGridListModule,
|
||||
MatListModule,
|
||||
MatStepperModule,
|
||||
MatTabsModule,
|
||||
MatTreeModule,
|
||||
MatButtonModule,
|
||||
MatButtonToggleModule,
|
||||
MatBadgeModule,
|
||||
MatChipsModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatProgressBarModule,
|
||||
MatRippleModule,
|
||||
MatBottomSheetModule,
|
||||
MatDialogModule,
|
||||
MatSnackBarModule,
|
||||
MatTooltipModule,
|
||||
MatPaginatorModule,
|
||||
MatSortModule,
|
||||
MatTableModule
|
||||
]
|
||||
})
|
||||
export class MaterialModule {}
|
||||
@@ -0,0 +1,56 @@
|
||||
<div class="container">
|
||||
<div class="flex column fill center middle">
|
||||
<form action="{{apiUrl}}/login" method="POST" #loginForm class="box">
|
||||
<mat-card>
|
||||
<mat-card-content>
|
||||
<img class="logo" src="assets/images/banner.png">
|
||||
<h2>{{'login.internal' | i18n}}</h2>
|
||||
<mat-error *ngIf="loginInvalid">
|
||||
{{'login.invalid' | i18n}}
|
||||
</mat-error>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'login.username' | i18n}}</mat-label>
|
||||
<input id="username" name="username" matInput required matAutofocus [value]="username">
|
||||
<mat-error>
|
||||
{{'login.username.missing' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'login.password' | i18n}}</mat-label>
|
||||
<input id="password" name="password" matInput type="password" required>
|
||||
<mat-error>
|
||||
{{'login.password.invalid.hint' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
<mat-slide-toggle (change)="rememberMe.value = '' + $event.checked">
|
||||
{{'login.keepSession' | i18n}}
|
||||
</mat-slide-toggle>
|
||||
<input #rememberMe id="remember-me" name="remember-me" type="hidden">
|
||||
</mat-card-content>
|
||||
<mat-card-actions>
|
||||
<button type="submit" (click)="loginForm.submit()" mat-raised-button color="primary"
|
||||
[disabled]="loginForm.invalid">{{'login' |
|
||||
i18n}}<mat-icon style="font-size: 1em;">open_in_new
|
||||
</mat-icon></button>
|
||||
</mat-card-actions>
|
||||
</mat-card>
|
||||
</form>
|
||||
|
||||
<mat-card *ngIf="externals && externals.length > 0" class="box">
|
||||
<mat-card-content>
|
||||
<h2>{{'login.external' | i18n}}</h2>
|
||||
<mat-error *ngIf="externalLoginInvalid">
|
||||
{{'login.external.invalid' | i18n}}
|
||||
</mat-error>
|
||||
</mat-card-content>
|
||||
<mat-card-actions class="flex wrap">
|
||||
<a class="external-login" (click)="externalLogin(client)" *ngFor="let client of externals"
|
||||
mat-raised-button color="accent">{{'login.external.client' | i18n:('login.provider.' + client.id |
|
||||
i18n)}}</a>
|
||||
<mat-slide-toggle [(ngModel)]="autologin">
|
||||
{{'login.autologin' | i18n}}
|
||||
</mat-slide-toggle>
|
||||
</mat-card-actions>
|
||||
</mat-card>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,33 @@
|
||||
img.logo {
|
||||
width: 300px;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
mat-form-field,
|
||||
mat-slide-toggle {
|
||||
display: block;
|
||||
margin-bottom: 25px;
|
||||
}
|
||||
|
||||
a.external-login {
|
||||
margin: 15px 0;
|
||||
flex-basis: 100%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.box {
|
||||
margin: 5px;
|
||||
|
||||
@media screen and (min-width: 576px) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 768px) {
|
||||
max-width: 80%;
|
||||
margin: 15px;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 992px) {
|
||||
max-width: 50%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
|
||||
import { environment } from '../../../environments/environment';
|
||||
|
||||
import { AuthService } from '../../services/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'page-login',
|
||||
templateUrl: './login.page.html',
|
||||
styleUrls: ['./login.page.scss']
|
||||
})
|
||||
export class PageLogin implements OnInit {
|
||||
|
||||
@ViewChild('loginForm') loginForm: ElementRef;
|
||||
autologin: boolean = false;
|
||||
loginInvalid: boolean;
|
||||
externalLoginInvalid: boolean;
|
||||
apiUrl = environment.apiUrl;
|
||||
targetRoute: string;
|
||||
externals: any[];
|
||||
username: string = '';
|
||||
|
||||
constructor(
|
||||
private authService: AuthService,
|
||||
private router: Router,
|
||||
private route: ActivatedRoute) { }
|
||||
|
||||
async ngOnInit() {
|
||||
this.route.queryParams.subscribe({
|
||||
next: (params) => {
|
||||
if (params['target']) {
|
||||
this.targetRoute = params['target'];
|
||||
this.router.navigate([], { queryParams: { target: null }, queryParamsHandling: 'merge', replaceUrl: true });
|
||||
}
|
||||
if (params['error'] || params['error'] == '') {
|
||||
this.loginInvalid = true;
|
||||
this.router.navigate([], { queryParams: { error: null }, queryParamsHandling: 'merge', replaceUrl: true });
|
||||
}
|
||||
if (params['username']) {
|
||||
this.username = params['username'];
|
||||
this.router.navigate([], { queryParams: { username: null }, queryParamsHandling: 'merge', replaceUrl: true });
|
||||
}
|
||||
if (params['externalError'] || params['externalError'] == '') {
|
||||
this.externalLoginInvalid = true;
|
||||
this.router.navigate([], { queryParams: { externalError: null }, queryParamsHandling: 'merge', replaceUrl: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.authService.getExternal().subscribe({
|
||||
next: (data: any[]) => {
|
||||
this.externals = data;
|
||||
const autologinClient = localStorage.getItem("buntspecht.autologin");
|
||||
for (let client of this.externals) {
|
||||
if (client.id == autologinClient) {
|
||||
window.location.href = this.apiUrl + "/" + client.loginUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
ngAfterViewInit(): void {
|
||||
if (this.targetRoute) {
|
||||
this.loginForm.nativeElement.action = this.loginForm.nativeElement.action + "?forward=" + window.location.origin + encodeURIComponent(this.targetRoute);
|
||||
}
|
||||
}
|
||||
|
||||
externalLogin(client: any): void {
|
||||
if (this.autologin) {
|
||||
localStorage.setItem("buntspecht.autologin", client.id);
|
||||
} else {
|
||||
localStorage.removeItem("buntspecht.autologin");
|
||||
}
|
||||
|
||||
window.location.href = this.apiUrl + "/" + client.loginUrl;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<div class="flex column fill">
|
||||
@if (entries && entries.error) {
|
||||
<div class="flex column fill">
|
||||
<mat-card class="accent box">
|
||||
<mat-card-header>
|
||||
<mat-card-title>{{ 'management.error.' + entries.error.status | i18n}}</mat-card-title>
|
||||
<mat-card-subtitle>{{'management.error' | i18n}}</mat-card-subtitle>
|
||||
</mat-card-header>
|
||||
<mat-card-content>
|
||||
<p>
|
||||
{{ 'management.error.' + entries.error.status + '.text' | i18n}}
|
||||
</p>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="flex wrap filter-container">
|
||||
<form class="flex wrap filter">
|
||||
<mat-form-field class="margin">
|
||||
<mat-label>{{'management.filter.created' | i18n}}</mat-label>
|
||||
<mat-date-range-input [rangePicker]="picker">
|
||||
<input matStartDate placeholder="{{'turnovers.filter.created.from' | i18n}}"
|
||||
[value]="entries && entries.filter && entries.filter.from"
|
||||
(dateChange)="setFilter('from', $event.value && $event.value.toISOString() || undefined)">
|
||||
<input matEndDate placeholder="{{'turnovers.filter.created.to' | i18n}}"
|
||||
[value]="entries && entries.filter && entries.filter.to"
|
||||
(dateChange)="setFilter('to', $event.value && $event.value.endOf('day').toISOString() || undefined)">
|
||||
</mat-date-range-input>
|
||||
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
|
||||
<mat-date-range-picker #picker></mat-date-range-picker>
|
||||
</mat-form-field>
|
||||
|
||||
|
||||
<mat-form-field class="margin">
|
||||
<mat-label>{{'management.filter.username' | i18n}}</mat-label>
|
||||
<input type="text" matInput [matAutocomplete]="auto" [formControl]="usersFormControl"
|
||||
(change)="setInputFilter('username', $event.target)">
|
||||
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="setFilter('username', $event.option.value)">
|
||||
@for (user of users | async; track user.username) {
|
||||
<mat-option [value]="user.username">{{user.username}}</mat-option>
|
||||
}
|
||||
</mat-autocomplete>
|
||||
</mat-form-field>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@if (entries) {
|
||||
<div class="scroll-container">
|
||||
<table class="default-table" mat-table [dataSource]="entries.results || []" matSort
|
||||
(matSortChange)="applySort($event)" [matSortDisableClear]="true">
|
||||
<ng-container matColumnDef="username">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header [disableClear]="false">{{'user.username' |
|
||||
i18n}}
|
||||
</th>
|
||||
<td mat-cell *matCellDef="let entry">
|
||||
<div class="flex middle">
|
||||
{{entry[0]}}
|
||||
</div>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="price">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header>
|
||||
<span class="spacer"></span>
|
||||
<span>{{'turnover.price' | i18n}}</span>
|
||||
</th>
|
||||
<td mat-cell *matCellDef="let entry">
|
||||
<div class="flex">
|
||||
<span class="spacer"></span>
|
||||
<span>{{entry[1] | number: '1.2-2'}}</span>
|
||||
<span> {{'turnover.price.suffix' | i18n}}</span>
|
||||
</div>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="timeInvestment">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header>
|
||||
<span class="spacer"></span>
|
||||
<span>{{'turnover.timeInvestment' | i18n}}</span>
|
||||
</th>
|
||||
<td mat-cell *matCellDef="let entry">
|
||||
<div class="flex">
|
||||
<span class="spacer"></span>
|
||||
<span>{{entry[2] | number: '1.1-1'}}</span>
|
||||
<span> {{'turnover.timeInvestment.suffix' | i18n}}</span>
|
||||
</div>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
|
||||
<tr mat-header-row *matHeaderRowDef="columns; sticky: true"></tr>
|
||||
<tr class="entry" mat-row *matRowDef="let row; columns: columns;"></tr>
|
||||
</table>
|
||||
</div>
|
||||
@if (entries.total == 0) {
|
||||
<mat-list>
|
||||
<mat-list-item>
|
||||
<p>{{'paginator.empty' | i18n}}</p>
|
||||
</mat-list-item>
|
||||
</mat-list>
|
||||
}
|
||||
|
||||
<span class="spacer"></span>
|
||||
|
||||
<div class="mat-mdc-paginator flex">
|
||||
<span class="spacer"></span>
|
||||
<mat-paginator [pageSizeOptions]="pageSizeOptions" [pageIndex]="entries.offset / entries.limit"
|
||||
[length]="entries.total" [pageSize]="entries.limit" (page)="applyPage($event)" showFirstLastButtons>
|
||||
</mat-paginator>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!entries || !entries.results && !entries.error) {
|
||||
<mat-progress-bar *ngIf="" mode="indeterminate"></mat-progress-bar>
|
||||
}
|
||||
</div>
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Component, Input, OnInit } from '@angular/core';
|
||||
import { FormControl } from '@angular/forms';
|
||||
import { PageEvent } from '@angular/material/paginator';
|
||||
import { Sort } from '@angular/material/sort';
|
||||
import { debounceTime, Observable, switchMap } from 'rxjs';
|
||||
import { TurnoverManagementService } from 'src/app/services/turnover.management.service';
|
||||
import { UserManagementService } from 'src/app/services/user.management.service';
|
||||
|
||||
@Component({
|
||||
selector: 'ui-management',
|
||||
templateUrl: './management.page.html',
|
||||
styleUrls: ['./management.page.scss']
|
||||
})
|
||||
export class PageManagement implements OnInit {
|
||||
|
||||
@Input() entries: any;
|
||||
pageSizeOptions: number[] = [1, 2, 3, 4, 5, 10, 15, 30, 50, 100];
|
||||
sort: string = "username";
|
||||
descending: boolean = false;
|
||||
|
||||
columns: string[] = ['username', 'price', 'timeInvestment'];
|
||||
|
||||
|
||||
users: Observable<any>;
|
||||
usersFormControl = new FormControl();
|
||||
|
||||
constructor(
|
||||
private turnoverManagementService: TurnoverManagementService,
|
||||
private userManagementService: UserManagementService
|
||||
) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
this.entries = {};
|
||||
this.update();
|
||||
this.users = this.usersFormControl
|
||||
.valueChanges
|
||||
.pipe(
|
||||
debounceTime(300),
|
||||
switchMap(value => this.userManagementService.pick(value))
|
||||
);
|
||||
}
|
||||
|
||||
update() {
|
||||
const filter = JSON.parse(JSON.stringify(this.entries.filter || {}));
|
||||
this.turnoverManagementService.overview(this.entries.limit || 15, this.entries.offset || 0, this.sort, this.descending, filter).subscribe({
|
||||
next: (data: any) => {
|
||||
this.entries = data;
|
||||
this.entries.filter = filter;
|
||||
}, error: (error) => {
|
||||
this.entries = { error: error };
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
applyPage(event: PageEvent) {
|
||||
this.entries.limit = event.pageSize;
|
||||
this.entries.offset = event.pageSize * event.pageIndex;
|
||||
this.update();
|
||||
}
|
||||
|
||||
applySort(event: Sort) {
|
||||
this.sort = event.direction ? event.active : 'username';
|
||||
this.descending = event.direction !== 'asc';
|
||||
this.update();
|
||||
}
|
||||
|
||||
setInputFilter(key: string, target: EventTarget) {
|
||||
this.setFilter(key, (target as HTMLInputElement).value);
|
||||
}
|
||||
|
||||
setFilter(key: string, value) {
|
||||
if (value != this.entries.filter[key]) {
|
||||
this.entries.filter[key] = value;
|
||||
this.entries.offset = 0;
|
||||
this.update();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<div class="container">
|
||||
<div class="flex column fill center middle">
|
||||
<mat-card class="accent box">
|
||||
<mat-card-header>
|
||||
<mat-card-title>404</mat-card-title>
|
||||
<mat-card-subtitle>{{'not-found' | i18n}}</mat-card-subtitle>
|
||||
</mat-card-header>
|
||||
<mat-card-content>
|
||||
<p>
|
||||
{{'not-found.text' | i18n}}
|
||||
</p>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,17 @@
|
||||
.box {
|
||||
margin: 5px;
|
||||
min-width: 400px;
|
||||
|
||||
@media screen and (min-width: 576px) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 768px) {
|
||||
max-width: 80%;
|
||||
margin: 15px;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 992px) {
|
||||
max-width: 50%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'page-notfound',
|
||||
templateUrl: './notfound.page.html',
|
||||
styleUrls: [ './notfound.page.scss' ]
|
||||
})
|
||||
export class PageNotFound {
|
||||
|
||||
constructor() { }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<div class="flex column fill middle">
|
||||
<form [formGroup]="passwordForm" (ngSubmit)="setPassword()">
|
||||
<mat-card>
|
||||
<mat-card-content>
|
||||
<mat-card-title>{{'password' | i18n}}</mat-card-title>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'password.old' | i18n}}</mat-label>
|
||||
<input matInput formControlName="old" type="password">
|
||||
<mat-error *ngFor="let error of passwordForm.get('old').errors | keyvalue">
|
||||
{{'password.error.' + error.key | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'password.new' | i18n}}</mat-label>
|
||||
<input matInput formControlName="password" type="password">
|
||||
<mat-error *ngFor="let error of passwordForm.get('password').errors | keyvalue">
|
||||
{{'password.error.' + error.key | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'password.repeat' | i18n}}</mat-label>
|
||||
<input matInput formControlName="password2" type="password">
|
||||
<mat-error *ngFor="let error of passwordForm.get('password2').errors | keyvalue">
|
||||
{{'password.error.' + error.key | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
</mat-card-content>
|
||||
<mat-card-actions>
|
||||
<button type="submit" *ngIf="!working" mat-raised-button color="primary" [disabled]="passwordForm.invalid">
|
||||
{{'password.update' | i18n}}
|
||||
</button>
|
||||
<a *ngIf="passwordSuccess" mat-button color="primary">{{'password.success' | i18n}}</a>
|
||||
</mat-card-actions>
|
||||
</mat-card>
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1,22 @@
|
||||
mat-form-field {
|
||||
display: block;
|
||||
margin: 25px 0 !important;
|
||||
}
|
||||
|
||||
form {
|
||||
margin: 5px;
|
||||
min-width: 400px;
|
||||
|
||||
@media screen and (min-width: 576px) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 768px) {
|
||||
max-width: 80%;
|
||||
margin: 15px;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 992px) {
|
||||
max-width: 50%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { AbstractControlOptions, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
|
||||
import { UserService } from '../../services/user.service';
|
||||
import { MatchingValidator } from 'src/app/utils/matching.validator';
|
||||
|
||||
@Component({
|
||||
selector: 'page-password',
|
||||
templateUrl: './password.page.html',
|
||||
styleUrls: ['./password.page.scss']
|
||||
})
|
||||
export class PagePassword implements OnInit, OnDestroy {
|
||||
|
||||
auth: any;
|
||||
working: boolean = false;
|
||||
passwordSuccess: boolean = false;
|
||||
passwordForm: FormGroup;
|
||||
|
||||
constructor(
|
||||
private userService: UserService,
|
||||
private formBuilder: FormBuilder) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
this.passwordForm = this.formBuilder.group({
|
||||
old: ['', Validators.nullValidator],
|
||||
password: ['', Validators.nullValidator],
|
||||
password2: ['', Validators.nullValidator]
|
||||
}, {
|
||||
validator: MatchingValidator('password', 'password2')
|
||||
} as AbstractControlOptions);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
}
|
||||
|
||||
passwordHasError(controlName: string): boolean {
|
||||
return this.passwordForm.controls[controlName].errors != null;
|
||||
}
|
||||
|
||||
setPassword() {
|
||||
if (this.working) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.working = true;
|
||||
this.passwordSuccess = false;
|
||||
this.userService.setPassword(this.passwordForm.get('old').value, this.passwordForm.get('password').value, this.passwordForm.get('password2').value).subscribe({
|
||||
next: () => {
|
||||
this.working = false;
|
||||
this.passwordSuccess = true;
|
||||
},
|
||||
error: (error) => {
|
||||
this.working = false;
|
||||
if (error.status == 409) {
|
||||
let errors = {};
|
||||
for (let code of error.error) {
|
||||
errors[code.field] = errors[code.field] || {};
|
||||
errors[code.field][code.code] = true;
|
||||
}
|
||||
|
||||
for (let code in errors) {
|
||||
this.passwordForm.get(code).setErrors(errors[code]);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<div class="flex column fill middle">
|
||||
<form [formGroup]="profileForm" (ngSubmit)="saveProfile()" *ngIf="user">
|
||||
<mat-card>
|
||||
<mat-card-content>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'profile.username' | i18n}}</mat-label>
|
||||
<input matInput formControlName="username" type="name">
|
||||
</mat-form-field>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'profile.name' | i18n}}</mat-label>
|
||||
<input matInput formControlName="name" type="name">
|
||||
<mat-error *ngIf="profileHasError('name')">
|
||||
{{'profile.name.error' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'profile.email' | i18n}}</mat-label>
|
||||
<input matInput formControlName="email" type="email">
|
||||
<mat-error *ngIf="profileHasError('email')">
|
||||
{{'profile.email.error' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'profile.about' | i18n}}</mat-label>
|
||||
<textarea matAutosize matAutosizeMinRows="3" matInput formControlName="about"></textarea>
|
||||
<mat-error>
|
||||
{{'profile.about.error' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
@if (admin) {
|
||||
<mat-slide-toggle class="margin" [checked]="isAdmin" (change)="isAdmin=$event.checked">
|
||||
{{'user.admin' | i18n}}
|
||||
</mat-slide-toggle>
|
||||
}
|
||||
</mat-card-content>
|
||||
<mat-card-actions>
|
||||
<button type="submit" *ngIf="!working" mat-raised-button color="primary" [disabled]="profileForm.invalid">
|
||||
{{'profile.update' | i18n}}
|
||||
</button>
|
||||
<a *ngIf="profileSuccess" mat-button color="primary">{{'profile.success' | i18n}}</a>
|
||||
</mat-card-actions>
|
||||
</mat-card>
|
||||
</form>
|
||||
|
||||
@if(admin) {
|
||||
<form [formGroup]="passwordForm" (ngSubmit)="setPassword()">
|
||||
<mat-card>
|
||||
<mat-card-content>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'password.new' | i18n}}</mat-label>
|
||||
<input matInput formControlName="password" type="password">
|
||||
<mat-error *ngFor="let error of passwordForm.get('password').errors | keyvalue">
|
||||
{{'password.error.' + error.key | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'password.repeat' | i18n}}</mat-label>
|
||||
<input matInput formControlName="password2" type="password">
|
||||
<mat-error *ngFor="let error of passwordForm.get('password2').errors | keyvalue">
|
||||
{{'password.error.' + error.key | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
</mat-card-content>
|
||||
<mat-card-actions>
|
||||
<button type="submit" *ngIf="!working" mat-raised-button color="primary" [disabled]="passwordForm.invalid">
|
||||
{{'password.update' | i18n}}
|
||||
</button>
|
||||
<a *ngIf="passwordSuccess" mat-button color="primary">{{'password.success' | i18n}}</a>
|
||||
@if (admin && user && user.username) {
|
||||
<span class="spacer"></span>
|
||||
<a mat-raised-button color="warn" (click)="deleteUser()">
|
||||
<mat-icon>delete</mat-icon> {{'user.delete' | i18n}}
|
||||
</a>
|
||||
}
|
||||
</mat-card-actions>
|
||||
</mat-card>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
@@ -0,0 +1,23 @@
|
||||
mat-form-field,
|
||||
mat-slide-toggle {
|
||||
display: block;
|
||||
margin: 25px 0 !important;
|
||||
}
|
||||
|
||||
form {
|
||||
margin: 5px;
|
||||
min-width: 400px;
|
||||
|
||||
@media screen and (min-width: 576px) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 768px) {
|
||||
max-width: 80%;
|
||||
margin: 15px;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 992px) {
|
||||
max-width: 50%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { AbstractControlOptions, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
|
||||
import { UserService } from '../../services/user.service';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { UserManagementService } from 'src/app/services/user.management.service';
|
||||
import { MatchingValidator } from 'src/app/utils/matching.validator';
|
||||
import { ConfirmDialog } from 'src/app/ui/confirm/confirm.component';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
|
||||
@Component({
|
||||
selector: 'page-profile',
|
||||
templateUrl: './profile.page.html',
|
||||
styleUrls: ['./profile.page.scss']
|
||||
})
|
||||
export class PageProfile implements OnInit, OnDestroy {
|
||||
|
||||
auth: any;
|
||||
user: any;
|
||||
working: boolean = false;
|
||||
profileSuccess: boolean = false;
|
||||
profileForm: FormGroup;
|
||||
passwordSuccess: boolean = false;
|
||||
passwordForm: FormGroup;
|
||||
admin: boolean = false;
|
||||
isAdmin: boolean = false;
|
||||
|
||||
constructor(
|
||||
private userService: UserService,
|
||||
private userManagementService: UserManagementService,
|
||||
private formBuilder: FormBuilder,
|
||||
private router: Router,
|
||||
private route: ActivatedRoute,
|
||||
public dialog: MatDialog) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
this.profileForm = this.formBuilder.group({
|
||||
username: [{ disabled: true }, Validators.nullValidator],
|
||||
email: ['', Validators.nullValidator],
|
||||
name: ['', Validators.nullValidator],
|
||||
about: ['', Validators.nullValidator]
|
||||
});
|
||||
|
||||
this.passwordForm = this.formBuilder.group({
|
||||
password: ['', Validators.nullValidator],
|
||||
password2: ['', Validators.nullValidator]
|
||||
}, {
|
||||
validator: MatchingValidator('password', 'password2')
|
||||
} as AbstractControlOptions);
|
||||
|
||||
this.profileForm.get('username').disable();
|
||||
|
||||
let userFetch = this.userService.get();
|
||||
if (this.route.snapshot.paramMap.has('username')) {
|
||||
this.admin = true;
|
||||
userFetch = this.userManagementService.get(this.route.snapshot.paramMap.get('username'));
|
||||
}
|
||||
|
||||
userFetch.subscribe({
|
||||
next: (user) => {
|
||||
this.user = user;
|
||||
this.isAdmin = this.user.roles && this.user.roles.indexOf('ROLE_ADMIN') != -1;
|
||||
this.profileForm.get('username').setValue(this.user.username);
|
||||
this.profileForm.get('name').setValue(this.user.name);
|
||||
this.profileForm.get('email').setValue(this.user.email);
|
||||
this.profileForm.get('about').setValue(this.user.about);
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
}
|
||||
|
||||
profileHasError(controlName: string): boolean {
|
||||
return this.profileForm.controls[controlName].errors != null;
|
||||
}
|
||||
|
||||
saveProfile(): void {
|
||||
if (this.working) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.working = true;
|
||||
this.profileSuccess = false;
|
||||
|
||||
this.user.about = this.profileForm.get('about').value;
|
||||
this.user.email = this.profileForm.get('email').value;
|
||||
this.user.name = this.profileForm.get('name').value;
|
||||
|
||||
if (this.isAdmin && (!this.user.roles || this.user.roles.indexOf('ROLE_ADMIN') == -1)) {
|
||||
this.user.roles = this.user.roles || [];
|
||||
this.user.roles.push('ROLE_ADMIN');
|
||||
} else if (!this.isAdmin && this.user.roles && this.user.roles.indexOf('ROLE_ADMIN') != -1) {
|
||||
this.user.roles.splice(this.user.roles.indexOf('ROLE_ADMIN'), 1);
|
||||
}
|
||||
|
||||
const create = this.admin ? this.userManagementService.update(this.user) : this.userService.update(this.user);
|
||||
|
||||
create.subscribe({
|
||||
next: (data) => {
|
||||
this.user = data;
|
||||
this.isAdmin = this.user.roles && this.user.roles.indexOf('ROLE_ADMIN') != -1;
|
||||
this.working = false;
|
||||
this.profileSuccess = true;
|
||||
},
|
||||
error: (error) => {
|
||||
this.working = false;
|
||||
if (error.status == 422) {
|
||||
let errors = {};
|
||||
for (let code of error.error) {
|
||||
errors[code.field] = errors[code.field] || {};
|
||||
errors[code.field][code.code] = true;
|
||||
}
|
||||
|
||||
for (let code in errors) {
|
||||
this.profileForm.get(code).setErrors(errors[code]);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
setPassword() {
|
||||
if (this.working) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.working = true;
|
||||
this.passwordSuccess = false;
|
||||
this.userManagementService.setPassword(this.user.username, this.passwordForm.get('password').value).subscribe({
|
||||
next: () => {
|
||||
this.working = false;
|
||||
this.passwordSuccess = true;
|
||||
},
|
||||
error: (error) => {
|
||||
this.working = false;
|
||||
if (error.status == 409) {
|
||||
let errors = {};
|
||||
for (let code of error.error) {
|
||||
errors[code.field] = errors[code.field] || {};
|
||||
errors[code.field][code.code] = true;
|
||||
}
|
||||
|
||||
for (let code in errors) {
|
||||
this.passwordForm.get(code).setErrors(errors[code]);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
deleteUser() {
|
||||
const dialogRef = this.dialog.open(ConfirmDialog, {
|
||||
data: {
|
||||
'label': 'user.confirmDelete',
|
||||
'args': [this.user.username]
|
||||
}
|
||||
})
|
||||
|
||||
dialogRef.afterClosed().subscribe({
|
||||
next: (result) => {
|
||||
if (result) {
|
||||
this.userManagementService.deleteUser(this.user.username).subscribe({
|
||||
next: () => {
|
||||
this.router.navigateByUrl('/');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<div class="flex column fill middle">
|
||||
@if (!turnover) {
|
||||
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
|
||||
}
|
||||
@if (turnover) {
|
||||
<form [formGroup]="form" (ngSubmit)="turnover.id ? update() : create()" #formDirective="ngForm">
|
||||
<mat-card>
|
||||
<mat-card-content>
|
||||
<div class="flex space-between">
|
||||
<p>{{ (turnover.id ? 'turnover.edit' : 'turnover.info') | i18n}}</p>
|
||||
@if (turnover.created) {
|
||||
<span>{{(turnover.username == username ? 'turnover.created.label' : 'turnover.created.label.username') |
|
||||
i18n:(turnover.created | datef:'LLL' ):turnover.username}}</span>
|
||||
}
|
||||
</div>
|
||||
<mat-form-field>
|
||||
<mat-label>{{'turnover.customer' | i18n}}</mat-label>
|
||||
<input matInput formControlName="customer" type="text" [required]="true">
|
||||
<mat-error *ngIf="hasError('customer')">
|
||||
{{'turnover.customer.error' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field>
|
||||
<mat-label>{{'turnover.motif' | i18n}}</mat-label>
|
||||
<input matInput formControlName="motif" type="text" [required]="true">
|
||||
<mat-error *ngIf="hasError('motif')">
|
||||
{{'turnover.motif.error' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field>
|
||||
<mat-label>{{'turnover.price' | i18n}}</mat-label>
|
||||
<input matInput formControlName="price" type="number" min="0" step="0.01" [required]="true">
|
||||
<span matTextSuffix>{{'turnover.price.suffix' | i18n}}</span>
|
||||
<mat-error *ngIf="hasError('price')">
|
||||
{{'turnover.price.error' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field>
|
||||
<mat-label>{{'turnover.timeInvestment' | i18n}}</mat-label>
|
||||
<input matInput formControlName="timeInvestment" type="number" min="0" step="0.1">
|
||||
<span matTextSuffix>{{'turnover.timeInvestment.suffix' | i18n}}</span>
|
||||
<mat-error *ngIf="hasError('timeInvestment')">
|
||||
{{'turnover.timeInvestment.error' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field>
|
||||
<mat-label>{{'turnover.remark' | i18n}}</mat-label>
|
||||
<textarea matAutosize matAutosizeMinRows="3" matInput formControlName="remark"></textarea>
|
||||
<mat-error *ngIf="hasError('remark')">
|
||||
{{'turnover.remark.error' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field>
|
||||
<mat-label>{{'turnover.materialConsumption' | i18n}}</mat-label>
|
||||
<textarea matAutosize matAutosizeMinRows="3" matInput formControlName="materialConsumption"></textarea>
|
||||
<mat-error *ngIf="hasError('materialConsumption')">
|
||||
{{'turnover.materialConsumption.error' | i18n}}
|
||||
</mat-error>
|
||||
</mat-form-field>
|
||||
|
||||
</mat-card-content>
|
||||
<mat-card-actions>
|
||||
@if (!working) {
|
||||
<button type="submit" mat-raised-button color="primary" [disabled]="form.invalid">
|
||||
{{(turnover.id ? 'turnover.update' : 'turnover.create') | i18n}}
|
||||
</button>
|
||||
}
|
||||
@if (turnover.updated && turnover.updated != turnover.created) {
|
||||
<span class="margin">{{'turnover.updated.label' | i18n:(turnover.updated | datef:'LLL' )}}</span>
|
||||
}
|
||||
@if (success) {
|
||||
<a mat-button color="primary" disabled="true">{{'turnover.success' | i18n}}</a>
|
||||
}
|
||||
@if (admin && turnover.id) {
|
||||
<span class="spacer"></span>
|
||||
<a mat-raised-button color="warn" (click)="deleteTurnover()">
|
||||
<mat-icon>delete</mat-icon> {{'turnover.delete' | i18n}}
|
||||
</a>
|
||||
}
|
||||
</mat-card-actions>
|
||||
</mat-card>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
@@ -0,0 +1,27 @@
|
||||
mat-form-field {
|
||||
display: block;
|
||||
margin: 25px 0 !important;
|
||||
}
|
||||
|
||||
mat-chip mat-icon.mat-icon-inline {
|
||||
margin-top: -12px;
|
||||
margin-right: -2px;
|
||||
}
|
||||
|
||||
form {
|
||||
margin: 5px;
|
||||
min-width: 400px;
|
||||
|
||||
@media screen and (min-width: 576px) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 768px) {
|
||||
max-width: 80%;
|
||||
margin: 15px;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 992px) {
|
||||
max-width: 50%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { AuthService } from 'src/app/services/auth.service';
|
||||
import { TurnoverManagementService } from 'src/app/services/turnover.management.service';
|
||||
import { TurnoverService } from 'src/app/services/turnover.service';
|
||||
import { ConfirmDialog } from 'src/app/ui/confirm/confirm.component';
|
||||
|
||||
@Component({
|
||||
selector: 'page-turnover',
|
||||
templateUrl: './turnover.page.html',
|
||||
styleUrls: ['./turnover.page.scss']
|
||||
})
|
||||
export class PageTurnover implements OnInit {
|
||||
|
||||
id: number;
|
||||
turnover: any;
|
||||
notfound: boolean = false;
|
||||
working: boolean = false;
|
||||
success: boolean = false;
|
||||
form: FormGroup;
|
||||
username: string = "";
|
||||
admin: boolean = false;
|
||||
|
||||
constructor(
|
||||
private turnoverService: TurnoverService,
|
||||
private turnoverManagementService: TurnoverManagementService,
|
||||
private authService: AuthService,
|
||||
private formBuilder: FormBuilder,
|
||||
private router: Router,
|
||||
private route: ActivatedRoute,
|
||||
private snackBar: MatSnackBar,
|
||||
private dialog: MatDialog) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
this.form = this.formBuilder.group({
|
||||
customer: ['', Validators.required],
|
||||
motif: ['', Validators.required],
|
||||
price: ['', Validators.required],
|
||||
timeInvestment: ['', Validators.nullValidator],
|
||||
remark: ['', Validators.nullValidator],
|
||||
materialConsumption: ['', Validators.nullValidator],
|
||||
});
|
||||
|
||||
this.id = this.route.snapshot.paramMap.get('id') && +this.route.snapshot.paramMap.get('id');
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
refresh() {
|
||||
if (this.id) {
|
||||
let request = this.turnoverService.get(this.id);
|
||||
|
||||
this.authService.auth.subscribe({
|
||||
next: (auth) => {
|
||||
this.username = auth.username;
|
||||
this.admin = auth.authorities && auth.authorities.find((role) => role.authority == 'ROLE_ADMIN') != undefined;
|
||||
|
||||
if (this.admin) {
|
||||
request = this.turnoverManagementService.get(this.id);
|
||||
}
|
||||
|
||||
request.subscribe({
|
||||
next: (data) => {
|
||||
this.turnover = data;
|
||||
this.form.get("customer").setValue(this.turnover.customer);
|
||||
this.form.get("motif").setValue(this.turnover.motif);
|
||||
this.form.get("price").setValue(this.turnover.price);
|
||||
this.form.get("timeInvestment").setValue(this.turnover.timeInvestment);
|
||||
this.form.get("remark").setValue(this.turnover.remark);
|
||||
this.form.get("materialConsumption").setValue(this.turnover.materialConsumption);
|
||||
|
||||
},
|
||||
error: (error) => {
|
||||
if (error.status == 404) {
|
||||
this.notfound = true;
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
},
|
||||
error: (error) => {
|
||||
this.username = ""
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
} else {
|
||||
this.turnover = {};
|
||||
}
|
||||
}
|
||||
|
||||
hasError(controlName: string): boolean {
|
||||
return this.form.controls[controlName].errors != null;
|
||||
}
|
||||
|
||||
create(): void {
|
||||
if (this.working) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.working = true;
|
||||
|
||||
this.turnover.customer = this.form.get("customer").value;
|
||||
this.turnover.motif = this.form.get("motif").value;
|
||||
this.turnover.price = this.form.get("price").value;
|
||||
this.turnover.timeInvestment = this.form.get("timeInvestment").value;
|
||||
this.turnover.remark = this.form.get("remark").value;
|
||||
this.turnover.materialConsumption = this.form.get("materialConsumption").value;
|
||||
|
||||
this.turnoverService.create(this.turnover).subscribe({
|
||||
next: (data) => {
|
||||
this.router.navigateByUrl('/');
|
||||
},
|
||||
error: (error) => {
|
||||
this.working = false;
|
||||
if (error.status == 422) {
|
||||
let errors = {};
|
||||
for (let code of error.error) {
|
||||
errors[code.field] = errors[code.field] || {};
|
||||
errors[code.field][code.code] = true;
|
||||
}
|
||||
|
||||
for (let code in errors) {
|
||||
this.form.get(code).setErrors(errors[code]);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
update(): void {
|
||||
if (this.working) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.working = true;
|
||||
this.turnover.customer = this.form.get("customer").value;
|
||||
this.turnover.motif = this.form.get("motif").value;
|
||||
this.turnover.price = this.form.get("price").value;
|
||||
this.turnover.timeInvestment = this.form.get("timeInvestment").value;
|
||||
this.turnover.remark = this.form.get("remark").value;
|
||||
this.turnover.materialConsumption = this.form.get("materialConsumption").value;
|
||||
|
||||
const request = this.admin ? this.turnoverManagementService.update(this.turnover) : this.turnoverService.update(this.turnover);
|
||||
|
||||
request.subscribe({
|
||||
next: (data) => {
|
||||
this.turnover = data;
|
||||
this.working = false;
|
||||
this.success = true;
|
||||
},
|
||||
error: (error) => {
|
||||
this.working = false;
|
||||
if (error.status == 403) {
|
||||
this.snackBar.open("Error");
|
||||
}
|
||||
if (error.status == 422) {
|
||||
let errors = {};
|
||||
for (let code of error.error) {
|
||||
errors[code.field] = errors[code.field] || {};
|
||||
errors[code.field][code.code] = true;
|
||||
}
|
||||
|
||||
for (let code in errors) {
|
||||
this.form.get(code).setErrors(errors[code]);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
deleteTurnover() {
|
||||
const dialogRef = this.dialog.open(ConfirmDialog, {
|
||||
data: {
|
||||
'label': 'turnover.confirmDelete',
|
||||
'args': [this.turnover.username]
|
||||
}
|
||||
})
|
||||
|
||||
dialogRef.afterClosed().subscribe({
|
||||
next: (result) => {
|
||||
if (result) {
|
||||
this.turnoverManagementService.delete(this.turnover.id).subscribe({
|
||||
next: () => {
|
||||
this.router.navigateByUrl('/');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<div class="flex column fill">
|
||||
<div class="flex wrap filter-container">
|
||||
<a mat-icon-button (click)="filterOpen=!filterOpen" title="{{'turnovers.filter' | i18n}}"
|
||||
[color]="filterOpen ? 'primary': 'accent'">
|
||||
<mat-icon>filter_alt</mat-icon>
|
||||
</a>
|
||||
|
||||
<form class="flex wrap filter" *ngIf="filterOpen">
|
||||
<mat-form-field class="margin">
|
||||
<mat-label>{{'turnovers.filter.created' | i18n}}</mat-label>
|
||||
<mat-date-range-input [rangePicker]="picker">
|
||||
<input matStartDate placeholder="{{'turnovers.filter.created.from' | i18n}}"
|
||||
[value]="turnovers && turnovers.filter && turnovers.filter.from"
|
||||
(dateChange)="setFilter('from', $event.value && $event.value.toISOString() || undefined)">
|
||||
<input matEndDate placeholder="{{'turnovers.filter.created.to' | i18n}}"
|
||||
[value]="turnovers && turnovers.filter && turnovers.filter.to"
|
||||
(dateChange)="setFilter('to', $event.value && $event.value.endOf('day').toISOString() || undefined)">
|
||||
</mat-date-range-input>
|
||||
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
|
||||
<mat-date-range-picker #picker></mat-date-range-picker>
|
||||
</mat-form-field>
|
||||
|
||||
|
||||
<mat-form-field class="margin">
|
||||
<mat-label>{{'turnovers.filter.username' | i18n}}</mat-label>
|
||||
<input type="text" matInput [matAutocomplete]="auto" [formControl]="usersFormControl"
|
||||
(change)="setInputFilter('username', $event.target)">
|
||||
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="setFilter('username', $event.option.value)">
|
||||
@for (user of users | async; track user.username) {
|
||||
<mat-option [value]="user.username">{{user.username}}</mat-option>
|
||||
}
|
||||
</mat-autocomplete>
|
||||
</mat-form-field>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<ui-turnovers class="flex column grow" [turnovers]="turnovers" (page)="applyPage($event)" (sort)="applySort($event)"
|
||||
[username]="true"></ui-turnovers>
|
||||
</div>
|
||||
@@ -0,0 +1,22 @@
|
||||
.filter-container {
|
||||
padding-left: 15px;
|
||||
justify-content: flex-start;
|
||||
align-items: center;
|
||||
|
||||
.filter {
|
||||
|
||||
justify-content: flex-start;
|
||||
align-items: center;
|
||||
max-height: 70px;
|
||||
|
||||
&>* {
|
||||
margin-top: 5px;
|
||||
margin-bottom: 5px;
|
||||
margin-left: 15px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ui-turnovers {
|
||||
min-height: 0;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { FormControl } from '@angular/forms';
|
||||
import { PageEvent } from '@angular/material/paginator';
|
||||
import { Sort } from '@angular/material/sort';
|
||||
import { debounceTime, Observable, switchMap } from 'rxjs';
|
||||
import { TurnoverManagementService } from 'src/app/services/turnover.management.service';
|
||||
import { UserManagementService } from 'src/app/services/user.management.service';
|
||||
|
||||
@Component({
|
||||
selector: 'page-turnovers-manage',
|
||||
templateUrl: './manage.page.html',
|
||||
styleUrls: ['./manage.page.scss']
|
||||
})
|
||||
export class PageTurnoversManage implements OnInit {
|
||||
|
||||
turnovers: any;
|
||||
sort: string = "created";
|
||||
descending: boolean = true;
|
||||
filterOpen: boolean = false;
|
||||
|
||||
users: Observable<any>;
|
||||
usersFormControl = new FormControl();
|
||||
|
||||
constructor(
|
||||
private turnoverManagementService: TurnoverManagementService,
|
||||
private userManagementService: UserManagementService
|
||||
) { }
|
||||
|
||||
|
||||
ngOnInit(): void {
|
||||
this.turnovers = {};
|
||||
this.update();
|
||||
this.users = this.usersFormControl
|
||||
.valueChanges
|
||||
.pipe(
|
||||
debounceTime(300),
|
||||
switchMap(value => this.userManagementService.pick(value))
|
||||
);
|
||||
}
|
||||
|
||||
update() {
|
||||
const filter = JSON.parse(JSON.stringify(this.turnovers.filter || {}));
|
||||
this.turnoverManagementService.fetch(this.turnovers.limit || 15, this.turnovers.offset || 0, this.sort, this.descending, this.turnovers.filter).subscribe({
|
||||
next: (data: any) => {
|
||||
this.turnovers = data;
|
||||
this.turnovers.filter = filter;
|
||||
}, error: (error) => {
|
||||
this.turnovers = { error: error };
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
applyPage(event: PageEvent) {
|
||||
this.turnovers.limit = event.pageSize;
|
||||
this.turnovers.offset = event.pageSize * event.pageIndex;
|
||||
this.update();
|
||||
}
|
||||
|
||||
applySort(event: Sort) {
|
||||
this.sort = event.direction ? event.active : 'created';
|
||||
this.descending = event.direction !== 'asc';
|
||||
this.update();
|
||||
}
|
||||
|
||||
setInputFilter(key: string, target: EventTarget) {
|
||||
this.setFilter(key, (target as HTMLInputElement).value);
|
||||
}
|
||||
|
||||
setFilter(key: string, value) {
|
||||
if (value != this.turnovers.filter[key]) {
|
||||
this.turnovers.filter[key] = value;
|
||||
this.turnovers.offset = 0;
|
||||
this.update();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<div class="flex column fill">
|
||||
<div class="flex wrap filter-container">
|
||||
<a mat-icon-button (click)="filterOpen=!filterOpen" title="{{'turnovers.filter' | i18n}}"
|
||||
[color]="filterOpen ? 'primary': 'accent'">
|
||||
<mat-icon>filter_alt</mat-icon>
|
||||
</a>
|
||||
|
||||
<form class="flex wrap filter" *ngIf="filterOpen">
|
||||
<mat-form-field class="margin">
|
||||
<mat-label>{{'turnovers.filter.created' | i18n}}</mat-label>
|
||||
<mat-date-range-input [rangePicker]="picker">
|
||||
<input matStartDate placeholder="{{'turnovers.filter.created.from' | i18n}}"
|
||||
[value]="turnovers && turnovers.filter && turnovers.filter.from"
|
||||
(dateChange)="setFilter('from', $event.value && $event.value.toISOString() || undefined)">
|
||||
<input matEndDate placeholder="{{'turnovers.filter.created.to' | i18n}}"
|
||||
[value]="turnovers && turnovers.filter && turnovers.filter.to"
|
||||
(dateChange)="setFilter('to', $event.value && $event.value.endOf('day').toISOString() || undefined)">
|
||||
</mat-date-range-input>
|
||||
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
|
||||
<mat-date-range-picker #picker></mat-date-range-picker>
|
||||
</mat-form-field>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<ui-turnovers class="flex column grow" [turnovers]="turnovers" (page)="applyPage($event)"
|
||||
(sort)="applySort($event)"></ui-turnovers>
|
||||
</div>
|
||||
@@ -0,0 +1,23 @@
|
||||
.filter-container {
|
||||
padding-left: 15px;
|
||||
justify-content: flex-start;
|
||||
align-items: center;
|
||||
|
||||
.filter {
|
||||
|
||||
justify-content: flex-start;
|
||||
align-items: center;
|
||||
max-height: 70px;
|
||||
|
||||
&>* {
|
||||
margin-top: 5px;
|
||||
margin-bottom: 5px;
|
||||
margin-left: 15px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
ui-turnovers {
|
||||
min-height: 0;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { FormControl } from '@angular/forms';
|
||||
import { PageEvent } from '@angular/material/paginator';
|
||||
import { Sort } from '@angular/material/sort';
|
||||
import { debounceTime, Observable, switchMap } from 'rxjs';
|
||||
import { TurnoverService } from 'src/app/services/turnover.service';
|
||||
import { UserManagementService } from 'src/app/services/user.management.service';
|
||||
|
||||
@Component({
|
||||
selector: 'page-turnovers',
|
||||
templateUrl: './turnovers.page.html',
|
||||
styleUrls: ['./turnovers.page.scss']
|
||||
})
|
||||
export class PageTurnovers implements OnInit {
|
||||
|
||||
turnovers: any;
|
||||
sort: string = "created";
|
||||
descending: boolean = true;
|
||||
filterOpen: boolean = false;
|
||||
|
||||
users: Observable<any>;
|
||||
usersFormControl = new FormControl();
|
||||
|
||||
constructor(
|
||||
private turnoverService: TurnoverService
|
||||
) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
this.turnovers = {};
|
||||
this.update();
|
||||
}
|
||||
|
||||
update() {
|
||||
const filter = JSON.parse(JSON.stringify(this.turnovers.filter || {}));
|
||||
this.turnoverService.fetch(this.turnovers.limit || 15, this.turnovers.offset || 0, this.sort, this.descending, this.turnovers.filter).subscribe({
|
||||
next: (data: any) => {
|
||||
this.turnovers = data;
|
||||
this.turnovers.filter = filter;
|
||||
}, error: (error) => {
|
||||
this.turnovers = { error: error };
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
applyPage(event: PageEvent) {
|
||||
this.turnovers.limit = event.pageSize;
|
||||
this.turnovers.offset = event.pageSize * event.pageIndex;
|
||||
this.update();
|
||||
}
|
||||
|
||||
applySort(event: Sort) {
|
||||
this.sort = event.direction ? event.active : 'created';
|
||||
this.descending = event.direction !== 'asc';
|
||||
this.update();
|
||||
}
|
||||
|
||||
setFilter(key: string, value) {
|
||||
if (value != this.turnovers.filter[key]) {
|
||||
this.turnovers.filter[key] = value;
|
||||
this.turnovers.offset = 0;
|
||||
this.update();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<div class="container">
|
||||
<div class="flex column fill center middle">
|
||||
<mat-card class="warn box">
|
||||
<mat-card-header>
|
||||
<mat-card-title>503</mat-card-title>
|
||||
<mat-card-subtitle>{{'service-unavailable' | i18n}}</mat-card-subtitle>
|
||||
</mat-card-header>
|
||||
<mat-card-content>
|
||||
<p>
|
||||
{{'service-unavailable.text' | i18n}}
|
||||
</p>
|
||||
</mat-card-content>
|
||||
<mat-card-actions>
|
||||
<a mat-raised-button color="primary" (click)="retry()">
|
||||
{{'service-unavailable.retry' | i18n}}
|
||||
</a>
|
||||
</mat-card-actions>
|
||||
</mat-card>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,17 @@
|
||||
.box {
|
||||
margin: 5px;
|
||||
min-width: 400px;
|
||||
|
||||
@media screen and (min-width: 576px) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 768px) {
|
||||
max-width: 80%;
|
||||
margin: 15px;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 992px) {
|
||||
max-width: 50%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Location } from '@angular/common'
|
||||
import { Router, ActivatedRoute } from '@angular/router';
|
||||
|
||||
@Component({
|
||||
selector: 'page-unavailable',
|
||||
templateUrl: './unavailable.page.html',
|
||||
styleUrls: ['./unavailable.page.scss']
|
||||
})
|
||||
export class PageUnavailable implements OnInit {
|
||||
|
||||
targetRoute = '';
|
||||
|
||||
constructor(
|
||||
private location: Location,
|
||||
private router: Router,
|
||||
private route: ActivatedRoute) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
this.route.queryParams.subscribe({
|
||||
next: (params) => {
|
||||
if (params['target']) {
|
||||
this.targetRoute = params['target'];
|
||||
this.router.navigate([], { queryParams: { target: null }, queryParamsHandling: 'merge', skipLocationChange: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
retry() {
|
||||
if (!this.targetRoute || this.targetRoute === "unavailable" || this.targetRoute === "/unavailable") {
|
||||
this.location.back;
|
||||
} else {
|
||||
this.router.navigate([this.targetRoute]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
@if (users && users.error) {
|
||||
<div class="flex column fill">
|
||||
<mat-card class="accent box">
|
||||
<mat-card-header>
|
||||
<mat-card-title>{{ 'users.error.' + users.error.status | i18n}}</mat-card-title>
|
||||
<mat-card-subtitle>{{'users.error' | i18n}}</mat-card-subtitle>
|
||||
</mat-card-header>
|
||||
<mat-card-content>
|
||||
<p>
|
||||
{{ 'users.error.' + users.error.status + '.text' | i18n}}
|
||||
</p>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (users) {
|
||||
<div class="flex column fill">
|
||||
<div class="scroll-container">
|
||||
<table class="default-table" mat-table [dataSource]="users.results || []" matSort
|
||||
(matSortChange)="applySort($event)" [matSortDisableClear]="true">
|
||||
<ng-container matColumnDef="username">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header [disableClear]="false">{{'user.username' |
|
||||
i18n}}
|
||||
</th>
|
||||
<td mat-cell *matCellDef="let user">
|
||||
<div class="flex middle">
|
||||
@if (user.roles && user.roles.indexOf('ROLE_ADMIN') != -1) {
|
||||
<mat-icon>admin_panel_settings</mat-icon>
|
||||
}
|
||||
{{user.username}}
|
||||
</div>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="name">
|
||||
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{'profile.name' | i18n}}</th>
|
||||
<td mat-cell *matCellDef="let user">{{user.name}}</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="email">
|
||||
<th mat-header-cell *matHeaderCellDef>{{'profile.email' | i18n}}</th>
|
||||
<td mat-cell *matCellDef="let user">{{user.email}}</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="about">
|
||||
<th mat-header-cell *matHeaderCellDef>{{'profile.about' | i18n}}</th>
|
||||
<td mat-cell *matCellDef="let user">
|
||||
<span class="ellipsis" matTooltip="{{user.about}}">{{user.about}}</span>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<tr mat-header-row *matHeaderRowDef="columns; sticky: true"></tr>
|
||||
<tr class="user" mat-row *matRowDef="let user; columns: columns;" [routerLink]="'/u/' + user.username"></tr>
|
||||
</table>
|
||||
</div>
|
||||
@if (users.total == 0) {
|
||||
<mat-list>
|
||||
<mat-list-item>
|
||||
<p>{{'paginator.empty' | i18n}}</p>
|
||||
</mat-list-item>
|
||||
</mat-list>
|
||||
}
|
||||
|
||||
<span class="spacer"></span>
|
||||
|
||||
|
||||
<form [formGroup]="form" (ngSubmit)="createUser()" #formDirective="ngForm">
|
||||
<div class="flex middle">
|
||||
<mat-form-field class="margin">
|
||||
<mat-label>{{'profile.username' | i18n}}</mat-label>
|
||||
<input matInput formControlName="username" type="text" [required]="true">
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field class="margin">
|
||||
<mat-label>{{'profile.name' | i18n}}</mat-label>
|
||||
<input matInput formControlName="name" type="text">
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field class="margin">
|
||||
<mat-label>{{'profile.email' | i18n}}</mat-label>
|
||||
<input matInput formControlName="email" type="email">
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field class="margin">
|
||||
<mat-label>{{'user.password' | i18n}}</mat-label>
|
||||
<input matInput formControlName="password" type="password">
|
||||
</mat-form-field>
|
||||
|
||||
<mat-slide-toggle class="margin" (change)="isAdmin=$event.checked">
|
||||
{{'user.admin' | i18n}}
|
||||
</mat-slide-toggle>
|
||||
|
||||
<button type="submit" mat-raised-button color="primary" [disabled]="form.invalid">{{'user.create' |
|
||||
i18n}}<mat-icon style="font-size: 1em;">person_add</mat-icon></button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="mat-mdc-paginator flex">
|
||||
<span class="spacer"></span>
|
||||
<mat-paginator [pageSizeOptions]="pageSizeOptions" [pageIndex]="users.offset / users.limit"
|
||||
[length]="users.total" [pageSize]="users.limit" (page)="applyPage($event)" showFirstLastButtons>
|
||||
</mat-paginator>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!users || !users.results && !users.error) {
|
||||
<mat-progress-bar *ngIf="" mode="indeterminate"></mat-progress-bar>
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
tr.user {
|
||||
&:hover {
|
||||
cursor: pointer;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
&.disabled {
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Component, HostListener, Input, OnInit } from '@angular/core';
|
||||
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { PageEvent } from '@angular/material/paginator';
|
||||
import { Sort } from '@angular/material/sort';
|
||||
import { AuthService } from 'src/app/services/auth.service';
|
||||
import { UserManagementService } from 'src/app/services/user.management.service';
|
||||
import { ConfirmDialog } from 'src/app/ui/confirm/confirm.component';
|
||||
|
||||
@Component({
|
||||
selector: 'ui-users',
|
||||
templateUrl: './users.page.html',
|
||||
styleUrls: ['./users.page.scss']
|
||||
})
|
||||
export class PageUsers implements OnInit {
|
||||
|
||||
@Input() users: any;
|
||||
pageSizeOptions: number[] = [1, 2, 3, 4, 5, 10, 15, 30, 50, 100];
|
||||
sort: string = "username";
|
||||
descending: boolean = false;
|
||||
|
||||
columns: string[] = [];
|
||||
|
||||
form: FormGroup;
|
||||
isAdmin: boolean = false;
|
||||
|
||||
username: string = "";
|
||||
|
||||
constructor(
|
||||
private userManagementService: UserManagementService,
|
||||
private authService: AuthService,
|
||||
private formBuilder: FormBuilder) { }
|
||||
|
||||
ngOnInit(): void {
|
||||
this.users = {};
|
||||
this.update();
|
||||
this.applyResize(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
|
||||
this.form = this.formBuilder.group({
|
||||
username: ['', Validators.required],
|
||||
name: ['', Validators.nullValidator],
|
||||
email: ['', Validators.nullValidator],
|
||||
password: ['', Validators.required]
|
||||
});
|
||||
|
||||
this.authService.auth.subscribe({
|
||||
next: (auth) => {
|
||||
this.username = auth.username;
|
||||
},
|
||||
error: (error) => {
|
||||
this.username = ""
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@HostListener('window:resize', ['$event'])
|
||||
onResize(event) {
|
||||
this.applyResize(event.target.innerWidth || event.target.documentElement.clientWidth || event.target.body.clientWidth)
|
||||
}
|
||||
|
||||
applyResize(width: number) {
|
||||
if (width < 992) {
|
||||
this.columns = ['username', 'name', 'email']
|
||||
} else {
|
||||
this.columns = ['username', 'name', 'email', 'about'];
|
||||
}
|
||||
}
|
||||
|
||||
update() {
|
||||
this.userManagementService.fetch(this.users.limit || 15, this.users.offset || 0, this.sort, this.descending).subscribe({
|
||||
next: (data: any) => {
|
||||
this.users = data;
|
||||
}, error: (error) => {
|
||||
this.users = { error: error };
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
applyPage(event: PageEvent) {
|
||||
this.users.limit = event.pageSize;
|
||||
this.users.offset = event.pageSize * event.pageIndex;
|
||||
this.update();
|
||||
}
|
||||
|
||||
applySort(event: Sort) {
|
||||
this.sort = event.direction ? event.active : 'username';
|
||||
this.descending = event.direction !== 'asc';
|
||||
this.update();
|
||||
}
|
||||
|
||||
createUser() {
|
||||
const user = {
|
||||
username: this.form.get("username").value,
|
||||
name: this.form.get("name").value,
|
||||
email: this.form.get("email").value,
|
||||
roles: this.isAdmin ? ['ROLE_ADMIN'] : []
|
||||
}
|
||||
this.userManagementService.create(user).subscribe({
|
||||
next: (result: any) => {
|
||||
this.userManagementService.setPassword(result.username, this.form.get("password").value).subscribe({
|
||||
next: (result) => {
|
||||
this.update();
|
||||
},
|
||||
error: (error) => {
|
||||
if (error.status == 422) {
|
||||
let errors = {};
|
||||
for (let code of error.error) {
|
||||
errors[code.field] = errors[code.field] || {};
|
||||
errors[code.field][code.code] = true;
|
||||
}
|
||||
|
||||
for (let code in errors) {
|
||||
this.form.get(code).setErrors(errors[code]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
if (error.status == 422) {
|
||||
let errors = {};
|
||||
for (let code of error.error) {
|
||||
errors[code.field] = errors[code.field] || {};
|
||||
errors[code.field][code.code] = true;
|
||||
}
|
||||
|
||||
for (let code in errors) {
|
||||
this.form.get(code).setErrors(errors[code]);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { HttpClient, HttpParams } from "@angular/common/http";
|
||||
import { Injectable } from "@angular/core";
|
||||
import { environment } from "src/environments/environment";
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AbstractService {
|
||||
|
||||
constructor(private http: HttpClient) {
|
||||
}
|
||||
|
||||
fetch(path: string, limit: number, offset: number, sort: string, descending: boolean, filter: any | undefined) {
|
||||
let httpParams = new HttpParams();
|
||||
if (limit != undefined) {
|
||||
httpParams = httpParams.set("limit", "" + limit);
|
||||
}
|
||||
if (offset) {
|
||||
httpParams = httpParams.set("offset", "" + offset);
|
||||
}
|
||||
|
||||
if (sort) {
|
||||
httpParams = httpParams.set("sort", "" + sort);
|
||||
}
|
||||
|
||||
if (descending) {
|
||||
httpParams = httpParams.set("descending", "" + descending);
|
||||
}
|
||||
|
||||
if (filter) {
|
||||
for (const param in filter) {
|
||||
if (filter[param]) {
|
||||
httpParams = httpParams.set(param, "" + filter[param]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this.http.get(environment.apiUrl + path, { params: httpParams });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { ReplaySubject, of } from 'rxjs';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
|
||||
import { RequestError } from './requesterror';
|
||||
|
||||
import { environment } from './../../environments/environment';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AuthService {
|
||||
|
||||
auth: ReplaySubject<any> = new ReplaySubject(undefined);
|
||||
|
||||
constructor(private http: HttpClient) {
|
||||
}
|
||||
|
||||
getAuth() {
|
||||
return this.authMe().toPromise().then((data: any) => {
|
||||
this.auth.next(data);
|
||||
return data;
|
||||
}, error => {
|
||||
throw new RequestError(error);
|
||||
});
|
||||
}
|
||||
|
||||
authMe() {
|
||||
return this.http.get(environment.apiUrl + "/auth");
|
||||
}
|
||||
|
||||
getExternal() {
|
||||
return this.http.get(environment.apiUrl + "/auth/external");
|
||||
}
|
||||
|
||||
logout() {
|
||||
return this.http.post(environment.apiUrl + "/logout", {});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
|
||||
import { environment } from '../../environments/environment';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class DebugService {
|
||||
|
||||
constructor(private http: HttpClient) {
|
||||
}
|
||||
|
||||
random() {
|
||||
return this.http.get(environment.apiUrl + "/debug/random");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { environment } from '../../environments/environment';
|
||||
import { MatPaginatorIntl } from '@angular/material/paginator';
|
||||
import { Subject } from 'rxjs';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class I18nService {
|
||||
|
||||
locale: string = "de-informal";
|
||||
locales: any[] = ["de-informal"];
|
||||
i18n: any;
|
||||
|
||||
constructor(private http: HttpClient) {
|
||||
|
||||
}
|
||||
|
||||
getLocales() {
|
||||
return this.locales;
|
||||
}
|
||||
|
||||
getLocale() {
|
||||
return this.locale || 'de-informal';
|
||||
}
|
||||
|
||||
setLocale(locale) {
|
||||
this.locale = locale;
|
||||
}
|
||||
|
||||
async fetch() {
|
||||
|
||||
let browserLocale = navigator.language;
|
||||
|
||||
if (browserLocale.indexOf("-") != -1) {
|
||||
browserLocale = browserLocale.split("-")[0];
|
||||
}
|
||||
|
||||
let locale = localStorage.getItem("buntspecht.locale") || browserLocale || this.locales[0];
|
||||
|
||||
if (locale == 'de') {
|
||||
locale = 'de-informal';
|
||||
}
|
||||
|
||||
if (this.locales.indexOf(locale) == -1) {
|
||||
locale = this.locales[0];
|
||||
}
|
||||
|
||||
this.setLocale(locale);
|
||||
this.i18n = await this.http.get("/assets/i18n/" + locale + ".json").toPromise();
|
||||
console.debug("fallback to default locale");
|
||||
|
||||
}
|
||||
|
||||
get(key, args: string[]): string {
|
||||
return this.getInternal(key, args, this.i18n, "", true);
|
||||
}
|
||||
|
||||
getEmpty(key, args: string[]): string {
|
||||
return this.getInternal(key, args, this.i18n, "", false);
|
||||
}
|
||||
|
||||
getInternal(key, args: string[], from, path, empty: boolean): string {
|
||||
key += '';
|
||||
if (!from) {
|
||||
return empty ? this.empty(key, args, path) : (key || "");
|
||||
} else if (from[key]) {
|
||||
if (typeof from[key] === 'object') {
|
||||
if (from[key]["."]) {
|
||||
return this.insertArguments(from[key]["."], args);
|
||||
}
|
||||
return empty ? this.empty(key, args, path) : (key || "");
|
||||
}
|
||||
return this.insertArguments(from[key], args);
|
||||
} else {
|
||||
let keys = key.split(".");
|
||||
if (from[keys[0]]) {
|
||||
key = keys.slice(1, keys.length).join(".");
|
||||
return this.getInternal(key, args, from[keys[0]], path + keys[0] + ".", empty)
|
||||
}
|
||||
}
|
||||
|
||||
return empty ? this.empty(key, args, path) : (key || "");
|
||||
}
|
||||
|
||||
empty(key, args: string[], path: string): string {
|
||||
return (path ? path + (path.endsWith(".") ? "" : ".") : "") + key + (args && args.length > 0 ? (" [" + args + "]") : "");
|
||||
}
|
||||
|
||||
insertArguments(label: string, args: string[]) {
|
||||
if (args) {
|
||||
for (let index in args) {
|
||||
label = label.replace(`{${index}}`, this.get(args[index], null));
|
||||
}
|
||||
}
|
||||
return label;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Injectable()
|
||||
export class I18nPaginatorIntl implements MatPaginatorIntl {
|
||||
|
||||
changes = new Subject<void>();
|
||||
|
||||
i18n: I18nService;
|
||||
|
||||
itemsPerPageLabel: string;
|
||||
nextPageLabel: string;
|
||||
previousPageLabel: string;
|
||||
firstPageLabel: string;
|
||||
lastPageLabel: string;
|
||||
|
||||
|
||||
injectI18n(i18n: I18nService) {
|
||||
this.i18n = i18n;
|
||||
|
||||
this.firstPageLabel = this.i18n.get('paginator.firstPage', []);
|
||||
this.itemsPerPageLabel = this.i18n.get('paginator.itemsPerPage', []);
|
||||
this.lastPageLabel = this.i18n.get('paginator.lastPage', []);
|
||||
|
||||
this.nextPageLabel = this.i18n.get('paginator.nextPage', []);
|
||||
this.previousPageLabel = this.i18n.get('paginator.previousPage', []);
|
||||
|
||||
}
|
||||
|
||||
|
||||
getRangeLabel(page: number, pageSize: number, length: number): string {
|
||||
if (length === 0) {
|
||||
return this.i18n.get('paginator.empty', []);
|
||||
}
|
||||
|
||||
const amountPages = Math.ceil(length / pageSize);
|
||||
return this.i18n.get('paginator.range', [page + 1 + "", amountPages + ""]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export class RequestError extends Error {
|
||||
|
||||
response: any;
|
||||
|
||||
constructor(response: any) {
|
||||
super(response.message);
|
||||
this.response = response;
|
||||
// Set the prototype explicitly.
|
||||
Object.setPrototypeOf(this, RequestError.prototype);
|
||||
}
|
||||
|
||||
getResponse(): any {
|
||||
return this.response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
import { environment } from '../../environments/environment';
|
||||
import { AbstractService } from './abstract.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class TurnoverManagementService {
|
||||
|
||||
constructor(private http: HttpClient, private abstractService: AbstractService) {
|
||||
}
|
||||
|
||||
fetch(limit: number, offset: number, sort: string, descending: boolean, filter: any | undefined) {
|
||||
return this.abstractService.fetch("/turnovers/manage", limit, offset, sort, descending, filter);
|
||||
}
|
||||
|
||||
overview(limit: number, offset: number, sort: string, descending: boolean, filter: any | undefined) {
|
||||
return this.abstractService.fetch("/turnovers/manage/overview", limit, offset, sort, descending, filter);
|
||||
}
|
||||
|
||||
get(id: number) {
|
||||
return this.http.get(environment.apiUrl + "/turnovers/manage/" + id);
|
||||
}
|
||||
|
||||
update(turnover: any) {
|
||||
return this.http.patch(environment.apiUrl + "/turnovers/manage", turnover);
|
||||
}
|
||||
|
||||
delete(id: number) {
|
||||
return this.http.delete(environment.apiUrl + "/turnovers/manage/" + id);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user