Compare commits
7 Commits
f379bba89a
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| 6d4c4617d3 | |||
| 5ebf098316 | |||
| 8d5e2f8113 | |||
| ad79bf08ad | |||
| 2cbd650eca | |||
| 80715ba98b | |||
| ef12dffb62 |
@@ -18,6 +18,52 @@ steps:
|
||||
branch: release
|
||||
event: push
|
||||
|
||||
migrate:
|
||||
image: bitnami/kubectl:latest
|
||||
volumes:
|
||||
- /home/future2/Studio_v2/woodpecker/kube/config:/tmp/kubeconfig:ro
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
commit="$(printf %.8s "$CI_COMMIT_SHA")"
|
||||
job="studio-auth-migrate-$commit"
|
||||
kubectl --kubeconfig=/tmp/kubeconfig -n studio-system delete job "$job" --ignore-not-found
|
||||
cat <<'EOF' | sed "s/__JOB_NAME__/$job/g" | kubectl --kubeconfig=/tmp/kubeconfig apply -f -
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
name: __JOB_NAME__
|
||||
namespace: studio-system
|
||||
spec:
|
||||
backoffLimit: 1
|
||||
ttlSecondsAfterFinished: 600
|
||||
template:
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
containers:
|
||||
- name: migrate
|
||||
image: localhost:5000/studio-auth-be:0.1.1
|
||||
imagePullPolicy: Always
|
||||
command:
|
||||
- sh
|
||||
- -lc
|
||||
- |
|
||||
export DATABASE_URL="postgresql://$(printenv POSTGRES_USER):$(bun -e 'process.stdout.write(encodeURIComponent(process.env.POSTGRES_PASSWORD ?? ""))')@studio-auth-db.studio-system.svc.cluster.local:5432/$(printenv POSTGRES_DB)?schema=public"
|
||||
bunx --no-install prisma migrate deploy
|
||||
envFrom:
|
||||
- secretRef:
|
||||
name: studio-auth-be-env
|
||||
- secretRef:
|
||||
name: studio-auth-db-secret
|
||||
EOF
|
||||
if ! kubectl --kubeconfig=/tmp/kubeconfig -n studio-system wait --for=condition=complete "job/$job" --timeout=180s; then
|
||||
kubectl --kubeconfig=/tmp/kubeconfig -n studio-system logs "job/$job" --all-containers=true || true
|
||||
exit 1
|
||||
fi
|
||||
when:
|
||||
branch: release
|
||||
event: push
|
||||
|
||||
deploy:
|
||||
image: bitnami/kubectl:latest
|
||||
volumes:
|
||||
|
||||
@@ -92,11 +92,26 @@ model License {
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
|
||||
userLicenses UserLicense[]
|
||||
appPermissions LicenseAppPermission[]
|
||||
|
||||
@@index([isActive])
|
||||
@@map("licenses")
|
||||
}
|
||||
|
||||
model LicenseAppPermission {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
licenseId String @map("license_id") @db.Uuid
|
||||
appKey String @map("app_key")
|
||||
canLaunch Boolean @default(true) @map("can_launch")
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
|
||||
license License @relation(fields: [licenseId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([licenseId, appKey])
|
||||
@@index([appKey])
|
||||
@@map("license_app_permissions")
|
||||
}
|
||||
|
||||
model UserLicense {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it, mock } from 'bun:test'
|
||||
|
||||
const findFirst = mock(async (): Promise<unknown> => null)
|
||||
mock.module('../prisma', () => ({ prisma: { userLicense: { findFirst } } }))
|
||||
const { getLauncherAppPolicy } = await import('./license-policy')
|
||||
|
||||
describe('launcher license policy', () => {
|
||||
it('returns the current license app policy', async () => {
|
||||
findFirst.mockResolvedValueOnce({ license: { appPermissions: [{ appKey: 'LMS', canLaunch: true }, { appKey: 'OTHER', canLaunch: false }] } })
|
||||
expect(await getLauncherAppPolicy('student')).toEqual({
|
||||
defaultCanLaunch: true,
|
||||
permissions: [{ appKey: 'LMS', canLaunch: true }, { appKey: 'OTHER', canLaunch: false }],
|
||||
})
|
||||
expect(findFirst).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
userId: 'student', startsAt: { lte: expect.any(Date) },
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: expect.any(Date) } }],
|
||||
license: { isActive: true },
|
||||
}),
|
||||
orderBy: { startsAt: 'desc' },
|
||||
}))
|
||||
})
|
||||
|
||||
it('denies by default without an active license', async () => {
|
||||
findFirst.mockResolvedValueOnce(null)
|
||||
expect(await getLauncherAppPolicy('student')).toEqual({ defaultCanLaunch: false, permissions: [] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { prisma } from '../prisma'
|
||||
|
||||
export async function getLauncherAppPolicy(userId: string) {
|
||||
const now = new Date()
|
||||
const current = await prisma.userLicense.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
startsAt: { lte: now },
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
|
||||
license: { isActive: true }
|
||||
},
|
||||
orderBy: { startsAt: 'desc' },
|
||||
select: {
|
||||
license: { select: { appPermissions: { select: { appKey: true, canLaunch: true } } } }
|
||||
}
|
||||
})
|
||||
return {
|
||||
// Match the admin license policy: unspecified apps are allowed for active licenses.
|
||||
defaultCanLaunch: Boolean(current),
|
||||
permissions: current?.license.appPermissions ?? []
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,12 @@ import { randomInt } from 'crypto'
|
||||
import { z } from 'zod'
|
||||
import { config } from '../config'
|
||||
import { sendEmailVerificationCode } from '../mail'
|
||||
import { prisma } from '../prisma'
|
||||
import { verifyPassword } from '../security/password'
|
||||
import { signAccessToken, verifyAccessToken } from '../security/tokens'
|
||||
import type { AuthUser } from '../types'
|
||||
import { authRequired, type AuthVariables } from './middleware'
|
||||
import { getLauncherAppPolicy } from './license-policy'
|
||||
import {
|
||||
clearLoginAttempts,
|
||||
assignUserAffiliation,
|
||||
@@ -26,6 +28,7 @@ import {
|
||||
findOrCreateOAuthUser,
|
||||
findUserProfileImage,
|
||||
findUserByEmail,
|
||||
findUserById,
|
||||
listOrganizations,
|
||||
isLoginBlocked,
|
||||
markLastLogin,
|
||||
@@ -153,6 +156,14 @@ const userResponse = (user: AuthUser) => ({
|
||||
|
||||
const requireAdmin = (user: AuthUser): boolean => user.role === 'ADMIN'
|
||||
|
||||
const canManageLmsStudents = (user: AuthUser): boolean => (
|
||||
user.role === 'ADMIN'
|
||||
|| (user.appRoles ?? []).some((appRole) => (
|
||||
appRole.appKey.toUpperCase() === 'LMS'
|
||||
&& ['INSTRUCTOR', 'LMS_ADMIN'].includes(appRole.roleCode.toUpperCase())
|
||||
))
|
||||
)
|
||||
|
||||
const accessTokenResponse = async (user: AuthUser) => ({
|
||||
accessToken: await signAccessToken(user),
|
||||
accessTokenExpiresIn: config.accessTokenTtlSeconds,
|
||||
@@ -676,6 +687,10 @@ authRoutes.post('/logout', async (c) => {
|
||||
return c.json({ ok: true })
|
||||
})
|
||||
|
||||
authRoutes.get('/launcher-app-policy', authRequired, async (c) => {
|
||||
return c.json(await getLauncherAppPolicy(c.get('user').id))
|
||||
})
|
||||
|
||||
authRoutes.get('/me', authRequired, (c) => {
|
||||
return c.json({ user: userResponse(c.get('user')) })
|
||||
})
|
||||
@@ -802,6 +817,56 @@ authRoutes.post('/admin/users', authRequired, async (c) => {
|
||||
}
|
||||
})
|
||||
|
||||
authRoutes.post('/instructor/students', authRequired, async (c) => {
|
||||
const instructor = c.get('user')
|
||||
if (!canManageLmsStudents(instructor)) return c.json({ error: 'forbidden' }, 403)
|
||||
|
||||
const body = adminCreateUserSchema.safeParse(await c.req.json().catch(() => null))
|
||||
if (!body.success) return c.json({ error: 'invalid_request', details: body.error.flatten() }, 400)
|
||||
|
||||
const organizationId = instructor.primaryAffiliation?.organizationId
|
||||
if (instructor.role !== 'ADMIN' && (!organizationId || body.data.organizationId !== organizationId)) {
|
||||
return c.json({ error: 'forbidden' }, 403)
|
||||
}
|
||||
|
||||
const email = body.data.email.toLowerCase()
|
||||
const existingUser = await findUserByEmail(email)
|
||||
|
||||
try {
|
||||
const user = existingUser ?? await createManagedUser({
|
||||
email,
|
||||
password: body.data.password,
|
||||
name: body.data.name,
|
||||
organizationId: body.data.organizationId,
|
||||
department: body.data.department,
|
||||
position: body.data.position,
|
||||
licenseCode: body.data.licenseCode,
|
||||
})
|
||||
|
||||
await prisma.userAppRole.upsert({
|
||||
where: {
|
||||
userId_appKey_roleCode: {
|
||||
userId: user.id,
|
||||
appKey: 'LMS',
|
||||
roleCode: 'STUDENT',
|
||||
},
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
appKey: 'LMS',
|
||||
roleCode: 'STUDENT',
|
||||
assignedById: instructor.id,
|
||||
},
|
||||
update: {},
|
||||
})
|
||||
|
||||
const resolvedUser = await findUserById(user.id)
|
||||
return c.json({ user: userResponse(resolvedUser ?? user) }, existingUser ? 200 : 201)
|
||||
} catch {
|
||||
return c.json({ error: 'user_create_failed' }, 400)
|
||||
}
|
||||
})
|
||||
|
||||
authRoutes.post('/admin/users/:userId/affiliations', authRequired, async (c) => {
|
||||
if (!requireAdmin(c.get('user'))) return c.json({ error: 'forbidden' }, 403)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user