Skip to content

Commit

Permalink
podbicie springa i paru rzeczy w pom.xml
Browse files Browse the repository at this point in the history
edycja debta i podział
dodanie Partitioned cookies dla CSRFa
DEPLOY
  • Loading branch information
JanisBe committed Jun 27, 2024
1 parent e25ffdb commit dbdc6cb
Show file tree
Hide file tree
Showing 12 changed files with 278 additions and 73 deletions.
8 changes: 4 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.0</version>
<version>3.3.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>pl.janis</groupId>
Expand All @@ -16,14 +16,14 @@
<properties>
<java.version>21</java.version>
<org.mapstruct.version>1.6.0.Beta2</org.mapstruct.version>
<sprinv-boot-version>3.3.0</sprinv-boot-version>
<sprinv-boot-version>3.3.1</sprinv-boot-version>
<mariadb-java-client.version>3.4.0</mariadb-java-client.version>
<jjwt.version>0.12.5</jjwt.version>
<jjwt.version>0.12.6</jjwt.version>
<mysql-connector.version>8.4.0</mysql-connector.version>
<lombok.version>1.18.32</lombok.version>
<jasypt.version>3.0.5</jasypt.version>
<apache-commons.version>3.14.0</apache-commons.version>
<spring-version>6.3.0</spring-version>
<spring-version>6.3.1</spring-version>
</properties>
<dependencies>
<dependency>
Expand Down
4 changes: 4 additions & 0 deletions src/main/frontend/src/app/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,8 @@ export class AuthService {
public isHttpsEnabled() {
return this.http.get<boolean>(`${environment.API_URL}/isHttpsEnabled`);
}

public csrfToken() {
return this.http.get<boolean>(`${environment.API_URL}/csrf`);
}
}
4 changes: 2 additions & 2 deletions src/main/frontend/src/app/auth/jwt.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ export class JwtInterceptor implements HttpInterceptor {
if (err instanceof HttpErrorResponse) {
if (err.status === 401 || err.status === 403) {
console.log('redirect');
this.authService.logout();
this.router.navigate(['login']);
// this.authService.logout();
// this.router.navigate(['login']);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ export class LoginComponent implements OnInit {
}

ngOnInit(): void {
this.authService.isHttpsEnabled().subscribe();
if (!!this.authService.user.value) {
// this.router.navigate(['/group/list']);
}
this.authService.csrfToken().subscribe();
this.initForm();
if (!!this.email) {
this.loginForm.patchValue({login: this.email})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ export class AddExpenseComponent implements OnInit, OnDestroy {
protected editMode: boolean;
private debts: Debt[] = [];
private splitDialogRef: MatDialogRef<SplitDialogComponent | MultiUserSplitComponent>;

private readonly AMOUNT_PATTERN = '^\\d+(?:[.,]\\d{0,2})?$';

constructor(private expenseService: ExpenseService,
Expand Down Expand Up @@ -102,6 +101,7 @@ export class AddExpenseComponent implements OnInit, OnDestroy {
this.patchForm(expense);
this.form.patchValue(this.currentExpense);
this.loadingService.setLoading(false);
this.dataSharingService.amount.set(expense.amount);

});
}
Expand Down Expand Up @@ -183,17 +183,37 @@ export class AddExpenseComponent implements OnInit, OnDestroy {
this.onCancel();
}

private initForm() {
this.form = new FormGroup({
amount: new FormControl(this.calculateAmount(this.currentExpense), [Validators.required, Validators.pattern(this.AMOUNT_PATTERN)]),
description: new FormControl(this.currentExpense?.description ?? null, Validators.required),
currency: new FormControl(this.defaultCurrency, Validators.required),
name: this.userName,
category: new FormControl(this.currentExpense?.categoryId ?? null),
group: new FormControl(this.data.groupId, Validators.required),
date: new FormControl(this.currentExpense?.date ?? new Date(), Validators.required)
openSplitDialog(usersOriginalList: User[]) {
if (this.splitDialogRef &&
(this.splitDialogRef as MatDialogRef<SplitDialogComponent>)?.getState() === 0 || this.dialog.openDialogs.length > 1) {
return;
}
const config = {
data: {
users: usersOriginalList,
currentUser: this.payer,
currency: this.form.value.currency,
existingDebts: this.debts
},
hasBackdrop: false,
width: '400px',
position: {left: '68%'},
panelClass: 'slide-in-from-right'
};
if (this.users.length > 2) {
this.splitDialogRef = this.dialog.open(MultiUserSplitComponent, config);
} else {
this.splitDialogRef = this.dialog.open(SplitDialogComponent, config);
}
this.splitDialogRef.afterClosed().subscribe(split => {
console.log(split);
if (split === undefined) {
return;
}
this.splitHow = split.text;
this.betweenWho = "";
this.debts = split.debts;
});
this.listenForAmountChange();
}

openPayerDialog(payer: User, usersOriginalList: User[]) {
Expand Down Expand Up @@ -260,32 +280,16 @@ export class AddExpenseComponent implements OnInit, OnDestroy {
});
}

openSplitDialog(usersOriginalList: User[]) {
if (this.splitDialogRef &&
(this.splitDialogRef as MatDialogRef<SplitDialogComponent>)?.getState() === 0 || this.dialog.openDialogs.length > 1) {
return;
updateValue(value: string) {
const amount = this.sanitizeAmount(value);
let parseInt = +amount;
if (isNaN(parseInt)) {
parseInt = 0;
}
const config = {
data: {users: usersOriginalList, currentUser: this.payer, currency: this.form.value.currency},
hasBackdrop: false,
width: '400px',
position: {left: '68%'},
panelClass: 'slide-in-from-right'
};
if (this.users.length > 2) {
this.splitDialogRef = this.dialog.open(MultiUserSplitComponent, config);
} else {
this.splitDialogRef = this.dialog.open(SplitDialogComponent, config);
if (this.editMode) {
this.updateDebts(parseInt);
}
this.splitDialogRef.afterClosed().subscribe(split => {
console.log(split);
if (split === undefined) {
return;
}
this.splitHow = split.text;
this.betweenWho = "";
this.debts = split.debts;
});
this.dataSharingService.amount.set(parseInt);
}

sanitizeInput(amount: string) {
Expand Down Expand Up @@ -316,10 +320,41 @@ export class AddExpenseComponent implements OnInit, OnDestroy {
});
}

updateDebts(currentExpenseAmount: number) {
if (this.debts.length > 0) {
const myDue = -((currentExpenseAmount / (this.users.length)) * (this.users.length - 1)).toFixed(2);
const other = +(currentExpenseAmount / (this.users.length)).toFixed(2)
this.debts.map((debt) => {
if (debt.to.id === this.payer.id) {
debt.amount = myDue;
} else {
debt.amount = other;
}
});
}
}

private sanitizeAmount(amount: string) {
return amount.toString().replace(/,/g, '.');
}

private initForm() {
this.form = new FormGroup({
amount: new FormControl(this.calculateTotalAmount(this.currentExpense), [Validators.required, Validators.pattern(this.AMOUNT_PATTERN)]),
description: new FormControl(this.currentExpense?.description ?? null, Validators.required),
currency: new FormControl(this.defaultCurrency, Validators.required),
name: this.userName,
category: new FormControl(this.currentExpense?.categoryId ?? null),
group: new FormControl(this.data.groupId, Validators.required),
date: new FormControl(this.currentExpense?.date ?? new Date(), Validators.required)
});
this.listenForAmountChange();
}

private patchForm(expense: Expense) {
this.editMode = true;
this.form.patchValue({
amount: this.calculateAmount(expense),
amount: this.calculateTotalAmount(expense),
description: expense.description,
currency: expense.currency,
category: expense.categoryId,
Expand All @@ -329,19 +364,6 @@ export class AddExpenseComponent implements OnInit, OnDestroy {
this.form.addControl("id", new FormControl(expense.id));
}

private sanitizeAmount(amount: string) {
return amount.toString().replace(/,/g, '.');
}

updateValue(value: string) {
const amount = this.sanitizeAmount(value);
let parseInt = +amount;
if (isNaN(parseInt)) {
parseInt = 0;
}
this.dataSharingService.amount.set(parseInt);
}

private listenForAmountChange() {
this.form.controls['amount'].valueChanges.subscribe((val: string) => {
if (!val.toString().match(this.AMOUNT_PATTERN)) {
Expand All @@ -352,7 +374,7 @@ export class AddExpenseComponent implements OnInit, OnDestroy {
});
}

private calculateAmount(expense: Expense): number | string {
private calculateTotalAmount(expense: Expense): number | string {
if (!expense?.debt) {
return "";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@ export class MultiUserSplitComponent implements OnInit, AfterViewInit {
private participants = '';
amountValid = false;
private wasChanged = false;
private editMode: boolean;

constructor(
@Inject(MAT_DIALOG_DATA) public data: { users: User[], currentUser: User, currency: string },
@Inject(MAT_DIALOG_DATA) public data: { users: User[], currentUser: User, currency: string, existingDebts: Debt[] },
public dialogRef: MatDialogRef<MultiUserSplitComponent>,
private fb: FormBuilder,
private snackbarService: SnackbarService,
Expand All @@ -49,6 +50,9 @@ export class MultiUserSplitComponent implements OnInit, AfterViewInit {
}

ngOnInit() {
if (this.data.existingDebts.length > 0) {
this.editMode = true;
}
this.numberForm = this.fb.group({});
const divideMap = this.divideCurrencyEvenly(this.amount, this.data.users.length);
this.data.users.forEach((user, index) => {
Expand Down Expand Up @@ -79,8 +83,14 @@ export class MultiUserSplitComponent implements OnInit, AfterViewInit {
this.snackbarService.displayError("Suma musi być równa: " + this.amount + " aktualnie: " + this.getSum());
return;
}
let calculatedDebts = this.recalculate();
console.log(this.data.existingDebts);
if (this.editMode) {
this.assignIdsToDebts(calculatedDebts, this.data.existingDebts);
console.log(calculatedDebts);
}
this.dialogRef.close({
debts: this.recalculate(),
debts: calculatedDebts,
text: this.participants
});
}
Expand Down Expand Up @@ -154,11 +164,28 @@ export class MultiUserSplitComponent implements OnInit, AfterViewInit {
let totalValue: number = 0;
debtMap.forEach((value, user) => {
if (user.id !== currentUser.id) {
debts.push({from: user, to: currentUser, amount: value, currency: this.data.currency});
let debtForOtherUser: Debt = {from: user, to: currentUser, amount: value, currency: this.data.currency};
debts.push(debtForOtherUser);
totalValue += value;
}
});
debts.push({from: currentUser, to: currentUser, amount: -totalValue, currency: this.data.currency});
let debtForCurrenUser: Debt = {
from: currentUser,
to: currentUser,
amount: -totalValue,
currency: this.data.currency
};
debts.push(debtForCurrenUser);
return debts;
}

private assignIdsToDebts(calculatedDebts: Debt[], existingDebts: Debt[]) {
existingDebts.forEach(debt => {
calculatedDebts.map(calculatedDebt => {
if (debt.from.id === calculatedDebt.from.id && debt.to.id === calculatedDebt.to.id) {
calculatedDebt.id = debt.id;
}
})
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class SplitDialogComponent implements OnInit, AfterViewInit {
amount = this.dataSharingService.amount;

constructor(
@Inject(MAT_DIALOG_DATA) public data: { users: User[], currentUser: User, currency: string },
@Inject(MAT_DIALOG_DATA) public data: { users: User[], currentUser: User, currency: string, existingDebts: Debt[] },
public dialogRef: MatDialogRef<SplitDialogComponent>,
private fb: FormBuilder,
private dataSharingService: DataSharingService,
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/pl/janis/komornik/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter;
import org.springframework.web.cors.CorsConfiguration;
import pl.janis.komornik.config.security.PartitionedCookieLogoutHandler;
import pl.janis.komornik.config.security.PartitionedCookieTokenRepository;
import pl.janis.komornik.filter.CsrfCookieFilter;
import pl.janis.komornik.filter.SpaWebFilter;
import pl.janis.komornik.service.UserService;
Expand All @@ -48,7 +48,7 @@ public SecurityConfig(@Lazy Filter jwtAuthFilter, @Lazy UserService userService)

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
CookieCsrfTokenRepository cookieCsrfTokenRepository = new CookieCsrfTokenRepository();
PartitionedCookieTokenRepository cookieCsrfTokenRepository = new PartitionedCookieTokenRepository();
cookieCsrfTokenRepository.setCookieCustomizer(c -> c.secure(true).httpOnly(true).sameSite("none"));
http.securityContext(context -> context.requireExplicitSave(false))
// .requiresChannel(channel -> channel.anyRequest().requiresSecure())
Expand Down
Loading

0 comments on commit dbdc6cb

Please sign in to comment.