Skip to content

Commit

Permalink
Refactoring the flag.validate function to reduce complexity
Browse files Browse the repository at this point in the history
  • Loading branch information
ssaigh committed Sep 2, 2024
1 parent 09ad0fe commit e9dbb88
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions src/flags.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,8 @@ Flags.sort = async function (flagIds, sort) {
return flagIds;
};

// help from ChatGPT

Flags.validate = async function (payload) {
const [target, reporter] = await Promise.all([
Flags.getTarget(payload.type, payload.id, payload.uid),
Expand All @@ -281,19 +283,22 @@ Flags.validate = async function (payload) {

if (!target) {
throw new Error('[[error:invalid-data]]');
} else if (target.deleted) {
}
if (target.deleted) {
throw new Error('[[error:post-deleted]]');
} else if (!reporter || !reporter.userslug) {
}
if (!reporter || !reporter.userslug) {
throw new Error('[[error:no-user]]');
} else if (reporter.banned) {
}
if (reporter.banned) {
throw new Error('[[error:user-banned]]');
}

// Disallow flagging of profiles/content of privileged users
const [targetPrivileged, reporterPrivileged] = await Promise.all([
user.isPrivileged(target.uid),
user.isPrivileged(reporter.uid),
]);

if (targetPrivileged && !reporterPrivileged) {
throw new Error('[[error:cant-flag-privileged]]');
}
Expand All @@ -303,19 +308,25 @@ Flags.validate = async function (payload) {
if (!editable.flag && !meta.config['reputation:disabled'] && reporter.reputation < meta.config['min:rep:flag']) {
throw new Error(`[[error:not-enough-reputation-to-flag, ${meta.config['min:rep:flag']}]]`);
}
} else if (payload.type === 'user') {
return;
}

if (payload.type === 'user') {
if (parseInt(payload.id, 10) === parseInt(payload.uid, 10)) {
throw new Error('[[error:cant-flag-self]]');
}
const editable = await privileges.users.canEdit(payload.uid, payload.id);
if (!editable && !meta.config['reputation:disabled'] && reporter.reputation < meta.config['min:rep:flag']) {
throw new Error(`[[error:not-enough-reputation-to-flag, ${meta.config['min:rep:flag']}]]`);
}
} else {
throw new Error('[[error:invalid-data]]');
return;
}

throw new Error('[[error:invalid-data]]');
};



Flags.getNotes = async function (flagId) {
let notes = await db.getSortedSetRevRangeWithScores(`flag:${flagId}:notes`, 0, -1);
notes = await modifyNotes(notes);
Expand Down

0 comments on commit e9dbb88

Please sign in to comment.