Thanks for this, this is gold. I’ve been banging my head against authorizations with broadcasting and, in the end, came up with a front-end solution. I basically put some info into the head about the current user:
Then I use this info in a stimulus controller, which shows/hides elements based on what user is present.
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="meta"
export default class extends Controller {
static targets = [ "admin", "user", "published" ]
connect() {
// Data from meta tags
const admin = document.querySelector('meta[name="current-person-admin"]').content
const user = document.querySelector('meta[name="current-person-user"]').content
const id = document.querySelector('meta[name="current-person-id"]').content
const published = document.querySelector('meta[name="current-record-published"]').content
const recordId = document.querySelector('meta[name="current-record-id"]').content
checkAuthorisation(this.userTargets, user)
checkAuthorisation(this.adminTargets, admin)
checkAuthorisationPublished(this.publishedTargets, user)
// Check if user owns record or if user is admin
function checkAuthorisation(elements, subject) {
elements.forEach((element) => {
if (subject === "true" || admin === "true") {
// Do nothing
// element.classList.remove("hidden")
} else {
element.classList.add("hidden")
}
})
}
// Check if record is published, user owns record or if user is admin
function checkAuthorisationPublished(elements, subject) {
elements.forEach((element) => {
if (subject === "true" || admin === "true" || published === "true") {
// Do nothing
// element.classList.remove("hidden")
} else {
element.classList.add("hidden")
}
})
}
}
}
On the view, I just traget the relevant elements e.g:
Very quick question regarding the answers route. Why not adding shallow: true to it so that edit and delete can be performed by just knowing the answer id. After the answer is created, there is no need to carry the question id when it comes to edit or delete it, no?
You can go that route for sure. Personally, I don't like the off chances that an answer could be updated for a different question by accident (if someone is changing the form values via inspect elements).
I haven't used your "template" starting point before. It seems to have devise built in and some generator bootstrap magic. I am sure much more. Can you point me to any doc about it? Thanks.
P.s. this is app
Why not adding shallow: true to it so that edit and delete can be performed by just knowing the answer id. After the answer is created, there is no need to carry the question id when it comes to edit or delete it, no?
I also use a .railsrc file which will set a few defaults whenever I create a new Rails app.
The basic devise install is another template that I have an alias for to apply to an existing template application.