Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Other entity login #2143

Merged
merged 30 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
097373e
session manager can load other entities
TheSlimvReal Dec 21, 2023
7bf56b9
removed deprecated todo?
TheSlimvReal Dec 21, 2023
64c48bc
user security component is entity agnostic
TheSlimvReal Dec 21, 2023
3d2daa8
mage todo completion entity agnostic
TheSlimvReal Dec 22, 2023
4df0a8f
added test
TheSlimvReal Dec 22, 2023
9cf9313
entity select can handle foreign entity references
TheSlimvReal Dec 22, 2023
d50d44a
fix display entity array to show entities again
TheSlimvReal Dec 22, 2023
15ad1ab
display entity array shows foreign entities
TheSlimvReal Dec 22, 2023
079ab70
display single entity allows foreign entities to be displayed
TheSlimvReal Dec 22, 2023
a830f9c
improved error message in MockEntityMapper
TheSlimvReal Dec 22, 2023
79506e4
added support for foreign entities in DisplayEntityComponent
TheSlimvReal Dec 22, 2023
9e15830
use local storage to save paginator settings
TheSlimvReal Dec 22, 2023
409169d
Merge branch 'master' into other_entity_login
TheSlimvReal Feb 5, 2024
5f93ef1
fixed tests
TheSlimvReal Feb 5, 2024
7282b5f
removed further usages of short id
TheSlimvReal Feb 5, 2024
a437de6
made user entity optional
TheSlimvReal Feb 6, 2024
dd03437
made `username` claim optional
TheSlimvReal Feb 6, 2024
cdfee7f
fixed issue with unassigned default values on array properties
TheSlimvReal Feb 6, 2024
4c6f3e4
only loading missing entities of other types in entity select
TheSlimvReal Feb 6, 2024
fb6b4b2
using ID as username in keycloak
TheSlimvReal Feb 6, 2024
fc112fc
some code cleanup
TheSlimvReal Feb 6, 2024
878d5a6
Merge branch 'master' into other_entity_login
TheSlimvReal Feb 6, 2024
74f45cc
Update src/app/core/session/session-service/session-manager.service.s…
TheSlimvReal Feb 7, 2024
2e261a7
added interface for parsed JWT
TheSlimvReal Feb 7, 2024
8b663a4
automatically adding User prefix to tokens with short entityId
TheSlimvReal Feb 7, 2024
d1ec5c0
showing linked user entity in user account page
TheSlimvReal Feb 7, 2024
211e229
removed account manager role from demo mode
TheSlimvReal Feb 7, 2024
f97689a
improve user profile ui
sleidig Feb 8, 2024
91216b8
Merge branch 'master' into other_entity_login
TheSlimvReal Feb 8, 2024
2ca6de3
removed unused styles
TheSlimvReal Feb 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/app/core/entity/default-datatype/view.directive.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Entity } from "../model/entity";
import { Directive, Input, OnChanges } from "@angular/core";
import { Directive, Input, OnChanges, SimpleChanges } from "@angular/core";

