moved hasRight into Role class

defined roles better
This commit is contained in:
Ulf Gebhardt 2021-11-21 18:01:33 +01:00
parent a24c6119a6
commit a3b87c39bf
Signed by: ulfgebhardt
GPG Key ID: DA6B843E748679C9
4 changed files with 27 additions and 30 deletions

View File

@ -2,10 +2,8 @@ import { INALIENABLE_RIGHTS } from './INALIENABLE_RIGHTS'
import { RIGHTS } from './RIGHTS'
import { Role } from './Role'
// TODO from database
export const ROLES = [
new Role('unauthorized', INALIENABLE_RIGHTS), // inalienable rights
new Role('user', [
export const ROLE_UNAUTHORIZED = new Role('unauthorized', INALIENABLE_RIGHTS)
export const ROLE_USER = new Role('user', [
...INALIENABLE_RIGHTS,
RIGHTS.BALANCE,
RIGHTS.LIST_GDT_ENTRIES,
@ -19,6 +17,8 @@ export const ROLES = [
RIGHTS.LOGOUT,
RIGHTS.UPDATE_USER_INFOS,
RIGHTS.HAS_ELOPAGE,
]),
new Role('admin', Object.values(RIGHTS)), // all rights
]
])
export const ROLE_ADMIN = new Role('admin', Object.values(RIGHTS)) // all rights
// TODO from database
export const ROLES = [ROLE_UNAUTHORIZED, ROLE_USER, ROLE_ADMIN]

View File

@ -8,4 +8,8 @@ export class Role {
this.id = id
this.rights = rights
}
hasRight = (right: RIGHTS): boolean => {
return this.rights.includes(right)
}
}

View File

@ -1,6 +0,0 @@
import { RIGHTS } from './RIGHTS'
import { Role } from './Role'
export const hasRight = (right: RIGHTS, role: Role): boolean => {
return role.rights.includes(right)
}

View File

@ -3,12 +3,11 @@
import { AuthChecker } from 'type-graphql'
import { decode, encode } from '../../auth/JWT'
import { ROLES } from '../../auth/ROLES'
import { hasRight } from '../../auth/hasRight'
import { ROLE_USER, ROLE_UNAUTHORIZED } from '../../auth/ROLES'
import { RIGHTS } from '../../auth/RIGHTS'
const isAuthorized: AuthChecker<any> = async ({ context }, rights) => {
context.role = ROLES[0] // unauthorized user
context.role = ROLE_UNAUTHORIZED // unauthorized user
// Do we have a token?
if (context.token) {
@ -22,11 +21,11 @@ const isAuthorized: AuthChecker<any> = async ({ context }, rights) => {
// set new header token
context.setHeaders.push({ key: 'token', value: encode(decoded.pubKey) })
// TODO - load from database dynamically & admin - maybe encode this in the token to prevent many database requests
context.role = ROLES[1] // logged in user
context.role = ROLE_USER // logged in user
}
// check for correct rights
const missingRights = (<RIGHTS[]>rights).filter((right) => !hasRight(right, context.role))
const missingRights = (<RIGHTS[]>rights).filter((right) => !context.role.hasRight(right))
if (missingRights.length !== 0) {
throw new Error('401 Unauthorized')
}