remove keycloak

This commit is contained in:
Andreas Knuth 2025-02-19 16:24:42 -06:00
parent a2e6243e93
commit f6d1b8623c
26 changed files with 166 additions and 282 deletions

View File

@ -14,8 +14,8 @@
"console": "integratedTerminal",
"env": {
"HOST_NAME": "localhost"
},
"preLaunchTask": "Start Stripe Listener"
}
// "preLaunchTask": "Start Stripe Listener"
},
{
"type": "node",

View File

@ -0,0 +1,68 @@
import 'dotenv/config';
import { drizzle } from 'drizzle-orm/node-postgres';
import { readFileSync } from 'fs';
import { Pool } from 'pg';
import { BusinessListingService } from 'src/listings/business-listing.service';
import { CommercialPropertyService } from 'src/listings/commercial-property.service';
import { UserService } from 'src/user/user.service';
import winston from 'winston';
import { BusinessListing, CommercialPropertyListing, User } from '../models/db.model';
import * as schema from './schema';
(async () => {
const connectionString = process.env.DATABASE_URL;
const client = new Pool({ connectionString });
const db = drizzle(client, { schema, logger: true });
const logger = winston.createLogger({
transports: [new winston.transports.Console()],
});
const commService = new CommercialPropertyService(null, db);
const businessService = new BusinessListingService(null, db);
const userService = new UserService(null, db, null, null);
//Delete Content
await db.delete(schema.commercials);
await db.delete(schema.businesses);
await db.delete(schema.users);
let filePath = `./data/users_export.json`;
let data: string = readFileSync(filePath, 'utf8');
const usersData: User[] = JSON.parse(data); // Erwartet ein Array von Objekten
for (let index = 0; index < usersData.length; index++) {
const user = usersData[index];
delete user.id;
const u = await userService.saveUser(user, false);
logger.info(`user_${index} inserted`);
}
//Corporate Listings
filePath = `./data/commercials_export.json`;
data = readFileSync(filePath, 'utf8');
const commercialJsonData = JSON.parse(data) as CommercialPropertyListing[]; // Erwartet ein Array von Objekten
for (let index = 0; index < commercialJsonData.length; index++) {
const commercial = commercialJsonData[index];
delete commercial.id;
const result = await commService.createListing(commercial);
}
//Business Listings
filePath = `./data/businesses_export.json`;
data = readFileSync(filePath, 'utf8');
const businessJsonData = JSON.parse(data) as BusinessListing[]; // Erwartet ein Array von Objekten
for (let index = 0; index < businessJsonData.length; index++) {
const business = businessJsonData[index];
delete business.id;
await businessService.createListing(business);
}
//End
await client.end();
})();
function getRandomItem<T>(arr: T[]): T {
if (arr.length === 0) {
throw new Error('The array is empty.');
}
const randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
}

View File

@ -1,12 +0,0 @@
import 'dotenv/config';
import { drizzle } from 'drizzle-orm/node-postgres';
import pkg from 'pg';
import * as schema from './schema';
const { Pool } = pkg;
const connectionString = process.env.DATABASE_URL;
const pool = new Pool({ connectionString });
const db = drizzle(pool, { schema });
// This will run migrations on the database, skipping the ones already applied
//await migrate(db, { migrationsFolder: './src/drizzle/migrations' });
// Don't forget to close the connection, otherwise the script will hang
//await pool.end();

View File

@ -42,8 +42,6 @@
"express": "^4.18.2",
"flowbite": "^2.4.1",
"jwt-decode": "^4.0.0",
"keycloak-angular": "^16.0.1",
"keycloak-js": "^25.0.1",
"leaflet": "^1.9.4",
"memoize-one": "^6.0.0",
"ng-gallery": "^11.0.0",

View File

@ -1,7 +1,6 @@
import { CommonModule } from '@angular/common';
import { Component, HostListener } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router, RouterOutlet } from '@angular/router';
import { KeycloakEventType, KeycloakService } from 'keycloak-angular';
import { filter } from 'rxjs/operators';
import build from '../build';
@ -34,7 +33,6 @@ export class AppComponent {
public loadingService: LoadingService,
private router: Router,
private activatedRoute: ActivatedRoute,
private keycloakService: KeycloakService,
private userService: UserService,
private confirmationService: ConfirmationService,
private auditService: AuditService,
@ -50,35 +48,33 @@ export class AppComponent {
});
}
ngOnInit() {
// Überwache Keycloak-Events, um den Token-Refresh zu kontrollieren
this.keycloakService.keycloakEvents$.subscribe({
next: event => {
if (event.type === KeycloakEventType.OnTokenExpired) {
// Wenn der Token abgelaufen ist, versuchen wir einen Refresh
this.handleTokenExpiration();
}
},
});
}
private async handleTokenExpiration(): Promise<void> {
try {
// Versuche, den Token zu erneuern
const refreshed = await this.keycloakService.updateToken();
if (!refreshed) {
// Wenn der Token nicht erneuert werden kann, leite zur Login-Seite weiter
this.keycloakService.login({
redirectUri: window.location.href, // oder eine andere Seite
});
}
} catch (error) {
if (error.error === 'invalid_grant' && error.error_description === 'Token is not active') {
// Hier wird der Fehler "invalid_grant" abgefangen
this.keycloakService.login({
redirectUri: window.location.href,
});
}
}
// this.keycloakService.keycloakEvents$.subscribe({
// next: event => {
// if (event.type === KeycloakEventType.OnTokenExpired) {
// this.handleTokenExpiration();
// }
// },
// });
}
// private async handleTokenExpiration(): Promise<void> {
// try {
// // Versuche, den Token zu erneuern
// const refreshed = await this.keycloakService.updateToken();
// if (!refreshed) {
// // Wenn der Token nicht erneuert werden kann, leite zur Login-Seite weiter
// this.keycloakService.login({
// redirectUri: window.location.href, // oder eine andere Seite
// });
// }
// } catch (error) {
// if (error.error === 'invalid_grant' && error.error_description === 'Token is not active') {
// // Hier wird der Fehler "invalid_grant" abgefangen
// this.keycloakService.login({
// redirectUri: window.location.href,
// });
// }
// }
// }
@HostListener('window:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (event.shiftKey && event.ctrlKey && event.key === 'V') {

View File

@ -5,7 +5,6 @@ import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@a
import { initializeApp, provideFirebaseApp } from '@angular/fire/app';
import { getAuth, provideAuth } from '@angular/fire/auth';
import { provideAnimations } from '@angular/platform-browser/animations';
import { KeycloakBearerInterceptor, KeycloakService } from 'keycloak-angular';
import { GALLERY_CONFIG, GalleryConfig } from 'ng-gallery';
import { provideQuillConfig } from 'ngx-quill';
import { provideShareButtonsOptions, SharerMethods, withConfig } from 'ngx-sharebuttons';
@ -17,7 +16,6 @@ import { AuthInterceptor } from './interceptors/auth.interceptor';
import { LoadingInterceptor } from './interceptors/loading.interceptor';
import { TimeoutInterceptor } from './interceptors/timeout.interceptor';
import { GlobalErrorHandler } from './services/globalErrorHandler';
import { KeycloakInitializerService } from './services/keycloak-initializer.service';
import { SelectOptionsService } from './services/select-options.service';
import { createLogger } from './utils/utils';
// provideClientHydration()
@ -25,16 +23,6 @@ const logger = createLogger('ApplicationConfig');
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptorsFromDi()),
{ provide: KeycloakService },
{
provide: APP_INITIALIZER,
// useFactory: initializeKeycloak1,
//useFactory: initializeKeycloak2,
useFactory: initializeKeycloak,
multi: true,
//deps: [KeycloakService],
deps: [KeycloakInitializerService],
},
{
provide: APP_INITIALIZER,
useFactory: initServices,
@ -46,11 +34,6 @@ export const appConfig: ApplicationConfig = {
useClass: LoadingInterceptor,
multi: true,
},
{
provide: HTTP_INTERCEPTORS,
useClass: KeycloakBearerInterceptor,
multi: true,
},
{
provide: HTTP_INTERCEPTORS,
useClass: TimeoutInterceptor,
@ -108,47 +91,3 @@ function initServices(selectOptions: SelectOptionsService) {
await selectOptions.init();
};
}
export function initializeKeycloak(keycloak: KeycloakInitializerService) {
return () => keycloak.initialize();
}
// export function initializeKeycloak1(keycloak: KeycloakService): () => Promise<void> {
// return async () => {
// const { url, realm, clientId } = environment.keycloak;
// const adapter = customKeycloakAdapter(() => keycloak.getKeycloakInstance(), {});
// if (window.location.search.length > 0) {
// sessionStorage.setItem('SEARCH', window.location.search);
// }
// const { host, hostname, href, origin, pathname, port, protocol, search } = window.location;
// await keycloak.init({
// config: { url, realm, clientId },
// initOptions: {
// onLoad: 'check-sso',
// silentCheckSsoRedirectUri: window.location.hostname === 'localhost' ? `${window.location.origin}/assets/silent-check-sso.html` : `${window.location.origin}/dealerweb/assets/silent-check-sso.html`,
// adapter,
// redirectUri: `${origin}${pathname}`,
// },
// });
// };
// }
// function initializeKeycloak2(keycloak: KeycloakService) {
// return async () => {
// logger.info(`###>calling keycloakService init ...`);
// const authenticated = await keycloak.init({
// config: {
// url: environment.keycloak.url,
// realm: environment.keycloak.realm,
// clientId: environment.keycloak.clientId,
// },
// initOptions: {
// onLoad: 'check-sso',
// silentCheckSsoRedirectUri: (<any>window).location.origin + '/assets/silent-check-sso.html',
// },
// bearerExcludedUrls: ['/assets'],
// shouldUpdateToken(request) {
// return !request.headers.get('token-update') === false;
// },
// });
// logger.info(`+++>${authenticated}`);
// };
// }

View File

@ -6,7 +6,6 @@ import { NavigationEnd, Router, RouterModule } from '@angular/router';
import { faUserGear } from '@fortawesome/free-solid-svg-icons';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { Collapse, Dropdown, initFlowbite } from 'flowbite';
import { KeycloakService } from 'keycloak-angular';
import { filter, Observable, Subject, Subscription } from 'rxjs';
import { SortByOptions, User } from '../../../../../bizmatch-server/src/models/db.model';
import { BusinessListingCriteria, CommercialPropertyListingCriteria, emailToDirName, KeycloakUser, KeyValueAsSortBy, UserListingCriteria } from '../../../../../bizmatch-server/src/models/main.model';
@ -17,7 +16,7 @@ import { SearchService } from '../../services/search.service';
import { SelectOptionsService } from '../../services/select-options.service';
import { SharedService } from '../../services/shared.service';
import { UserService } from '../../services/user.service';
import { assignProperties, compareObjects, createEmptyBusinessListingCriteria, createEmptyCommercialPropertyListingCriteria, createEmptyUserListingCriteria, getCriteriaProxy, map2User } from '../../utils/utils';
import { assignProperties, compareObjects, createEmptyBusinessListingCriteria, createEmptyCommercialPropertyListingCriteria, createEmptyUserListingCriteria, getCriteriaProxy, isAdmin, map2User } from '../../utils/utils';
import { DropdownComponent } from '../dropdown/dropdown.component';
import { ModalService } from '../search-modal/modal.service';
@UntilDestroy()
@ -48,7 +47,6 @@ export class HeaderComponent {
sortDropdownVisible: boolean;
sortByOptions: KeyValueAsSortBy[] = [];
constructor(
public keycloakService: KeycloakService,
private router: Router,
private userService: UserService,
private sharedService: SharedService,
@ -67,7 +65,6 @@ export class HeaderComponent {
}
}
async ngOnInit() {
//const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
this.keycloakUser = map2User(token);
if (this.keycloakUser) {
@ -127,11 +124,6 @@ export class HeaderComponent {
navigateWithState(dest: string, state: any) {
this.router.navigate([dest], { state: state });
}
login() {
this.keycloakService.login({
redirectUri: `${window.location.origin}/login${this.router.routerState.snapshot.url}`,
});
}
isActive(route: string): boolean {
return this.router.url === route;
@ -192,9 +184,7 @@ export class HeaderComponent {
return 0;
}
}
isAdmin() {
return this.keycloakService.getUserRoles(true).includes('ADMIN');
}
sortBy(sortBy: SortByOptions) {
this.criteria.sortBy = sortBy;
this.sortDropdownVisible = false;
@ -203,4 +193,7 @@ export class HeaderComponent {
toggleSortDropdown() {
this.sortDropdownVisible = !this.sortDropdownVisible;
}
isAdmin() {
return isAdmin(this.user.email);
}
}

View File

@ -1,7 +1,7 @@
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { KeycloakService } from 'keycloak-angular';
import { AuthService } from '../../services/auth.service';
@Component({
@ -11,9 +11,7 @@ import { AuthService } from '../../services/auth.service';
template: ``,
})
export class LogoutComponent {
constructor(public keycloakService: KeycloakService, private authService: AuthService, private router: Router) {
//sessionStorage.removeItem('USERID');
//keycloakService.logout(window.location.origin + '/home');
constructor(private authService: AuthService, private router: Router) {
this.authService.logout();
this.router.navigate(['/home']);
}

View File

@ -6,39 +6,6 @@ const logger = createLogger('AuthGuard');
@Injectable({
providedIn: 'root',
})
// export class AuthGuard extends KeycloakAuthGuard {
// constructor(protected override readonly router: Router, protected readonly keycloak: KeycloakService, private keycloakInitializer: KeycloakInitializerService) {
// super(router, keycloak);
// }
// async isAccessAllowed(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean | UrlTree> {
// logger.info(`--->AuthGuard`);
// while (!this.keycloakInitializer.initialized) {
// logger.info(`Waiting 100 msec`);
// await new Promise(resolve => setTimeout(resolve, 100));
// }
// // Force the user to log in if currently unauthenticated.
// const authenticated = this.keycloak.isLoggedIn();
// //this.keycloak.isTokenExpired()
// if (!this.authenticated && !authenticated) {
// await this.keycloak.login({
// redirectUri: window.location.origin + state.url,
// });
// // return false;
// }
// // Get the roles required from the route.
// const requiredRoles = route.data['roles'];
// // Allow the user to proceed if no additional roles are required to access the route.
// if (!Array.isArray(requiredRoles) || requiredRoles.length === 0) {
// return true;
// }
// // Allow the user to proceed if all the required roles are present.
// return requiredRoles.every(role => this.roles.includes(role));
// }
// }
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}

View File

@ -2,7 +2,6 @@ import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { LeafletModule } from '@bluehalo/ngx-leaflet';
import { KeycloakService } from 'keycloak-angular';
import { ShareButton } from 'ngx-sharebuttons/button';
import { lastValueFrom } from 'rxjs';
import { BusinessListing, EventTypeEnum, ShareByEMail, User } from '../../../../../../bizmatch-server/src/models/db.model';
@ -22,7 +21,7 @@ import { MailService } from '../../../services/mail.service';
import { SelectOptionsService } from '../../../services/select-options.service';
import { UserService } from '../../../services/user.service';
import { SharedModule } from '../../../shared/shared/shared.module';
import { createMailInfo, map2User } from '../../../utils/utils';
import { createMailInfo, isAdmin, map2User } from '../../../utils/utils';
// Import für Leaflet
// Benannte Importe für Leaflet
import { AuthService } from '../../../services/auth.service';
@ -75,7 +74,6 @@ export class DetailsBusinessListingComponent extends BaseDetailsComponent {
private mailService: MailService,
private sanitizer: DomSanitizer,
public historyService: HistoryService,
public keycloakService: KeycloakService,
private validationMessagesService: ValidationMessagesService,
private messageService: MessageService,
private auditService: AuditService,
@ -94,7 +92,6 @@ export class DetailsBusinessListingComponent extends BaseDetailsComponent {
}
async ngOnInit() {
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
this.keycloakUser = map2User(token);
if (this.keycloakUser) {
@ -119,7 +116,7 @@ export class DetailsBusinessListingComponent extends BaseDetailsComponent {
this.validationMessagesService.clearMessages(); // Löschen Sie alle bestehenden Validierungsnachrichten
}
isAdmin() {
return this.keycloakService.getUserRoles(true).includes('ADMIN');
return isAdmin(this.keycloakUser.email); //this.keycloakService.getUserRoles(true).includes('ADMIN');
}
async mail() {
try {

View File

@ -3,7 +3,6 @@ import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { LeafletModule } from '@bluehalo/ngx-leaflet';
import { faTimes } from '@fortawesome/free-solid-svg-icons';
import { KeycloakService } from 'keycloak-angular';
import { GalleryModule, ImageItem } from 'ng-gallery';
import { ShareButton } from 'ngx-sharebuttons/button';
import { lastValueFrom } from 'rxjs';
@ -25,7 +24,7 @@ import { MailService } from '../../../services/mail.service';
import { SelectOptionsService } from '../../../services/select-options.service';
import { UserService } from '../../../services/user.service';
import { SharedModule } from '../../../shared/shared/shared.module';
import { createMailInfo, map2User } from '../../../utils/utils';
import { createMailInfo, isAdmin, map2User } from '../../../utils/utils';
import { BaseDetailsComponent } from '../base-details.component';
@Component({
@ -78,7 +77,6 @@ export class DetailsCommercialPropertyListingComponent extends BaseDetailsCompon
private mailService: MailService,
private sanitizer: DomSanitizer,
public historyService: HistoryService,
public keycloakService: KeycloakService,
private imageService: ImageService,
private ngZone: NgZone,
private validationMessagesService: ValidationMessagesService,
@ -92,7 +90,6 @@ export class DetailsCommercialPropertyListingComponent extends BaseDetailsCompon
}
async ngOnInit() {
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
this.keycloakUser = map2User(token);
if (this.keycloakUser) {
@ -143,7 +140,7 @@ export class DetailsCommercialPropertyListingComponent extends BaseDetailsCompon
});
}
isAdmin() {
return this.keycloakService.getUserRoles(true).includes('ADMIN');
return isAdmin(this.keycloakUser.email);
}
async mail() {
try {

View File

@ -1,7 +1,6 @@
import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { KeycloakService } from 'keycloak-angular';
import { Observable } from 'rxjs';
import { BusinessListing, CommercialPropertyListing, User } from '../../../../../../bizmatch-server/src/models/db.model';
import { KeycloakUser, emailToDirName } from '../../../../../../bizmatch-server/src/models/main.model';
@ -13,7 +12,7 @@ import { ListingsService } from '../../../services/listings.service';
import { SelectOptionsService } from '../../../services/select-options.service';
import { UserService } from '../../../services/user.service';
import { SharedModule } from '../../../shared/shared/shared.module';
import { formatPhoneNumber, map2User } from '../../../utils/utils';
import { formatPhoneNumber, isAdmin, map2User } from '../../../utils/utils';
@Component({
selector: 'app-details-user',
@ -46,7 +45,6 @@ export class DetailsUserComponent {
private sanitizer: DomSanitizer,
private imageService: ImageService,
public historyService: HistoryService,
public keycloakService: KeycloakService,
private authService: AuthService,
) {}
@ -56,8 +54,6 @@ export class DetailsUserComponent {
// Zuweisen der Ergebnisse zu den Member-Variablen der Klasse
this.businessListings = results[0];
this.commercialPropListings = results[1] as CommercialPropertyListing[];
//this.user$ = this.userService.getUserObservable();
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
this.keycloakUser = map2User(token);
this.companyOverview = this.sanitizer.bypassSecurityTrustHtml(this.user.companyOverview ? this.user.companyOverview : '');
@ -65,6 +61,6 @@ export class DetailsUserComponent {
}
isAdmin() {
return this.keycloakService.getUserRoles(true).includes('ADMIN');
return isAdmin(this.user.email);
}
}

View File

@ -23,8 +23,8 @@
@if(user){
<a routerLink="/account" class="text-white text-xl py-2">Account</a>
} @else {
<a (click)="login()" class="text-white text-xl py-2">Log In</a>
<a routerLink="/pricing" class="text-white text-xl py-2">Register</a>
<a routerLink="/login" [queryParams]="{ mode: 'login' }" class="text-white text-xl py-2">Log In</a>
<a routerLink="/login" [queryParams]="{ mode: 'register' }" class="text-white text-xl py-2">Register</a>
}
<button (click)="toggleMenu()" class="text-white mt-4">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">

View File

@ -5,7 +5,6 @@ import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { NgSelectModule } from '@ng-select/ng-select';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { initFlowbite } from 'flowbite';
import { KeycloakService } from 'keycloak-angular';
import { catchError, concat, debounceTime, distinctUntilChanged, lastValueFrom, Observable, of, Subject, Subscription, switchMap, tap } from 'rxjs';
import { BusinessListingCriteria, CityAndStateResult, CommercialPropertyListingCriteria, GeoResult, KeycloakUser, UserListingCriteria } from '../../../../../bizmatch-server/src/models/main.model';
import { ModalService } from '../../components/search-modal/modal.service';
@ -72,7 +71,7 @@ export class HomeComponent {
private searchService: SearchService,
private activatedRoute: ActivatedRoute,
public selectOptions: SelectOptionsService,
public keycloakService: KeycloakService,
private criteriaChangeService: CriteriaChangeService,
private geoService: GeoService,
public cdRef: ChangeDetectorRef,
@ -85,7 +84,7 @@ export class HomeComponent {
setTimeout(() => {
initFlowbite();
}, 0);
//const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
sessionStorage.removeItem('businessListings');
sessionStorage.removeItem('commercialPropertyListings');
@ -115,14 +114,14 @@ export class HomeComponent {
private setupCriteriaChangeListener() {
this.criteriaChangeSubscription = this.criteriaChangeService.criteriaChange$.pipe(untilDestroyed(this), debounceTime(400)).subscribe(() => this.setTotalNumberOfResults());
}
login() {
this.keycloakService.login({
redirectUri: `${window.location.origin}/login${this.router.routerState.snapshot.url}`,
});
}
register() {
this.keycloakService.register({ redirectUri: `${window.location.origin}/account` });
}
// login() {
// this.keycloakService.login({
// redirectUri: `${window.location.origin}/login${this.router.routerState.snapshot.url}`,
// });
// }
// register() {
// this.keycloakService.register({ redirectUri: `${window.location.origin}/account` });
// }
toggleMenu() {
this.isMenuOpen = !this.isMenuOpen;
}

View File

@ -1,7 +1,7 @@
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { KeycloakService } from 'keycloak-angular';
import { lastValueFrom } from 'rxjs';
import { AuthService } from '../../services/auth.service';
import { SubscriptionsService } from '../../services/subscriptions.service';
@ -19,13 +19,12 @@ export class LoginComponent {
constructor(
public userService: UserService,
private activatedRoute: ActivatedRoute,
private keycloakService: KeycloakService,
private router: Router,
private subscriptionService: SubscriptionsService,
private authService: AuthService,
) {}
async ngOnInit() {
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
const keycloakUser = map2User(token);
const email = keycloakUser.email;

View File

@ -1,7 +1,6 @@
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { KeycloakService } from 'keycloak-angular';
import { StripeService } from 'ngx-stripe';
import { switchMap } from 'rxjs';
import { User } from '../../../../../bizmatch-server/src/models/db.model';
@ -27,7 +26,6 @@ export class PricingComponent {
keycloakUser: KeycloakUser;
user: User;
constructor(
public keycloakService: KeycloakService,
private http: HttpClient,
private stripeService: StripeService,
private activatedRoute: ActivatedRoute,
@ -38,7 +36,6 @@ export class PricingComponent {
) {}
async ngOnInit() {
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
this.keycloakUser = map2User(token);
if (this.keycloakUser) {
@ -59,19 +56,6 @@ export class PricingComponent {
this.checkout({ priceId: atob(base64PriceId), email: this.keycloakUser.email, name: `${this.keycloakUser.firstName} ${this.keycloakUser.lastName}` });
}
}
// if (this.id === 'free' || this.keycloakUser.priceId === 'free') {
// this.user.subscriptionPlan = 'free';
// await this.userService.saveGuaranteed(this.user);
// this.router.navigate([`/account`]);
// } else if (this.id || this.keycloakUser.priceId) {
// const priceId = this.id ? this.id : this.keycloakUser.priceId;
// this.checkout({ priceId: atob(priceId), email: this.keycloakUser.email, name: `${this.keycloakUser.firstName} ${this.keycloakUser.lastName}` });
// } else if (!this.id && !this.pricingOverview) {
// this.user = await this.userService.getByMail(this.keycloakUser.email);
// if (this.user.subscriptionId) {
// this.router.navigate([`/account`]);
// }
// }
} else {
this.pricingOverview = false;
}
@ -88,13 +72,13 @@ export class PricingComponent {
this.checkout({ priceId: priceId, email: this.keycloakUser.email, name: `${this.keycloakUser.firstName} ${this.keycloakUser.lastName}` });
}
} else {
if (priceId) {
this.keycloakService.register({
redirectUri: `${window.location.origin}/pricing/${btoa(priceId)}`,
});
} else {
this.keycloakService.register({ redirectUri: `${window.location.origin}/pricing/free` });
}
// if (priceId) {
// this.keycloakService.register({
// redirectUri: `${window.location.origin}/pricing/${btoa(priceId)}`,
// });
// } else {
// this.keycloakService.register({ redirectUri: `${window.location.origin}/pricing/free` });
// }
}
}

View File

@ -4,7 +4,7 @@ import { ActivatedRoute, Router } from '@angular/router';
import { faTrash } from '@fortawesome/free-solid-svg-icons';
import { NgSelectModule } from '@ng-select/ng-select';
import { initFlowbite } from 'flowbite';
import { KeycloakService } from 'keycloak-angular';
import { NgxCurrencyDirective } from 'ngx-currency';
import { ImageCropperComponent } from 'ngx-image-cropper';
import { QuillModule } from 'ngx-quill';
@ -34,7 +34,7 @@ import { SharedService } from '../../../services/shared.service';
import { SubscriptionsService } from '../../../services/subscriptions.service';
import { UserService } from '../../../services/user.service';
import { SharedModule } from '../../../shared/shared/shared.module';
import { checkAndUpdate, map2User } from '../../../utils/utils';
import { checkAndUpdate, isAdmin, map2User } from '../../../utils/utils';
import { TOOLBAR_OPTIONS } from '../../utils/defaults';
@Component({
selector: 'app-account',
@ -89,7 +89,6 @@ export class AccountComponent {
private loadingService: LoadingService,
private imageUploadService: ImageService,
private imageService: ImageService,
private keycloakService: KeycloakService,
private confirmationService: ConfirmationService,
private messageService: MessageService,
private sharedService: SharedService,
@ -107,7 +106,6 @@ export class AccountComponent {
if (this.id) {
this.user = await this.userService.getById(this.id);
} else {
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
const keycloakUser = map2User(token);
const email = keycloakUser.email;
@ -268,7 +266,7 @@ export class AccountComponent {
return message ? message.message : '';
}
isAdmin() {
return this.keycloakService.getUserRoles(true).includes('ADMIN');
return isAdmin(this.user.email);
}
setState(index: number, state: string) {
if (state === null) {

View File

@ -7,7 +7,6 @@ import { map2User, routeListingWithState } from '../../../utils/utils';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { faTrash } from '@fortawesome/free-solid-svg-icons';
import { KeycloakService } from 'keycloak-angular';
import { QuillModule } from 'ngx-quill';
import { NgSelectModule } from '@ng-select/ng-select';
@ -86,7 +85,6 @@ export class EditBusinessListingComponent {
private loadingService: LoadingService,
private messageService: MessageService,
private route: ActivatedRoute,
private keycloakService: KeycloakService,
private validationMessagesService: ValidationMessagesService,
private authService: AuthService,
) {
@ -105,7 +103,6 @@ export class EditBusinessListingComponent {
});
}
async ngOnInit() {
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
const keycloakUser = map2User(token);
this.listingUser = await this.userService.getByMail(keycloakUser.email);

View File

@ -9,7 +9,6 @@ import { DragDropModule } from '@angular/cdk/drag-drop';
import { ViewportRuler } from '@angular/cdk/scrolling';
import { faTrash } from '@fortawesome/free-solid-svg-icons';
import { NgSelectModule } from '@ng-select/ng-select';
import { KeycloakService } from 'keycloak-angular';
import { NgxCurrencyDirective } from 'ngx-currency';
import { ImageCropperComponent } from 'ngx-image-cropper';
import { QuillModule } from 'ngx-quill';
@ -123,7 +122,6 @@ export class EditCommercialPropertyListingComponent {
private loadingService: LoadingService,
private route: ActivatedRoute,
private keycloakService: KeycloakService,
private cdr: ChangeDetectorRef,
private confirmationService: ConfirmationService,
private messageService: MessageService,
@ -147,7 +145,6 @@ export class EditCommercialPropertyListingComponent {
});
}
async ngOnInit() {
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
const keycloakUser = map2User(token);
const email = keycloakUser.email;

View File

@ -1,6 +1,4 @@
import { Component } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
import { User } from '../../../../../../bizmatch-server/src/models/db.model';
import { ErrorResponse, KeycloakUser, MailInfo } from '../../../../../../bizmatch-server/src/models/main.model';
import { MessageService } from '../../../components/message/message.service';
@ -31,7 +29,6 @@ export class EmailUsComponent {
constructor(
private mailService: MailService,
private userService: UserService,
public keycloakService: KeycloakService,
private validationMessagesService: ValidationMessagesService,
private messageService: MessageService,
public selectOptions: SelectOptionsService,
@ -41,7 +38,6 @@ export class EmailUsComponent {
this.mailinfo = createMailInfo();
}
async ngOnInit() {
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
this.keycloakUser = map2User(token);
if (this.keycloakUser) {

View File

@ -1,5 +1,4 @@
import { Component } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
import { BusinessListing, CommercialPropertyListing } from '../../../../../../bizmatch-server/src/models/db.model';
import { KeycloakUser } from '../../../../../../bizmatch-server/src/models/main.model';
import { ConfirmationComponent } from '../../../components/confirmation/confirmation.component';
@ -21,15 +20,8 @@ export class FavoritesComponent {
user: KeycloakUser;
// listings: Array<ListingType> = []; //= dataListings as unknown as Array<BusinessListing>;
favorites: Array<BusinessListing | CommercialPropertyListing>;
constructor(
public keycloakService: KeycloakService,
private listingsService: ListingsService,
public selectOptions: SelectOptionsService,
private confirmationService: ConfirmationService,
private authService: AuthService,
) {}
constructor(private listingsService: ListingsService, public selectOptions: SelectOptionsService, private confirmationService: ConfirmationService, private authService: AuthService) {}
async ngOnInit() {
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
this.user = map2User(token);
const result = await Promise.all([await this.listingsService.getFavoriteListings('business'), await this.listingsService.getFavoriteListings('commercialProperty')]);

View File

@ -1,5 +1,4 @@
import { ChangeDetectorRef, Component } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
import { CommercialPropertyListing, User } from '../../../../../../bizmatch-server/src/models/db.model';
import { ListingType } from '../../../../../../bizmatch-server/src/models/main.model';
import { ConfirmationComponent } from '../../../components/confirmation/confirmation.component';
@ -27,7 +26,6 @@ export class MyListingComponent {
user: User;
constructor(
public userService: UserService,
public keycloakService: KeycloakService,
private listingsService: ListingsService,
private cdRef: ChangeDetectorRef,
public selectOptions: SelectOptionsService,
@ -36,8 +34,6 @@ export class MyListingComponent {
private authService: AuthService,
) {}
async ngOnInit() {
// const keycloakUser = this.userService.getKeycloakUser();
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
const keycloakUser = map2User(token);
const email = keycloakUser.email;
@ -62,14 +58,5 @@ export class MyListingComponent {
// this.messageService.showMessage('Listing has been deleted');
this.deleteListing(listing);
}
// this.confirmationService.confirm({
// target: event.target as EventTarget,
// message: 'Are you sure you want to delet this listing?',
// icon: 'pi pi-exclamation-triangle',
// accept: () => {
// this.messageService.add({ severity: 'info', summary: 'Confirmed', detail: 'Listing has been deleted', life: 3000 });
// this.deleteListing(listing);
// },
// });
}
}

View File

@ -1,7 +1,6 @@
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { KeycloakService } from 'keycloak-angular';
import { User } from '../../../../../bizmatch-server/src/models/db.model';
import { AuditService } from '../../services/audit.service';
import { AuthService } from '../../services/auth.service';
@ -19,12 +18,11 @@ export class SuccessComponent {
user: User;
maxAttemptsReached: boolean = false; // Neue Variable hinzufügen
constructor(private keycloakService: KeycloakService, private userService: UserService, private auditService: AuditService, private router: Router, private authService: AuthService) {}
constructor(private userService: UserService, private auditService: AuditService, private router: Router, private authService: AuthService) {}
async ngOnInit() {
let email = null;
try {
// const token = await this.keycloakService.getToken();
const token = await this.authService.getToken();
const keycloakUser = map2User(token);
email = keycloakUser.email;

View File

@ -1,10 +1,10 @@
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandler, Injectable } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
import { Router } from '@angular/router';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(private keycloakService: KeycloakService) {}
constructor(private router: Router) {}
handleError(error: any): void {
// Prüfe, ob es sich um einen HttpErrorResponse handelt
@ -12,9 +12,7 @@ export class GlobalErrorHandler implements ErrorHandler {
// Prüfe, ob es ein 401 Unauthorized Fehler ist
if (error.status === 401) {
// Führe den Login-Prozess über Keycloak aus
this.keycloakService.login({
redirectUri: window.location.href, // oder eine benutzerdefinierte URL
});
this.router.navigate(['/login-register']);
}
}

View File

@ -1,34 +1,33 @@
import { Injectable } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
import { environment } from '../../environments/environment';
import { createLogger } from '../utils/utils';
const logger = createLogger('KeycloakInitializerService');
@Injectable({ providedIn: 'root' })
export class KeycloakInitializerService {
public initialized = false;
constructor(private keycloakService: KeycloakService) {}
constructor() {}
async initialize(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
try {
await this.keycloakService.init({
config: {
url: environment.keycloak.url,
realm: environment.keycloak.realm,
clientId: environment.keycloak.clientId,
},
initOptions: {
onLoad: 'check-sso',
silentCheckSsoRedirectUri: (<any>window).location.origin + '/assets/silent-check-sso.html',
},
bearerExcludedUrls: ['/assets'],
});
this.initialized = true;
resolve(true);
} catch (error) {
reject(error);
}
});
}
// async initialize(): Promise<boolean> {
// return new Promise<boolean>(async (resolve, reject) => {
// try {
// await this.keycloakService.init({
// config: {
// url: environment.keycloak.url,
// realm: environment.keycloak.realm,
// clientId: environment.keycloak.clientId,
// },
// initOptions: {
// onLoad: 'check-sso',
// silentCheckSsoRedirectUri: (<any>window).location.origin + '/assets/silent-check-sso.html',
// },
// bearerExcludedUrls: ['/assets'],
// });
// this.initialized = true;
// resolve(true);
// } catch (error) {
// reject(error);
// }
// });
// }
}

View File

@ -340,3 +340,6 @@ export function createEnhancedProxy(obj: BusinessListingCriteria | CommercialPro
}
});
}
export function isAdmin(email: string) {
return 'andreas.knuth@gmail.com' === email;
}