Skip to content

Commit

Permalink
chore: add checkPermissions
Browse files Browse the repository at this point in the history
  • Loading branch information
katallaxie committed Jan 18, 2024
1 parent 6a7b516 commit 15b9522
Show file tree
Hide file tree
Showing 15 changed files with 185 additions and 31 deletions.
1 change: 1 addition & 0 deletions packages/app/src/app/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import TotalSolutionsCard from './components/total-solutions-card'
import LoadingCard from './components/loading-card'
import { Main } from '@/components/main'
import WorkloadsListCard from '@/components/dashboard/workloads-card'
import { api } from '@/trpc/server-http'

export const metadata: Metadata = {
title: 'Dashboard',
Expand Down
8 changes: 1 addition & 7 deletions packages/app/src/components/teams/new-form.action.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,8 @@

import 'server-only'
import { createAction, protectedProcedure } from '@/server/trpc'
import { createTeam } from '@/db/services/teams'
import { TeamsCreateSchema } from '@/server/routers/schemas/teams'

export const rhfAction = createAction(
protectedProcedure
.input(TeamsCreateSchema)
.mutation(
async opts =>
await createTeam({ ...opts.input, userId: opts.ctx.session.user.id })
)
protectedProcedure.input(TeamsCreateSchema).mutation(async opts => {})
)
4 changes: 4 additions & 0 deletions packages/app/src/db/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import { Role } from '../models/roles'
import { Permission } from '../models/permissions'
import { RolePermission } from '../models/roles-permissions'
import { UserRole } from '../models/users-roles'
import { UserTeam } from '../models/users-teams'
import { UserPermission } from '../models/users-permissions'

const env = process.env.NODE_ENV || 'development'
const isProduction = env === 'production'
Expand All @@ -52,7 +54,9 @@ const models = [
SolutionTemplate,
Team,
User,
UserPermission,
UserRole,
UserTeam,
Workload,
WorkloadEnvironment,
WorkloadLens,
Expand Down
54 changes: 49 additions & 5 deletions packages/app/src/db/migrations/20231120145740-added_new_auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,13 @@ module.exports = {
image: {
type: Sequelize.STRING
},
createdAt: {
created_at: {
type: Sequelize.DATE
},
updatedAt: {
updated_at: {
type: Sequelize.DATE
},
deletedAt: {
deleted_at: {
type: Sequelize.DATE
}
})
Expand Down Expand Up @@ -237,6 +237,15 @@ module.exports = {
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
roleId: {
type: Sequelize.BIGINT,
references: {
model: 'roles',
key: 'id'
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
teamId: {
type: Sequelize.UUID,
references: {
Expand All @@ -246,10 +255,37 @@ module.exports = {
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
roleId: {
createdAt: {
type: Sequelize.DATE
},
updatedAt: {
type: Sequelize.DATE
},
deletedAt: {
type: Sequelize.DATE
}
})

await queryInterface.createTable('users-teams', {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
userId: {
type: Sequelize.UUID,
references: {
model: 'roles',
model: 'users',
key: 'id'
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
teamId: {
type: Sequelize.UUID,
references: {
model: 'teams',
key: 'id'
},
onUpdate: 'CASCADE',
Expand All @@ -265,13 +301,21 @@ module.exports = {
type: Sequelize.DATE
}
})

await queryInterface.sequelize.query(
'CREATE VIEW vw_user_teams_permissions AS SELECT A."userId", A."teamId", C.slug as permission FROM "users-roles" AS A LEFT JOIN "roles-permissions" AS B ON A."roleId" = B."roleId" LEFT JOIN "permissions" AS C on B."permissionId" = C.id;'
)
},

async down(queryInterface, Sequelize) {
await queryInterface.dropTable('verification_token')
await queryInterface.dropTable('accounts')
await queryInterface.dropTable('sessions')
await queryInterface.sequelize.query(
'DROP VIEW IF EXISTS vw_user_teams_permissions'
)
await queryInterface.dropTable('users-roles', { cascade: true })
await queryInterface.dropTable('users-teams', { cascade: true })
await queryInterface.dropTable('roles-permissions', { cascade: true })
await queryInterface.dropTable('permissions', { cascade: true })
await queryInterface.dropTable('roles', { cascade: true })
Expand Down
5 changes: 0 additions & 5 deletions packages/app/src/db/models/teams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import {
AllowNull,
Default
} from 'sequelize-typescript'
import { User } from './users'
import { TeamMembers } from './team-members'

export interface TeamAttributes {
id: string
Expand Down Expand Up @@ -54,9 +52,6 @@ export class Team extends Model<TeamAttributes, TeamCreationAttributes> {
@Column
description?: string

@BelongsToMany(() => User, () => TeamMembers, 'teamId', 'userId')
members?: User[]

@CreatedAt
@Column
createdAt?: Date
Expand Down
44 changes: 44 additions & 0 deletions packages/app/src/db/models/users-permissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {
Table,
Model,
Column,
PrimaryKey,
DataType,
AutoIncrement,
ForeignKey,
Unique,
Default,
BelongsToMany,
AllowNull
} from 'sequelize-typescript'

export interface UserPermissionAttributes {
id: bigint
userId: string
teamId: string
permission: string
}

export type UserPermissionCreationAttributes = Omit<
UserPermissionAttributes,
'id'
>

@Table({
tableName: 'vw_user_teams_permissions'
})
export class UserPermission extends Model<
UserPermissionAttributes,
UserPermissionCreationAttributes
> {
@AllowNull(false)
@Column(DataType.UUIDV4)
userId?: string

@AllowNull(false)
@Column(DataType.UUIDV4)
teamId?: bigint

@Column
permission?: string
}
4 changes: 1 addition & 3 deletions packages/app/src/db/models/users-roles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ export interface UserRoleAttributes {
export type UserRoleCreationAttributes = Omit<UserRoleAttributes, 'id'>

@Table({
tableName: 'users',
timestamps: false,
underscored: true
tableName: 'users-roles'
})
export class UserRole extends Model<
UserRoleAttributes,
Expand Down
38 changes: 38 additions & 0 deletions packages/app/src/db/models/users-teams.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {
Table,
Model,
Column,
PrimaryKey,
DataType,
AutoIncrement,
ForeignKey
} from 'sequelize-typescript'
import { User } from './users'
import { Team } from './teams'

export interface UserTeamAttributes {
id: string
}

export type UserRoleCreationAttributes = Omit<UserTeamAttributes, 'id'>

@Table({
tableName: 'users-teams'
})
export class UserTeam extends Model<
UserTeamAttributes,
UserRoleCreationAttributes
> {
@PrimaryKey
@AutoIncrement
@Column(DataType.BIGINT)
id!: bigint

@ForeignKey(() => User)
@Column(DataType.UUIDV4)
userId?: string

@ForeignKey(() => Team)
@Column(DataType.UUIDV4)
teamId?: bigint
}
8 changes: 7 additions & 1 deletion packages/app/src/db/models/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ import {
Default,
CreatedAt,
DeletedAt,
UpdatedAt
UpdatedAt,
BelongsToMany
} from 'sequelize-typescript'
import { UserTeam } from './users-teams'
import { Team } from './teams'

export interface UserAttributes {
id: string
Expand Down Expand Up @@ -47,6 +50,9 @@ export class User extends Model<UserAttributes, UserCreationAttributes> {
@Column
image?: string

@BelongsToMany(() => Team, () => UserTeam, 'userId', 'teamId')
teams?: Team[]

@CreatedAt
@Column
createdAt?: Date
Expand Down
8 changes: 8 additions & 0 deletions packages/app/src/db/schemas/permissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { z } from 'zod'

export const FindOnePermissionSchema = z.object({
userId: z.string().uuid(),
teamId: z.string().uuid(),
permission: z.string()
})
export type FindOnePermissionSchema = z.infer<typeof FindOnePermissionSchema>
5 changes: 5 additions & 0 deletions packages/app/src/db/services/permissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { FindOnePermissionSchema } from '../schemas/permissions'
import { UserPermission } from '../models/users-permissions'

export const findOnePermission = async (opts: FindOnePermissionSchema) =>
await UserPermission.count({ where: { ...opts } })
19 changes: 9 additions & 10 deletions packages/app/src/db/services/teams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,22 @@ import {
} from '../schemas/teams'
import { z } from 'zod'
import sequelize from '@/db/config/config'
import { TeamMembers } from '../models/team-members'

export type Pagination = {
offset?: number
limit?: number
}

export const createTeam = async (opts: z.infer<typeof CreateTeamSchema>) =>
sequelize.transaction(async transaction => {
const team = await Team.create({ ...opts }, { transaction })
await TeamMembers.create(
{ userId: opts.userId, teamId: team.id },
{ transaction }
)
// export const createTeam = async (opts: z.infer<typeof CreateTeamSchema>) =>
// sequelize.transaction(async transaction => {
// const team = await Team.create({ ...opts }, { transaction })
// await TeamMembers.create(
// { userId: opts.userId, teamId: team.id },
// { transaction }
// )

return team.dataValues
})
// return team.dataValues
// })

export const findOneTeam = async (opts: z.infer<typeof FindOneTeamSchema>) =>
await Team.findOne({
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/server/routers/_app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
totalSolutions,
deleteSolutionTemplate
} from './actions/solutions'
import { checkPermission } from './actions/permissions'
import { lensRouter } from '@/server/routers/actions/lenses'
import { solutionsRouter } from './actions/solutions'
import { profilesRouter } from './actions/profiles'
Expand All @@ -41,6 +42,8 @@ export const appRouter = router({
return `hello ${opts.input.text} - ${Math.random()}`
}),

checkPermission: checkPermission,

secret: publicProcedure.query(async opts => {
if (!opts.ctx.session) {
return 'You are not authenticated'
Expand Down
7 changes: 7 additions & 0 deletions packages/app/src/server/routers/actions/permissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { PermissionGetSchema } from '../schemas/permissions'
import { protectedProcedure } from '../../trpc'
import { findOnePermission } from '@/db/services/permissions'

export const checkPermission = protectedProcedure
.input(PermissionGetSchema)
.query(async opts => findOnePermission(opts.input))
8 changes: 8 additions & 0 deletions packages/app/src/server/routers/schemas/permissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { z } from 'zod'

export const PermissionGetSchema = z.object({
userId: z.string().uuid(),
teamId: z.string().uuid(),
permission: z.string()
})
export type PermissionGetSchema = z.infer<typeof PermissionGetSchema>

0 comments on commit 15b9522

Please sign in to comment.