@Directive()
export abstract class ViewDirective<T, C = any> implements OnChanges {
Expand All @@ -12,7 +12,7 @@ export abstract class ViewDirective<T, C = any> implements OnChanges {
/** indicating that the value is not in its original state, so that components can explain this to the user */
isPartiallyAnonymized: boolean;

ngOnChanges() {
ngOnChanges(changes?: SimpleChanges) {
this.isPartiallyAnonymized =
this.entity?.anonymized &&
this.entity?.getSchema()?.get(this.id)?.anonymize === "retain-anonymized";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ export class AccountPageComponent implements OnInit {
return;
}

// TODO can we use keycloak for this?
this.authService.setEmail(this.email.value).subscribe({
next: () =>
this.alertService.addInfo(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { EntityMapperService } from "../../entity/entity-mapper/entity-mapper.se
import { mockEntityMapper } from "../../entity/entity-mapper/mock-entity-mapper-service";
import { User } from "../../user/user";
import { TEST_USER } from "../../user/demo-user-generator.service";
import { Child } from "../../../child-dev-project/children/model/child";

describe("SessionManagerService", () => {
let service: SessionManagerService;
Expand Down Expand Up @@ -141,6 +142,23 @@ describe("SessionManagerService", () => {
expect(currentUser.value).toEqual(adminUser);
});

it("should allow other entities to log in", async () => {
const childSession: SessionInfo = { name: "Child:123", roles: [] };
mockKeycloak.login.and.resolveTo(childSession);
const loggedInChild = new Child("123");
const otherChild = new Child("456");
await TestBed.inject(EntityMapperService).saveAll([
loggedInChild,
otherChild,
]);

await service.remoteLogin();

expect(sessionInfo.value).toBe(childSession);
expect(loginStateSubject.value).toBe(LoginState.LOGGED_IN);
expect(TestBed.inject(CurrentUserSubject).value).toEqual(loggedInChild);
});

it("should automatically login, if the session is still valid", async () => {
await service.remoteLogin();

Expand Down
18 changes: 12 additions & 6 deletions src/app/core/session/session-service/session-manager.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { CurrentUserSubject } from "../current-user-subject";
import { EntityMapperService } from "../../entity/entity-mapper/entity-mapper.service";
import { filter } from "rxjs/operators";
import { Subscription } from "rxjs";
import { Entity } from "../../entity/model/entity";

/**
* This service handles the user session.
Expand Down Expand Up @@ -96,18 +97,23 @@ export class SessionManagerService {
return this.initializeUser(user);
}

private async initializeUser(user: SessionInfo) {
await this.initializeDatabaseForCurrentUser(user);
this.sessionInfo.next(user);
private async initializeUser(session: SessionInfo) {
await this.initializeDatabaseForCurrentUser(session);
this.sessionInfo.next(session);
this.loginStateSubject.next(LoginState.LOGGED_IN);
this.initUserEntity(session);
}

// TODO allow generic entities with fallback to User entity
private initUserEntity(user: SessionInfo) {
const entityType = user.name.includes(":")
? Entity.extractTypeFromId(user.name)
: User;
this.entityMapper
.load(User, user.name)
.load(entityType, user.name)
.then((res) => this.currentUser.next(res))
.catch(() => undefined);
this.updateSubscription = this.entityMapper
.receiveUpdates(User)
.receiveUpdates(entityType)
.pipe(
filter(
({ entity }) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ describe("UserSecurityComponent", () => {
name: "Not Assigned Role",
description: "this role is not assigned to the user",
};
const user = { name: "test-user" } as User;
const user = Object.assign(new User(), { username: "test-user" });
let keycloakUser: KeycloakUser;

beforeEach(async () => {
Expand All @@ -57,7 +57,7 @@ describe("UserSecurityComponent", () => {
{
provide: SessionSubject,
useValue: new BehaviorSubject({
name: user.name,
name: user.getId(true),
roles: [KeycloakAuthService.ACCOUNT_MANAGER_ROLE],
}),
},
Expand All @@ -80,7 +80,7 @@ describe("UserSecurityComponent", () => {

expect(component.user).toBe(keycloakUser);
expect(component.form).toHaveValue({
username: user.name,
username: user.toString(),
email: "my@email.de",
roles: [assignedRole],
});
Expand Down Expand Up @@ -116,7 +116,7 @@ describe("UserSecurityComponent", () => {
expect(mockHttp.post).toHaveBeenCalledWith(
jasmine.stringMatching(/\/account$/),
{
username: user.name,
username: user.toString(),
email: "new@email.com",
roles: [assignedRole],
enabled: true,
Expand Down
18 changes: 11 additions & 7 deletions src/app/core/user/user-security/user-security.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
KeycloakUser,
Role,
} from "../../session/auth/keycloak/keycloak-auth.service";
import { User } from "../user";
import { AlertService } from "../../alerts/alert.service";
import { HttpClient } from "@angular/common/http";
import { AppSettings } from "../../app-settings";
Expand All @@ -23,6 +22,8 @@ import { MatInputModule } from "@angular/material/input";
import { MatSelectModule } from "@angular/material/select";
import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy";
import { SessionSubject } from "../../session/auth/session-info";
import { Entity } from "../../entity/model/entity";
import { catchError } from "rxjs/operators";

@UntilDestroy()
@DynamicComponent("UserSecurity")
Expand All @@ -43,7 +44,7 @@ import { SessionSubject } from "../../session/auth/session-info";
standalone: true,
})
export class UserSecurityComponent implements OnInit {
@Input() entity: User;
@Input() entity: Entity;
form = this.fb.group({
username: [{ value: "", disabled: true }],
email: ["", [Validators.required, Validators.email]],
Expand Down Expand Up @@ -91,12 +92,15 @@ export class UserSecurityComponent implements OnInit {
}

ngOnInit() {
this.form.get("username").setValue(this.entity.name);
this.form.get("username").setValue(this.entity.toString());
if (this.authService) {
this.authService.getUser(this.entity.name).subscribe({
next: (res) => this.assignUser(res),
error: () => undefined,
});
this.authService
.getUser(this.entity.getId(true))
.pipe(catchError(() => this.authService.getUser(this.entity.getId())))
.subscribe({
next: (res) => this.assignUser(res),
error: () => undefined,
});
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
<span i18n>completed</span>
</div>
<div class="completed-details" i18n>
by {{ value.completedBy }} on {{ value.completedAt | date }}
by {{ completedBy.toString() }} on {{ value.completedAt | date }}
</div>
</div>
Original file line number Diff line number Diff line change
@@ -1,16 +1,41 @@
import { Component } from "@angular/core";
import { Component, OnChanges, SimpleChanges } from "@angular/core";
import { DynamicComponent } from "../../../../core/config/dynamic-components/dynamic-component.decorator";
import { ViewDirective } from "../../../../core/entity/default-datatype/view.directive";
import { TodoCompletion } from "../../model/todo-completion";
import { DatePipe, NgIf } from "@angular/common";
import { FontAwesomeModule } from "@fortawesome/angular-fontawesome";
import { EntityMapperService } from "../../../../core/entity/entity-mapper/entity-mapper.service";
import { Entity } from "../../../../core/entity/model/entity";
import { User } from "../../../../core/user/user";
import { DisplayEntityComponent } from "../../../../core/basic-datatypes/entity/display-entity/display-entity.component";

@DynamicComponent("DisplayTodoCompletion")
@Component({
selector: "app-display-todo-completion",
templateUrl: "./display-todo-completion.component.html",
styleUrls: ["./display-todo-completion.component.scss"],
standalone: true,
imports: [NgIf, FontAwesomeModule, DatePipe],
imports: [NgIf, FontAwesomeModule, DatePipe, DisplayEntityComponent],
})
export class DisplayTodoCompletionComponent extends ViewDirective<TodoCompletion> {}
export class DisplayTodoCompletionComponent
extends ViewDirective<TodoCompletion>
implements OnChanges
{
completedBy: Entity;
constructor(private entityMapper: EntityMapperService) {
super();
}

ngOnChanges(changes: SimpleChanges) {
super.ngOnChanges(changes);
if (changes.hasOwnProperty("value") && this.value.completedBy) {
const entityId = this.value.completedBy;
const entityType = entityId.includes(":")
? Entity.extractTypeFromId(entityId)
: User;
this.entityMapper
.load(entityType, entityId)
.then((res) => (this.completedBy = res));
}
}
}
4 changes: 1 addition & 3 deletions src/app/features/todos/todo.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,12 @@ export class TodoService {
const nextTodo = await this.createNextRepetition(todo);

todo.completed = {
completedBy: this.currentUser.value.getId(),
completedBy: this.currentUser.value.getId(true),
completedAt: new Date(),
nextRepetition: nextTodo?.getId(true),
};

await this.entityMapper.save(todo);

// TODO: user block instead of id to display in template
TheSlimvReal marked this conversation as resolved.
Show resolved Hide resolved
}

private async createNextRepetition(originalTodo: Todo): Promise<Todo | null> {
Expand Down
Loading