Files
doneit-web/src/app/services/DomSanitizer.service.ts
T
2023-12-01 12:19:20 +01:00

80 lines
2.1 KiB
TypeScript

import { Injectable, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { Router } from '@angular/router';
import DOMPurify from 'dompurify';
@Injectable({
providedIn: 'root'
})
export class DomSanitizerService {
constructor(private sanitizer: DomSanitizer) {
}
sanitizeInput(input: string) {
// Encode special characters to prevent XSS attacks
const encodedInput = this.encodeSpecialCharacters(input);
// Use DomSanitizer to sanitize the content
return this.sanitizer.sanitize(SecurityContext.HTML, encodedInput);
}
private encodeSpecialCharacters(input: string): string {
const specialCharactersMap: Record<string, string> = {
'!': '&#33;',
'@': '&#64;',
'#': '&#35;',
'$': '&#36;',
'%': '&#37;',
'^': '&#94;',
'&': '&#38;',
'*': '&#42;',
'(': '&#40;',
')': '&#41;',
'-': '&#45;',
'_': '&#95;',
'+': '&#43;',
'=': '&#61;',
'{': '&#123;',
'}': '&#125;',
'|': '&#124;',
'\\': '&#92;',
':': '&#58;',
';': '&#59;',
'"': '&#34;',
"'": '&#39;',
'<': '&#60;',
'>': '&#62;',
',': '&#44;',
'.': '&#46;',
'?': '&#63;',
'/': '&#47;',
'ã': '&atilde;', // ã
'ç': '&ccedil;', // ç
'Â': '&Acirc;', // Â
'â': '&acirc;', // â
'Ã': '&Atilde;', // Ã
};
return input.replace(/[!@#$%^&*()-_+=\{\}|\\:;"'<>,.?/ãçÂâÃ]/g, match => specialCharactersMap[match] || match);
}
// private encodeSpecialCharacters(input: string): string {
// You can use a library like DOMPurify to encode special characters
// return DOMPurify.sanitize(input);
// If you don't want to use an external library, you can manually encode
// Here's a simple example, you may need to extend this based on your requirements
/* return input.replace(/</g, '&lt;').replace(/>/g, '&gt;'); */
// }
/* sanitizeInput(input: string): string {
return this.sanitizer.sanitize(SecurityContext.HTML, input);
} */
}