Add auth into who can edit a part

This commit is contained in:
Kurt Hutten
2020-11-07 21:44:12 +11:00
parent a009efafac
commit f6964c0f78
3 changed files with 41 additions and 16 deletions

View File

@@ -1,31 +1,43 @@
import { AuthenticationError, ForbiddenError, parseJWT } from '@redwoodjs/api'
import { db } from 'src/lib/db'
export const requireOwnership = async ({ id, userName } = {}) => {
export const requireOwnership = async ({ userId, userName, partId } = {}) => {
// IMPORTANT, don't forget to await this function, as it will only block
// unwanted db actions if it has time to look up resources in the db.
if (!context.currentUser) {
throw new AuthenticationError("You don't have permission to do that.")
}
if(!id && !userName) {
if(!userId && !userName && !partId) {
throw new ForbiddenError("You don't have access to do that.")
}
const netlifyUserId = context.currentUser?.sub
if(id && id !== netlifyUserId) {
throw new ForbiddenError("You don't own this resource.")
}
if(context.currentUser.roles?.includes('admin')) {
return
}
const user = await db.user.findOne({
where: { userName },
})
console.log(user, 'USER')
if(!user) {
const netlifyUserId = context.currentUser?.sub
if(userId && userId !== netlifyUserId) {
throw new ForbiddenError("You don't own this resource.")
}
if(userName) {
const user = await db.user.findOne({
where: { userName },
})
if(!user || user.id !== netlifyUserId) {
throw new ForbiddenError("You don't own this resource.")
}
}
if(partId) {
const user = await db.part.findOne({
where: { id: partId },
}).user()
if(!user || user.id !== netlifyUserId) {
throw new ForbiddenError("You don't own this resource.")
}
}
}