feat(fullstack): Set user roles per orga, scope notification to orga and role, add orga and role to JWT

This commit is contained in:
2025-09-15 19:23:06 +02:00
parent 83f1fa71b6
commit e3643d8318
25 changed files with 575 additions and 287 deletions

View File

@@ -8,20 +8,50 @@ import {
worksCouncilMemberRole,
employeeRole,
adminRole,
ownerRole,
ROLES,
type LegalRole
} from './permissions'
const db = new Database('./sqlite.db')
export const auth = betterAuth({
database: new Database('./sqlite.db'),
database: db,
onAPIError: { throw: true },
emailAndPassword: { enabled: true, autoSignIn: false },
emailAndPassword: { enabled: true, autoSignIn: false, minPasswordLength: 1 },
trustedOrigins: ['http://localhost:3001'],
plugins: [
jwt({
jwt: {
issuer: 'http://192.168.178.114:3001',
expirationTime: '1yr'
expirationTime: '1yr',
definePayload: ({ user, session }) => {
let userRoles: string[] = []
if (session.activeOrganizationId) {
try {
const roleQuery = db.prepare(`
SELECT role
FROM member
WHERE userId = ? AND organizationId = ?
`)
const memberRole = roleQuery.get(user.id, session.activeOrganizationId) as { role: string } | undefined
if (memberRole?.role) {
userRoles = [memberRole.role]
}
} catch (error) {
console.error('Error querying user role:', error)
}
}
return {
id: user.id,
name: user.name,
roles: userRoles,
organizationId: session.activeOrganizationId
}
}
},
jwks: {
keyPairConfig: {
@@ -37,11 +67,10 @@ export const auth = betterAuth({
[ROLES.EMPLOYER]: employerRole,
[ROLES.WORKS_COUNCIL_MEMBER]: worksCouncilMemberRole,
[ROLES.EMPLOYEE]: employeeRole,
[ROLES.ADMIN]: adminRole
[ROLES.ADMIN]: adminRole,
[ROLES.OWNER]: ownerRole
},
// Creator gets admin role by default
creatorRole: ROLES.ADMIN,
creatorRole: ROLES.ADMIN, // OWNER fixen here!
async sendInvitationEmail(data) {
console.log('Sending invitation email', data)
@@ -51,7 +80,8 @@ export const auth = betterAuth({
[ROLES.EMPLOYER]: 'Arbeitgeber',
[ROLES.EMPLOYEE]: 'Arbeitnehmer',
[ROLES.WORKS_COUNCIL_MEMBER]: 'Betriebsrat',
[ROLES.ADMIN]: 'Administrator'
[ROLES.ADMIN]: 'Administrator',
[ROLES.OWNER]: 'Eigentümer'
}
const roleDisplayName = roleDisplayNames[data.role as LegalRole] || data.role
@@ -70,7 +100,7 @@ export const auth = betterAuth({
})
if (result.error) {
throw new Error(`Email sending failed: ${result.error?.statusCode} ${result.error?.error}`)
throw new Error(`Email sending failed: ${result.error.message || result.error.name || 'Unknown error'}`)
}
console.log('Email invite link:', inviteLink)