mirror of
https://github.com/openpgpjs/openpgpjs.git
synced 2025-11-24 14:35:51 +00:00
refactor: Simplify User ID parsing
This commit is contained in:
parent
b31bc89854
commit
b45305a5e4
@ -87,15 +87,36 @@ class UserIDPacket {
|
|||||||
* The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`,
|
* The `name` and `comment` parts can include any letters, whitespace, and symbols, except for `(` and `)`,
|
||||||
* since they interfere with `comment` parsing.
|
* since they interfere with `comment` parsing.
|
||||||
*/
|
*/
|
||||||
const re = /^(?<name>[^()]+\s+)?(?<comment>\([^()]+\)\s+)?(?<email><\S+@\S+>)$/;
|
|
||||||
const matches = re.exec(userID);
|
const isValidEmail = str => /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(str);
|
||||||
if (matches !== null) {
|
const firstBracket = userID.indexOf('<');
|
||||||
const { name, comment, email } = matches.groups;
|
const lastBracket = userID.lastIndexOf('>');
|
||||||
this.comment = comment?.replace(/^\(|\)|\s$/g, '').trim() || ''; // remove parenthesis and separating whiltespace
|
if (
|
||||||
this.name = name?.trim() || '';
|
firstBracket !== -1 &&
|
||||||
this.email = email.substring(1, email.length - 1); // remove brackets
|
lastBracket !== -1 &&
|
||||||
} else if (/^[^\s@]+@[^\s@]+$/.test(userID)) { // unbracketed email: enforce single @ and no whitespace
|
lastBracket > firstBracket
|
||||||
this.email = userID;
|
) {
|
||||||
|
const potentialEmail = userID.substring(firstBracket + 1, lastBracket);
|
||||||
|
if (isValidEmail(potentialEmail)) {
|
||||||
|
this.email = potentialEmail;
|
||||||
|
const beforeEmail = userID.substring(0, firstBracket).trim();
|
||||||
|
const firstParen = beforeEmail.indexOf('(');
|
||||||
|
const lastParen = beforeEmail.lastIndexOf(')');
|
||||||
|
if (firstParen !== -1 && lastParen !== -1 && lastParen > firstParen) {
|
||||||
|
this.comment = beforeEmail
|
||||||
|
.substring(firstParen + 1, lastParen)
|
||||||
|
.trim();
|
||||||
|
this.name = beforeEmail.substring(0, firstParen).trim();
|
||||||
|
} else {
|
||||||
|
this.name = beforeEmail;
|
||||||
|
this.comment = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (isValidEmail(userID.trim())) {
|
||||||
|
// unbracketed email case
|
||||||
|
this.email = userID.trim();
|
||||||
|
this.name = '';
|
||||||
|
this.comment = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
this.userID = userID;
|
this.userID = userID;
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user