docbrown/app/javascript/packs/applyApplicationPolicyToggles.js
Jeremy Friesen c3c884f4d0
Conditional rendering of "Create Post" link (#17076)
* WIP - Conditional rendering of "Create Post" link

This PR builds on the conversation from forem/forem#17056 and moves in a
slightly different direction.

Important in all of this is that the ability to create a post is
enforced on the server.  If the "Create Post" button were to be visible
but the user couldn't create a post when they clicked the button, they
would get an authorization error (or some such response).

This PR posits a different and perhaps competing approach to
forem/forem#16606.  This PR provides a general approach in which we add
class attributes in our HTML erb files.

Note: I have not included Cypress tests as I don't want to yet commit
that time.  I'm also wondering if this is the "right" thing to do.  I
definitely think we want to add some JS tests.  But could we do JS and
unit tests?  (How do we reach consensus regarding our test approach?)

Again, thank you for the conversation and expect an even more "complete"
PR after we have our discussion.

* Extracting AsyncInfo model to ease testing

* Renaming forbidden to visible

* Adding cypress test to assert no 'Create Post'

These are always treacherous.  What happens when we rename the button?
The test will continue to work.

* Apply suggestions from code review

Co-authored-by: Suzanne Aitchison <suzanne@forem.com>

* Switching to pack file for policy

Follows on [Suzanne's comment](https://github.com/forem/forem/pull/17076#issuecomment-1088567286)

* Update app/javascript/packs/applyApplicationPolicyToggles.js

Co-authored-by: Suzanne Aitchison <suzanne@forem.com>

Co-authored-by: Suzanne Aitchison <suzanne@forem.com>
2022-04-05 12:47:12 -04:00

26 lines
1,005 B
JavaScript

import { getUserDataAndCsrfToken } from '@utilities/getUserDataAndCsrfToken';
/**
* Responsible for hiding or showing elements that match each of the given user
* policies. While this function is "oblivious" to what it's hiding, it
* coordinates between the rendered HTML and the user data to show or hide
* elements that present functionality available or not available to the given
* user.
*
* A critical assumption is that we are not employing "security through
* obscurity". That is to say, if we accidentally show the link, the server
* will enforce the correct policy.
*/
getUserDataAndCsrfToken().then(({ currentUser }) => {
if (currentUser.policies) {
currentUser.policies.forEach((policy) => {
const elements = document.getElementsByClassName(policy.dom_class);
for (const element of elements) {
if (policy.visible) {
element.classList.remove('hidden');
} else {
element.classList.add('hidden');
}
}
});
}
});