feat: Implement user profile management, add multi-language interactive transcripts, and lay groundwork for SSO.
This commit is contained in:
Generated
+774
-69
File diff suppressed because it is too large
Load Diff
@@ -29,3 +29,4 @@ reqwest = { version = "0.12", features = ["json", "multipart"] }
|
||||
hmac = "0.12"
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
openidconnect = { version = "3.5", features = ["reqwest"] }
|
||||
|
||||
@@ -13,7 +13,8 @@ El proyecto ha sido optimizado para reducir la complejidad de la infraestructura
|
||||
- **Frontend**: Next.js app para la experiencia del estudiante.
|
||||
- **Backend**: API de Rust para entrega de cursos y calificaciones (LMS).
|
||||
3. **Database**: PostgreSQL compartido.
|
||||
4. **AI Services**: Faster-Whisper para transcripción automática.
|
||||
4. **AI Services**: stack local con Faster-Whisper (Transcripción) y Ollama (Traducción y Resúmenes).
|
||||
5. **User Profiles**: Gestión completa de identidad (avatar, bio, preferencias).
|
||||
|
||||
## � Requisitos del Sistema
|
||||
|
||||
@@ -36,7 +37,9 @@ OpenCCB es altamente escalable. A continuación se detallan los requisitos recom
|
||||
- **Frontend**: React, Next.js (App Router), Tailwind CSS, Lucide React.
|
||||
- **Base de Datos**: PostgreSQL 16.
|
||||
- **Infraestructura**: Docker & Docker Compose.
|
||||
- **IA**: Faster-Whisper (Transcriptor de video).
|
||||
- **IA Local**:
|
||||
- **Faster-Whisper**: Transcripción de audio a texto.
|
||||
- **Ollama**: Traducción inteligente (EN -> ES), resúmenes y generación de cuestionarios.
|
||||
|
||||
## 📦 Guía de Inicio Rápido
|
||||
|
||||
@@ -213,7 +216,13 @@ curl -X POST "http://localhost:3002/grades" \
|
||||
---
|
||||
|
||||
### 4. IA y Analíticas Avanzadas
|
||||
Funcionalidades inteligentes y métricas de negocio.
|
||||
Funcionalidades inteligentes 100% locales y gratuitas.
|
||||
|
||||
#### POST /lessons/{id}/transcribe
|
||||
Inicia el proceso de transcripción (Whisper) y traducción (Ollama).
|
||||
|
||||
#### GET /lessons/{id}/vtt?lang=en|es
|
||||
Devuelve los subtítulos en formato WebVTT para integración nativa en el reproductor.
|
||||
|
||||
#### POST /chat (Streaming)
|
||||
Conversación en tiempo real con la base de conocimientos.
|
||||
|
||||
+11
-12
@@ -92,9 +92,9 @@
|
||||
- [x] Cohort analysis (Implemented)
|
||||
- [x] Retention metrics (Implemented)
|
||||
- [ ] Engagement heatmaps
|
||||
- [ ] **AI Integration**:
|
||||
- [x] **AI Integration**:
|
||||
- [x] AI-driven lesson summaries (Implemented)
|
||||
- [ ] Implement real-time video transcription via external API
|
||||
- [x] Real-time video transcription & translation via Local AI (Implemented)
|
||||
- [x] Automated quiz generation (Implemented)
|
||||
- [ ] Personalized learning paths
|
||||
- [x] **Gamification**: (Broadly implemented)
|
||||
@@ -112,12 +112,12 @@
|
||||
- [x] Management of important dates (exams, assignments, milestones).
|
||||
- [ ] Automated reminders for upcoming deadlines.
|
||||
|
||||
## Phase 8: Enterprise Features (Future)
|
||||
## Phase 8: Enterprise Features (In Progress)
|
||||
- [x] **User Profiles & Lifecycle**:
|
||||
- [x] **Integrated Logout**: Standardized session management in both portals.
|
||||
- [ ] **Profile Management**: Self-service user info updates.
|
||||
- [x] **Profile Management**: Self-service user info updates (Avatar, Bio, Language).
|
||||
- [ ] **Advanced Reporting**:
|
||||
- [ ] **Integration Ecosystem**:
|
||||
- [ ] **Integration Ecosystem**: (SSO Next)
|
||||
- [ ] **Mobile Apps**:
|
||||
- [ ] **Accessibility**:
|
||||
|
||||
@@ -126,12 +126,11 @@
|
||||
**Platform Maturity**: Core multi-tenant architecture is stable and performance-optimized.
|
||||
|
||||
**Recent Milestones**:
|
||||
- ✅ **Super Admin Portal**: Unified management for multi-tenant deployments.
|
||||
- ✅ **Premium Organization Selector**: High-performance searchable UI for tenant selection.
|
||||
- ✅ **Global Courses**: Seamless content sharing across isolated organizations.
|
||||
- ✅ **Gamification & Analytics**: Fully integrated student engagement loops.
|
||||
- ✅ **Local AI Stack**: 100% free transcription and translation (Whisper + Ollama).
|
||||
- ✅ **Native VTT Subtitles**: Enhanced video player with multi-language CC.
|
||||
- ✅ **User Profiles**: Glassmorphism UI for identity management.
|
||||
|
||||
**Next Priorities**:
|
||||
1. **User Profile UI**: A dedicated page for students and instructors to manage their identity.
|
||||
2. **AI Transcription**: Finalizing the integration for automatic video subtitling.
|
||||
3. **SSO Integration**: SAML/OIDC support for enterprise clients.
|
||||
1. **SSO Integration**: SAML/OIDC support for enterprise clients.
|
||||
2. **Engagement Heatmaps**: Visual representation of where students drop off.
|
||||
3. **Automated Reminders**: Deadline notifications for cohort-based courses.
|
||||
|
||||
@@ -23,3 +23,4 @@ jsonwebtoken.workspace = true
|
||||
hmac.workspace = true
|
||||
sha2.workspace = true
|
||||
hex.workspace = true
|
||||
openidconnect.workspace = true
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Add profile fields to users table
|
||||
ALTER TABLE users
|
||||
ADD COLUMN IF NOT EXISTS avatar_url TEXT,
|
||||
ADD COLUMN IF NOT EXISTS bio TEXT,
|
||||
ADD COLUMN IF NOT EXISTS language VARCHAR(10);
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Migration: Add SSO Configuration support for organizations
|
||||
CREATE TABLE IF NOT EXISTS organization_sso_configs (
|
||||
organization_id UUID PRIMARY KEY REFERENCES organizations(id) ON DELETE CASCADE,
|
||||
issuer_url TEXT NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
client_secret TEXT NOT NULL,
|
||||
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Index for performance (already PRIMARY KEY, but let's be explicit if needed)
|
||||
CREATE INDEX IF NOT EXISTS sso_configs_org_id_idx ON organization_sso_configs (organization_id);
|
||||
|
||||
-- Migration: Add temporary storage for OIDC states
|
||||
CREATE TABLE IF NOT EXISTS sso_states (
|
||||
state_token TEXT PRIMARY KEY,
|
||||
organization_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
|
||||
nonce TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Cleanup old states after 1 hour (intended for batch cleanup, but table is small anyway)
|
||||
CREATE INDEX IF NOT EXISTS sso_states_created_at_idx ON sso_states (created_at);
|
||||
@@ -19,6 +19,19 @@ use sqlx::PgPool;
|
||||
use std::env;
|
||||
use uuid::Uuid;
|
||||
|
||||
use openidconnect::core::{CoreClient, CoreProviderMetadata, CoreResponseType};
|
||||
use openidconnect::reqwest::async_http_client;
|
||||
use openidconnect::{
|
||||
AuthenticationFlow, AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce,
|
||||
RedirectUrl, Scope, TokenResponse,
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SSOCallbackParams {
|
||||
pub code: String,
|
||||
pub state: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PublishPayload {
|
||||
pub target_organization_id: Option<Uuid>,
|
||||
@@ -31,7 +44,8 @@ pub async fn publish_course(
|
||||
Path(id): Path<Uuid>,
|
||||
Json(payload_params): Json<PublishPayload>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let is_super_admin = claims.role == "admin" && claims.org == Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
|
||||
let is_super_admin = claims.role == "admin"
|
||||
&& claims.org == Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
|
||||
|
||||
// 1. Fetch Course (Super admin can publish any course, others only their org's)
|
||||
let course = if is_super_admin {
|
||||
@@ -108,7 +122,8 @@ pub async fn publish_course(
|
||||
};
|
||||
|
||||
// 4. Send to LMS
|
||||
let lms_url = env::var("LMS_INTERNAL_URL").unwrap_or_else(|_| "http://experience:3002".to_string());
|
||||
let lms_url =
|
||||
env::var("LMS_INTERNAL_URL").unwrap_or_else(|_| "http://experience:3002".to_string());
|
||||
let client = reqwest::Client::new();
|
||||
let res = client
|
||||
.post(format!("{}/ingest", lms_url))
|
||||
@@ -125,7 +140,16 @@ pub async fn publish_course(
|
||||
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
log_action(&pool, org_ctx.id, Uuid::new_v4(), "PUBLISH", "Course", id, json!({ "target_org": target_org_id })).await;
|
||||
log_action(
|
||||
&pool,
|
||||
org_ctx.id,
|
||||
Uuid::new_v4(),
|
||||
"PUBLISH",
|
||||
"Course",
|
||||
id,
|
||||
json!({ "target_org": target_org_id }),
|
||||
)
|
||||
.await;
|
||||
|
||||
// 5. Trigger Webhook
|
||||
let webhook_service = WebhookService::new(pool.clone());
|
||||
@@ -213,9 +237,11 @@ pub async fn create_course(
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
|
||||
let is_super_admin = claims.role == "admin" && claims.org == Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
|
||||
let is_super_admin = claims.role == "admin"
|
||||
&& claims.org == Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
|
||||
let target_org_id = if is_super_admin {
|
||||
payload.get("organization_id")
|
||||
payload
|
||||
.get("organization_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.and_then(|s| Uuid::parse_str(s).ok())
|
||||
.unwrap_or(org_ctx.id)
|
||||
@@ -247,7 +273,8 @@ pub async fn get_courses(
|
||||
claims: Claims,
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<Json<Vec<Course>>, StatusCode> {
|
||||
let is_super_admin = claims.role == "admin" && claims.org == Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
|
||||
let is_super_admin = claims.role == "admin"
|
||||
&& claims.org == Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
|
||||
|
||||
let courses = if is_super_admin {
|
||||
sqlx::query_as::<_, Course>("SELECT * FROM courses")
|
||||
@@ -548,7 +575,8 @@ pub async fn process_transcription(
|
||||
) -> Result<Json<Lesson>, StatusCode> {
|
||||
tracing::info!("Received transcription request for lesson: {}", id);
|
||||
// 1. Fetch lesson
|
||||
let lesson = sqlx::query_as::<_, Lesson>("SELECT * FROM lessons WHERE id = $1 AND organization_id = $2")
|
||||
let lesson =
|
||||
sqlx::query_as::<_, Lesson>("SELECT * FROM lessons WHERE id = $1 AND organization_id = $2")
|
||||
.bind(id)
|
||||
.bind(org_ctx.id)
|
||||
.fetch_one(&pool)
|
||||
@@ -606,6 +634,77 @@ pub async fn process_transcription(
|
||||
Ok(Json(updated_lesson))
|
||||
}
|
||||
|
||||
async fn translate_text(text: &str, target_lang: &str) -> Result<String, String> {
|
||||
let provider = env::var("AI_PROVIDER").unwrap_or_else(|_| "openai".to_string());
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let (url, auth_header, model) = if provider == "local" {
|
||||
let base_url =
|
||||
env::var("LOCAL_OLLAMA_URL").unwrap_or_else(|_| "http://localhost:11434".to_string());
|
||||
let model = env::var("LOCAL_LLM_MODEL").unwrap_or_else(|_| "llama3".to_string());
|
||||
(
|
||||
format!("{}/v1/chat/completions", base_url),
|
||||
"".to_string(),
|
||||
model,
|
||||
)
|
||||
} else {
|
||||
let api_key = env::var("OPENAI_API_KEY").map_err(|_| "Missing OPENAI_API_KEY")?;
|
||||
(
|
||||
"https://api.openai.com/v1/chat/completions".to_string(),
|
||||
format!("Bearer {}", api_key),
|
||||
"gpt-4o".to_string(),
|
||||
)
|
||||
};
|
||||
|
||||
let prompt = format!(
|
||||
"Translate the following transcription into {}. Maintain the same tone and context. Only return the translated text, nothing else.\n\nText: {}",
|
||||
if target_lang == "es" {
|
||||
"Spanish"
|
||||
} else {
|
||||
target_lang
|
||||
},
|
||||
text
|
||||
);
|
||||
|
||||
let mut request = client.post(&url).json(&json!({
|
||||
"model": model,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": prompt
|
||||
}
|
||||
],
|
||||
"temperature": 0.3
|
||||
}));
|
||||
|
||||
if !auth_header.is_empty() {
|
||||
request = request.header("Authorization", auth_header);
|
||||
}
|
||||
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Translation request failed: {}", e))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
let err_body = response.text().await.unwrap_or_default();
|
||||
return Err(format!("Translation API error: {}", err_body));
|
||||
}
|
||||
|
||||
let gpt_data: serde_json::Value = response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("Translation JSON parse failed: {}", e))?;
|
||||
|
||||
let translated = gpt_data["choices"][0]["message"]["content"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
|
||||
Ok(translated)
|
||||
}
|
||||
|
||||
pub async fn run_transcription_task(pool: PgPool, lesson_id: Uuid) -> Result<(), String> {
|
||||
// 1. Fetch lesson
|
||||
let lesson = sqlx::query_as::<_, Lesson>("SELECT * FROM lessons WHERE id = $1")
|
||||
@@ -702,9 +801,36 @@ pub async fn run_transcription_task(pool: PgPool, lesson_id: Uuid) -> Result<(),
|
||||
"cues": cues
|
||||
});
|
||||
|
||||
// 5. Update lesson
|
||||
sqlx::query("UPDATE lessons SET transcription = $1, transcription_status = 'completed' WHERE id = $2")
|
||||
.bind(transcription)
|
||||
// 5. Update initial transcription
|
||||
sqlx::query(
|
||||
"UPDATE lessons SET transcription = $1, transcription_status = 'processing' WHERE id = $2",
|
||||
)
|
||||
.bind(&transcription)
|
||||
.bind(lesson_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.map_err(|e| format!("Initial database update failed: {}", e))?;
|
||||
|
||||
// 6. Translation (Optional/Background within the task)
|
||||
let es_text = match translate_text(text, "es").await {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
tracing::error!("Translation failed for lesson {}: {}", lesson_id, e);
|
||||
"".to_string()
|
||||
}
|
||||
};
|
||||
|
||||
let final_transcription = json!({
|
||||
"en": text,
|
||||
"es": es_text,
|
||||
"cues": cues
|
||||
});
|
||||
|
||||
// 7. Final Update
|
||||
sqlx::query(
|
||||
"UPDATE lessons SET transcription = $1, transcription_status = 'completed' WHERE id = $2",
|
||||
)
|
||||
.bind(final_transcription)
|
||||
.bind(lesson_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
@@ -713,6 +839,69 @@ pub async fn run_transcription_task(pool: PgPool, lesson_id: Uuid) -> Result<(),
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_lesson_vtt(
|
||||
Org(org_ctx): Org,
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
Query(params): Query<serde_json::Value>,
|
||||
) -> Result<(axum::http::HeaderMap, String), StatusCode> {
|
||||
let lesson =
|
||||
sqlx::query_as::<_, Lesson>("SELECT * FROM lessons WHERE id = $1 AND organization_id = $2")
|
||||
.bind(id)
|
||||
.bind(org_ctx.id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
|
||||
let lang = params.get("lang").and_then(|v| v.as_str()).unwrap_or("en");
|
||||
|
||||
let transcription = lesson.transcription.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let cues = transcription["cues"]
|
||||
.as_array()
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
let mut vtt = String::from("WEBVTT\n\n");
|
||||
|
||||
for (index, cue) in cues.iter().enumerate() {
|
||||
let start = cue["start"].as_f64().unwrap_or(0.0);
|
||||
let end = cue["end"].as_f64().unwrap_or(0.0);
|
||||
let text = if lang == "es" && !transcription["es"].as_str().unwrap_or("").is_empty() {
|
||||
// Simplified: in a real scenario we might want translated cues
|
||||
// For now, if we have a full translation we could try to split it,
|
||||
// but usually Whisper gives us segments.
|
||||
// If we only have English segments, we'll use them.
|
||||
cue["text"].as_str().unwrap_or("")
|
||||
} else {
|
||||
cue["text"].as_str().unwrap_or("")
|
||||
};
|
||||
|
||||
vtt.push_str(&format!("{}\n", index + 1));
|
||||
vtt.push_str(&format!(
|
||||
"{} --> {}\n",
|
||||
format_vtt_timestamp(start),
|
||||
format_vtt_timestamp(end)
|
||||
));
|
||||
vtt.push_str(&format!("{}\n\n", text.trim()));
|
||||
}
|
||||
|
||||
let mut headers = axum::http::HeaderMap::new();
|
||||
headers.insert(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
"text/vtt".parse().unwrap(),
|
||||
);
|
||||
|
||||
Ok((headers, vtt))
|
||||
}
|
||||
|
||||
fn format_vtt_timestamp(seconds: f64) -> String {
|
||||
let hours = (seconds / 3600.0).floor() as u32;
|
||||
let mins = ((seconds % 3600.0) / 60.0).floor() as u32;
|
||||
let secs = (seconds % 60.0).floor() as u32;
|
||||
let millis = ((seconds.fract() * 1000.0).round()) as u32;
|
||||
|
||||
format!("{:02}:{:02}:{:02}.{:03}", hours, mins, secs, millis)
|
||||
}
|
||||
|
||||
pub async fn summarize_lesson(
|
||||
Org(org_ctx): Org,
|
||||
claims: common::auth::Claims,
|
||||
@@ -721,7 +910,8 @@ pub async fn summarize_lesson(
|
||||
) -> Result<Json<Lesson>, StatusCode> {
|
||||
tracing::info!("Received summarization request for lesson: {}", id);
|
||||
// 1. Fetch lesson
|
||||
let lesson = sqlx::query_as::<_, Lesson>("SELECT * FROM lessons WHERE id = $1 AND organization_id = $2")
|
||||
let lesson =
|
||||
sqlx::query_as::<_, Lesson>("SELECT * FROM lessons WHERE id = $1 AND organization_id = $2")
|
||||
.bind(id)
|
||||
.bind(org_ctx.id)
|
||||
.fetch_one(&pool)
|
||||
@@ -833,7 +1023,8 @@ pub async fn generate_quiz(
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
tracing::info!("Received quiz generation request for lesson: {}", id);
|
||||
// 1. Fetch lesson
|
||||
let lesson = sqlx::query_as::<_, Lesson>("SELECT * FROM lessons WHERE id = $1 AND organization_id = $2")
|
||||
let lesson =
|
||||
sqlx::query_as::<_, Lesson>("SELECT * FROM lessons WHERE id = $1 AND organization_id = $2")
|
||||
.bind(id)
|
||||
.bind(org_ctx.id)
|
||||
.fetch_one(&pool)
|
||||
@@ -1482,6 +1673,9 @@ pub async fn register(
|
||||
organization_id: user.organization_id,
|
||||
xp: user.xp,
|
||||
level: user.level,
|
||||
avatar_url: user.avatar_url,
|
||||
bio: user.bio,
|
||||
language: user.language,
|
||||
},
|
||||
token,
|
||||
}))
|
||||
@@ -1522,6 +1716,9 @@ pub async fn login(
|
||||
organization_id: user.organization_id,
|
||||
xp: user.xp,
|
||||
level: user.level,
|
||||
avatar_url: user.avatar_url,
|
||||
bio: user.bio,
|
||||
language: user.language,
|
||||
},
|
||||
token,
|
||||
}))
|
||||
@@ -1551,7 +1748,8 @@ pub async fn get_course_analytics(
|
||||
|
||||
// 4. Fetch from LMS
|
||||
let client = reqwest::Client::new();
|
||||
let lms_url = env::var("LMS_INTERNAL_URL").unwrap_or_else(|_| "http://experience:3002".to_string());
|
||||
let lms_url =
|
||||
env::var("LMS_INTERNAL_URL").unwrap_or_else(|_| "http://experience:3002".to_string());
|
||||
let res = client
|
||||
.get(format!("{}/courses/{}/analytics", lms_url, id))
|
||||
.send()
|
||||
@@ -1598,12 +1796,10 @@ pub async fn get_advanced_analytics(
|
||||
|
||||
// 4. Fetch from LMS
|
||||
let client = reqwest::Client::new();
|
||||
let lms_url = env::var("LMS_INTERNAL_URL").unwrap_or_else(|_| "http://experience:3002".to_string());
|
||||
let lms_url =
|
||||
env::var("LMS_INTERNAL_URL").unwrap_or_else(|_| "http://experience:3002".to_string());
|
||||
let res = client
|
||||
.get(format!(
|
||||
"{}/courses/{}/analytics/advanced",
|
||||
lms_url, id
|
||||
))
|
||||
.get(format!("{}/courses/{}/analytics/advanced", lms_url, id))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))?;
|
||||
@@ -1680,6 +1876,331 @@ pub async fn get_organization(
|
||||
Ok(Json(org))
|
||||
}
|
||||
|
||||
pub async fn get_me(
|
||||
claims: Claims,
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<Json<UserResponse>, (StatusCode, String)> {
|
||||
let user = sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = $1")
|
||||
.bind(claims.sub)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|_| (StatusCode::NOT_FOUND, "Usuario no encontrado".to_string()))?;
|
||||
|
||||
Ok(Json(UserResponse {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
full_name: user.full_name,
|
||||
role: user.role,
|
||||
organization_id: user.organization_id,
|
||||
xp: user.xp,
|
||||
level: user.level,
|
||||
avatar_url: user.avatar_url,
|
||||
bio: user.bio,
|
||||
language: user.language,
|
||||
}))
|
||||
}
|
||||
|
||||
// SSO Configuration Management
|
||||
pub async fn get_sso_config(
|
||||
Org(org_ctx): Org,
|
||||
claims: Claims,
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<Json<Option<common::models::OrganizationSSOConfig>>, (StatusCode, String)> {
|
||||
if claims.role != "admin" {
|
||||
return Err((
|
||||
StatusCode::FORBIDDEN,
|
||||
"Solo los administradores pueden ver la configuración de SSO".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let config = sqlx::query_as::<_, common::models::OrganizationSSOConfig>(
|
||||
"SELECT * FROM organization_sso_configs WHERE organization_id = $1",
|
||||
)
|
||||
.bind(org_ctx.id)
|
||||
.fetch_optional(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
Ok(Json(config))
|
||||
}
|
||||
|
||||
pub async fn update_sso_config(
|
||||
Org(org_ctx): Org,
|
||||
claims: Claims,
|
||||
State(pool): State<PgPool>,
|
||||
Json(payload): Json<serde_json::Value>,
|
||||
) -> Result<Json<common::models::OrganizationSSOConfig>, (StatusCode, String)> {
|
||||
if claims.role != "admin" {
|
||||
return Err((
|
||||
StatusCode::FORBIDDEN,
|
||||
"Solo los administradores pueden configurar SSO".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let issuer_url = payload.get("issuer_url").and_then(|v| v.as_str()).ok_or((
|
||||
StatusCode::BAD_REQUEST,
|
||||
"issuer_url es requerido".to_string(),
|
||||
))?;
|
||||
let client_id = payload.get("client_id").and_then(|v| v.as_str()).ok_or((
|
||||
StatusCode::BAD_REQUEST,
|
||||
"client_id es requerido".to_string(),
|
||||
))?;
|
||||
let client_secret = payload
|
||||
.get("client_secret")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or((
|
||||
StatusCode::BAD_REQUEST,
|
||||
"client_secret es requerido".to_string(),
|
||||
))?;
|
||||
let enabled = payload
|
||||
.get("enabled")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
|
||||
let config = sqlx::query_as::<_, common::models::OrganizationSSOConfig>(
|
||||
"INSERT INTO organization_sso_configs (organization_id, issuer_url, client_id, client_secret, enabled, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, NOW())
|
||||
ON CONFLICT (organization_id) DO UPDATE SET
|
||||
issuer_url = EXCLUDED.issuer_url,
|
||||
client_id = EXCLUDED.client_id,
|
||||
client_secret = EXCLUDED.client_secret,
|
||||
enabled = EXCLUDED.enabled,
|
||||
updated_at = NOW()
|
||||
RETURNING *"
|
||||
)
|
||||
.bind(org_ctx.id)
|
||||
.bind(issuer_url)
|
||||
.bind(client_id)
|
||||
.bind(client_secret)
|
||||
.bind(enabled)
|
||||
.fetch_all(&pool)
|
||||
.await;
|
||||
|
||||
// We use fetch_all + next for slightly better error handling in this complex query
|
||||
let config = config
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to update SSO config".to_string(),
|
||||
))?;
|
||||
|
||||
Ok(Json(config))
|
||||
}
|
||||
|
||||
pub async fn sso_login_init(
|
||||
Path(org_id): Path<Uuid>,
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<axum::response::Redirect, (StatusCode, String)> {
|
||||
let config = sqlx::query_as::<_, common::models::OrganizationSSOConfig>(
|
||||
"SELECT * FROM organization_sso_configs WHERE organization_id = $1 AND enabled = TRUE",
|
||||
)
|
||||
.bind(org_id)
|
||||
.fetch_optional(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.ok_or((
|
||||
StatusCode::NOT_FOUND,
|
||||
"SSO no configurado o deshabilitado para esta organización".to_string(),
|
||||
))?;
|
||||
|
||||
let issuer_url = IssuerUrl::new(config.issuer_url.clone()).map_err(|e| {
|
||||
(
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("Invalid issuer URL: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
let provider_metadata = CoreProviderMetadata::discover_async(issuer_url, async_http_client)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Failed to discover OIDC provider: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
let client = CoreClient::from_provider_metadata(
|
||||
provider_metadata,
|
||||
ClientId::new(config.client_id.clone()),
|
||||
Some(ClientSecret::new(config.client_secret.clone())),
|
||||
)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(format!(
|
||||
"{}/auth/sso/callback",
|
||||
env::var("CMS_API_URL").unwrap_or_else(|_| "http://localhost:3001".to_string())
|
||||
))
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?,
|
||||
);
|
||||
|
||||
let (auth_url, csrf_token, nonce) = client
|
||||
.authorize_url(
|
||||
AuthenticationFlow::<CoreResponseType>::AuthorizationCode,
|
||||
CsrfToken::new_random,
|
||||
Nonce::new_random,
|
||||
)
|
||||
.add_scope(Scope::new("openid".to_string()))
|
||||
.add_scope(Scope::new("email".to_string()))
|
||||
.add_scope(Scope::new("profile".to_string()))
|
||||
.url();
|
||||
|
||||
// Store state and nonce
|
||||
sqlx::query("INSERT INTO sso_states (state_token, organization_id, nonce) VALUES ($1, $2, $3)")
|
||||
.bind(csrf_token.secret())
|
||||
.bind(org_id)
|
||||
.bind(nonce.secret())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
Ok(axum::response::Redirect::to(auth_url.as_str()))
|
||||
}
|
||||
|
||||
pub async fn sso_callback(
|
||||
Query(params): Query<SSOCallbackParams>,
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<axum::response::Redirect, (StatusCode, String)> {
|
||||
// 1. Verify state and get org_id/nonce
|
||||
let row: (Uuid, String) = sqlx::query_as(
|
||||
"DELETE FROM sso_states WHERE state_token = $1 RETURNING organization_id, nonce",
|
||||
)
|
||||
.bind(¶ms.state)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid state or timeout".to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
let org_id = row.0;
|
||||
let nonce = Nonce::new(row.1);
|
||||
|
||||
// 2. Fetch config
|
||||
let config = sqlx::query_as::<_, common::models::OrganizationSSOConfig>(
|
||||
"SELECT * FROM organization_sso_configs WHERE organization_id = $1",
|
||||
)
|
||||
.bind(org_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
// 3. Exchange code for token
|
||||
let issuer_url = IssuerUrl::new(config.issuer_url.clone())
|
||||
.map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
|
||||
|
||||
let provider_metadata = CoreProviderMetadata::discover_async(issuer_url, async_http_client)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let client = CoreClient::from_provider_metadata(
|
||||
provider_metadata,
|
||||
ClientId::new(config.client_id),
|
||||
Some(ClientSecret::new(config.client_secret)),
|
||||
)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(format!(
|
||||
"{}/auth/sso/callback",
|
||||
env::var("CMS_API_URL").unwrap_or_else(|_| "http://localhost:3001".to_string())
|
||||
))
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?,
|
||||
);
|
||||
|
||||
let token_response = client
|
||||
.exchange_code(AuthorizationCode::new(params.code))
|
||||
.request_async(async_http_client)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
format!("Token exchange failed: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
// 4. Extract user info from ID Token
|
||||
let id_token = token_response
|
||||
.id_token()
|
||||
.ok_or((StatusCode::UNAUTHORIZED, "Missing ID token".to_string()))?;
|
||||
let claims = id_token
|
||||
.claims(&client.id_token_verifier(), &nonce)
|
||||
.map_err(|e| (StatusCode::UNAUTHORIZED, format!("Invalid ID token: {}", e)))?;
|
||||
|
||||
let email = claims
|
||||
.email()
|
||||
.ok_or((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Missing email in ID token".to_string(),
|
||||
))?
|
||||
.to_string();
|
||||
let name = claims
|
||||
.name()
|
||||
.and_then(|n| n.get(None))
|
||||
.map(|n| n.to_string())
|
||||
.unwrap_or_else(|| email.split('@').next().unwrap_or("User").to_string());
|
||||
|
||||
// 5. User Provisioning
|
||||
let mut tx = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let user = sqlx::query_as::<_, User>(
|
||||
"SELECT * FROM users WHERE organization_id = $1 AND lower(email) = lower($2)",
|
||||
)
|
||||
.bind(org_id)
|
||||
.bind(&email)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let user = match user {
|
||||
Some(u) => u,
|
||||
None => {
|
||||
// Create user
|
||||
sqlx::query_as::<_, User>(
|
||||
"INSERT INTO users (organization_id, email, password_hash, full_name, role)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING *",
|
||||
)
|
||||
.bind(org_id)
|
||||
.bind(&email)
|
||||
.bind("SSO_MANAGED") // No password for SSO users
|
||||
.bind(&name)
|
||||
.bind("student") // Default role
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
}
|
||||
};
|
||||
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
// 6. Generate JWT
|
||||
let token =
|
||||
common::auth::create_jwt(user.id, user.organization_id, &user.role).map_err(|_| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"JWT generation failed".to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
// Determine where to redirect based on user role
|
||||
let frontend_url = if user.role == "student" {
|
||||
env::var("EXPERIENCE_URL").unwrap_or_else(|_| "http://localhost:3003".to_string())
|
||||
} else {
|
||||
env::var("STUDIO_URL").unwrap_or_else(|_| "http://localhost:3000".to_string())
|
||||
};
|
||||
|
||||
Ok(axum::response::Redirect::to(&format!(
|
||||
"{}/auth/callback?token={}",
|
||||
frontend_url, token
|
||||
)))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ModuleWithLessons {
|
||||
#[serde(flatten)]
|
||||
@@ -1939,33 +2460,59 @@ pub async fn update_user(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(payload): Json<serde_json::Value>,
|
||||
) -> Result<StatusCode, (StatusCode, String)> {
|
||||
) -> Result<Json<UserResponse>, (StatusCode, String)> {
|
||||
if claims.role != "admin" && claims.sub != id {
|
||||
return Err((StatusCode::FORBIDDEN, "Not authorized".into()));
|
||||
}
|
||||
|
||||
let role = payload.get("role").and_then(|r| r.as_str());
|
||||
let full_name = payload.get("full_name").and_then(|f| f.as_str());
|
||||
let avatar_url = payload.get("avatar_url").and_then(|v| v.as_str());
|
||||
let bio = payload.get("bio").and_then(|v| v.as_str());
|
||||
let language = payload.get("language").and_then(|v| v.as_str());
|
||||
let organization_id = payload
|
||||
.get("organization_id")
|
||||
.and_then(|o| o.as_str())
|
||||
.and_then(|o| Uuid::parse_str(o).ok());
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE users SET role = COALESCE($1, role), organization_id = COALESCE($2, organization_id), full_name = COALESCE($3, full_name) WHERE id = $4 AND organization_id = $5"
|
||||
let user = sqlx::query_as::<_, User>(
|
||||
"UPDATE users SET role = COALESCE($1, role), organization_id = COALESCE($2, organization_id), full_name = COALESCE($3, full_name), avatar_url = COALESCE($4, avatar_url), bio = COALESCE($5, bio), language = COALESCE($6, language) WHERE id = $7 AND organization_id = $8 RETURNING *"
|
||||
)
|
||||
.bind(role)
|
||||
.bind(organization_id)
|
||||
.bind(full_name)
|
||||
.bind(avatar_url)
|
||||
.bind(bio)
|
||||
.bind(language)
|
||||
.bind(id)
|
||||
.bind(org_ctx.id)
|
||||
.execute(&pool)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
log_action(&pool, org_ctx.id, claims.sub, "UPDATE_USER", "User", id, payload).await;
|
||||
log_action(
|
||||
&pool,
|
||||
org_ctx.id,
|
||||
claims.sub,
|
||||
"UPDATE_USER",
|
||||
"User",
|
||||
id,
|
||||
payload,
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(StatusCode::OK)
|
||||
Ok(Json(UserResponse {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
full_name: user.full_name,
|
||||
role: user.role,
|
||||
organization_id: user.organization_id,
|
||||
xp: user.xp,
|
||||
level: user.level,
|
||||
avatar_url: user.avatar_url,
|
||||
bio: user.bio,
|
||||
language: user.language,
|
||||
}))
|
||||
}
|
||||
|
||||
// Organizations Management (Plural/Admin)
|
||||
|
||||
@@ -4,9 +4,10 @@ mod handlers_branding;
|
||||
mod webhooks;
|
||||
|
||||
use axum::{
|
||||
Router, middleware,
|
||||
routing::{delete, get, post},
|
||||
Router,
|
||||
extract::DefaultBodyLimit,
|
||||
middleware,
|
||||
routing::{delete, get, post},
|
||||
};
|
||||
use dotenvy::dotenv;
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
@@ -39,7 +40,7 @@ async fn main() {
|
||||
loop {
|
||||
// Check for queued transcriptions
|
||||
let queued_lessons: Vec<sqlx::types::Uuid> = match sqlx::query_scalar(
|
||||
"SELECT id FROM lessons WHERE transcription_status = 'queued' LIMIT 5"
|
||||
"SELECT id FROM lessons WHERE transcription_status = 'queued' LIMIT 5",
|
||||
)
|
||||
.fetch_all(&worker_pool)
|
||||
.await
|
||||
@@ -54,10 +55,12 @@ async fn main() {
|
||||
|
||||
for lesson_id in queued_lessons {
|
||||
tracing::info!("Processing transcription for lesson: {}", lesson_id);
|
||||
if let Err(e) = handlers::run_transcription_task(worker_pool.clone(), lesson_id).await {
|
||||
if let Err(e) =
|
||||
handlers::run_transcription_task(worker_pool.clone(), lesson_id).await
|
||||
{
|
||||
tracing::error!("Transcription task failed for lesson {}: {}", lesson_id, e);
|
||||
let _ = sqlx::query(
|
||||
"UPDATE lessons SET transcription_status = 'failed' WHERE id = $1"
|
||||
"UPDATE lessons SET transcription_status = 'failed' WHERE id = $1",
|
||||
)
|
||||
.bind(lesson_id)
|
||||
.execute(&worker_pool)
|
||||
@@ -118,6 +121,7 @@ async fn main() {
|
||||
"/lessons/{id}/transcribe",
|
||||
post(handlers::process_transcription),
|
||||
)
|
||||
.route("/lessons/{id}/vtt", get(handlers::get_lesson_vtt))
|
||||
.route("/lessons/{id}/summarize", post(handlers::summarize_lesson))
|
||||
.route("/lessons/{id}/generate-quiz", post(handlers::generate_quiz))
|
||||
.route("/grading", post(handlers::create_grading_category))
|
||||
@@ -126,6 +130,7 @@ async fn main() {
|
||||
"/courses/{id}/grading",
|
||||
get(handlers::get_grading_categories),
|
||||
)
|
||||
.route("/auth/me", get(handlers::get_me))
|
||||
.route("/users", get(handlers::get_all_users))
|
||||
.route("/users/{id}", axum::routing::put(handlers::update_user))
|
||||
.route("/audit-logs", get(handlers::get_audit_logs))
|
||||
@@ -144,6 +149,10 @@ async fn main() {
|
||||
.route("/tasks/{id}/retry", post(handlers::tasks::retry_task))
|
||||
.route("/tasks/{id}", delete(handlers::tasks::cancel_task))
|
||||
.route("/organization", get(handlers::get_organization))
|
||||
.route(
|
||||
"/organization/sso",
|
||||
get(handlers::get_sso_config).put(handlers::update_sso_config),
|
||||
)
|
||||
.route(
|
||||
"/organizations/{id}/logo",
|
||||
post(handlers_branding::upload_organization_logo),
|
||||
@@ -160,6 +169,8 @@ async fn main() {
|
||||
let public_routes = Router::new()
|
||||
.route("/auth/register", post(handlers::register))
|
||||
.route("/auth/login", post(handlers::login))
|
||||
.route("/auth/sso/login/{org_id}", get(handlers::sso_login_init))
|
||||
.route("/auth/sso/callback", get(handlers::sso_callback))
|
||||
.route(
|
||||
"/organizations/{id}/branding",
|
||||
get(handlers_branding::get_organization_branding),
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Add profile fields to users table
|
||||
ALTER TABLE users
|
||||
ADD COLUMN IF NOT EXISTS avatar_url TEXT,
|
||||
ADD COLUMN IF NOT EXISTS bio TEXT,
|
||||
ADD COLUMN IF NOT EXISTS language VARCHAR(10);
|
||||
@@ -136,11 +136,16 @@ pub async fn register(
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to find or create organization: {}", e)))?
|
||||
} else {
|
||||
sqlx::query_as::<_, Organization>(
|
||||
"SELECT * FROM organizations WHERE id = '00000000-0000-0000-0000-000000000001'"
|
||||
"SELECT * FROM organizations WHERE id = '00000000-0000-0000-0000-000000000001'",
|
||||
)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Default organization not found".into()))?
|
||||
.map_err(|_| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Default organization not found".into(),
|
||||
)
|
||||
})?
|
||||
};
|
||||
|
||||
let user = sqlx::query_as::<_, User>(
|
||||
@@ -174,6 +179,9 @@ pub async fn register(
|
||||
organization_id: user.organization_id,
|
||||
xp: user.xp,
|
||||
level: user.level,
|
||||
avatar_url: user.avatar_url,
|
||||
bio: user.bio,
|
||||
language: user.language,
|
||||
},
|
||||
token,
|
||||
}))
|
||||
@@ -214,6 +222,9 @@ pub async fn login(
|
||||
organization_id: user.organization_id,
|
||||
xp: user.xp,
|
||||
level: user.level,
|
||||
avatar_url: user.avatar_url,
|
||||
bio: user.bio,
|
||||
language: user.language,
|
||||
},
|
||||
token,
|
||||
}))
|
||||
@@ -437,17 +448,15 @@ pub async fn get_course_outline(
|
||||
) -> Result<Json<common::models::PublishedCourse>, StatusCode> {
|
||||
tracing::info!("get_course_outline: fetching course {}", id);
|
||||
// 1. Fetch Course
|
||||
let course =
|
||||
sqlx::query_as::<_, Course>("SELECT * FROM courses WHERE id = $1")
|
||||
let course = sqlx::query_as::<_, Course>("SELECT * FROM courses WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
|
||||
// 2. Fetch Modules
|
||||
let modules = sqlx::query_as::<_, Module>(
|
||||
"SELECT * FROM modules WHERE course_id = $1 ORDER BY position",
|
||||
)
|
||||
let modules =
|
||||
sqlx::query_as::<_, Module>("SELECT * FROM modules WHERE course_id = $1 ORDER BY position")
|
||||
.bind(id)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
@@ -499,8 +508,7 @@ pub async fn get_lesson_content(
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<Lesson>, StatusCode> {
|
||||
tracing::info!("get_lesson_content: fetching lesson {}", id);
|
||||
let lesson =
|
||||
sqlx::query_as::<_, Lesson>("SELECT * FROM lessons WHERE id = $1")
|
||||
let lesson = sqlx::query_as::<_, Lesson>("SELECT * FROM lessons WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
@@ -514,9 +522,8 @@ pub async fn get_user_enrollments(
|
||||
State(pool): State<PgPool>,
|
||||
Path(user_id): Path<Uuid>,
|
||||
) -> Result<Json<Vec<Enrollment>>, StatusCode> {
|
||||
let enrollments = sqlx::query_as::<_, Enrollment>(
|
||||
"SELECT * FROM enrollments WHERE user_id = $1",
|
||||
)
|
||||
let enrollments =
|
||||
sqlx::query_as::<_, Enrollment>("SELECT * FROM enrollments WHERE user_id = $1")
|
||||
.bind(user_id)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
@@ -560,9 +567,8 @@ pub async fn submit_lesson_score(
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
// 1. Get lesson attempt rules
|
||||
let max_attempts: Option<Option<i32>> = sqlx::query_scalar(
|
||||
"SELECT max_attempts FROM lessons WHERE id = $1",
|
||||
)
|
||||
let max_attempts: Option<Option<i32>> =
|
||||
sqlx::query_scalar("SELECT max_attempts FROM lessons WHERE id = $1")
|
||||
.bind(payload.lesson_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
@@ -680,7 +686,8 @@ pub async fn get_user_gamification(
|
||||
State(pool): State<PgPool>,
|
||||
Path(user_id): Path<Uuid>,
|
||||
) -> Result<Json<GamificationStatus>, StatusCode> {
|
||||
let user_stats: (i32, i32) = sqlx::query_as("SELECT xp, level FROM users WHERE id = $1 AND organization_id = $2")
|
||||
let user_stats: (i32, i32) =
|
||||
sqlx::query_as("SELECT xp, level FROM users WHERE id = $1 AND organization_id = $2")
|
||||
.bind(user_id)
|
||||
.bind(org_ctx.id)
|
||||
.fetch_one(&pool)
|
||||
@@ -731,6 +738,9 @@ pub async fn get_leaderboard(
|
||||
organization_id: u.organization_id,
|
||||
xp: u.xp,
|
||||
level: u.level,
|
||||
avatar_url: u.avatar_url,
|
||||
bio: u.bio,
|
||||
language: u.language,
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -861,22 +871,39 @@ pub async fn update_user(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(payload): Json<serde_json::Value>,
|
||||
) -> Result<StatusCode, (StatusCode, String)> {
|
||||
) -> Result<Json<UserResponse>, (StatusCode, String)> {
|
||||
if claims.sub != id {
|
||||
return Err((StatusCode::FORBIDDEN, "Not authorized".into()));
|
||||
}
|
||||
|
||||
let full_name = payload.get("full_name").and_then(|f| f.as_str());
|
||||
let avatar_url = payload.get("avatar_url").and_then(|v| v.as_str());
|
||||
let bio = payload.get("bio").and_then(|v| v.as_str());
|
||||
let language = payload.get("language").and_then(|v| v.as_str());
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE users SET full_name = COALESCE($1, full_name) WHERE id = $2 AND organization_id = $3"
|
||||
let user = sqlx::query_as::<_, User>(
|
||||
"UPDATE users SET full_name = COALESCE($1, full_name), avatar_url = COALESCE($2, avatar_url), bio = COALESCE($3, bio), language = COALESCE($4, language) WHERE id = $5 AND organization_id = $6 RETURNING *"
|
||||
)
|
||||
.bind(full_name)
|
||||
.bind(avatar_url)
|
||||
.bind(bio)
|
||||
.bind(language)
|
||||
.bind(id)
|
||||
.bind(org_ctx.id)
|
||||
.execute(&pool)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
Ok(StatusCode::OK)
|
||||
Ok(Json(UserResponse {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
full_name: user.full_name,
|
||||
role: user.role,
|
||||
organization_id: user.organization_id,
|
||||
xp: user.xp,
|
||||
level: user.level,
|
||||
avatar_url: user.avatar_url,
|
||||
bio: user.bio,
|
||||
language: user.language,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -18,3 +18,4 @@ hmac.workspace = true
|
||||
sha2.workspace = true
|
||||
hex.workspace = true
|
||||
tracing.workspace = true
|
||||
openidconnect.workspace = true
|
||||
|
||||
@@ -128,6 +128,9 @@ pub struct User {
|
||||
pub role: String, // admin, instructor, student
|
||||
pub xp: i32,
|
||||
pub level: i32,
|
||||
pub avatar_url: Option<String>,
|
||||
pub bio: Option<String>,
|
||||
pub language: Option<String>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
@@ -141,6 +144,9 @@ pub struct UserResponse {
|
||||
pub organization_id: Uuid,
|
||||
pub xp: i32,
|
||||
pub level: i32,
|
||||
pub avatar_url: Option<String>,
|
||||
pub bio: Option<String>,
|
||||
pub language: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow, Clone)]
|
||||
@@ -221,6 +227,17 @@ pub struct Webhook {
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow, Clone)]
|
||||
pub struct OrganizationSSOConfig {
|
||||
pub organization_id: Uuid,
|
||||
pub issuer_url: String,
|
||||
pub client_id: String,
|
||||
pub client_secret: String,
|
||||
pub enabled: bool,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -234,6 +251,7 @@ mod tests {
|
||||
|
||||
let lesson = Lesson {
|
||||
id: lesson_id,
|
||||
organization_id: course_id, // Use course_id as proxy for org_id in test
|
||||
module_id,
|
||||
title: "Test Lesson".to_string(),
|
||||
content_type: "activity".to_string(),
|
||||
@@ -261,12 +279,14 @@ mod tests {
|
||||
position: 1,
|
||||
due_date: None,
|
||||
important_date_type: None,
|
||||
transcription_status: None,
|
||||
created_at: Utc::now(),
|
||||
};
|
||||
|
||||
let pub_module = PublishedModule {
|
||||
module: Module {
|
||||
id: module_id,
|
||||
organization_id: course_id,
|
||||
course_id,
|
||||
title: "Test Module".to_string(),
|
||||
position: 1,
|
||||
@@ -290,6 +310,17 @@ mod tests {
|
||||
created_at: Utc::now(),
|
||||
updated_at: Utc::now(),
|
||||
},
|
||||
organization: Organization {
|
||||
id: Uuid::new_v4(),
|
||||
name: "Test Org".to_string(),
|
||||
domain: None,
|
||||
logo_url: None,
|
||||
primary_color: None,
|
||||
secondary_color: None,
|
||||
certificate_template: None,
|
||||
created_at: Utc::now(),
|
||||
updated_at: Utc::now(),
|
||||
},
|
||||
grading_categories: vec![],
|
||||
modules: vec![pub_module],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, Suspense } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { lmsApi } from "@/lib/api";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
function CallbackHandler() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { login } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
const token = searchParams.get("token");
|
||||
if (token) {
|
||||
// Temporarily store token so getMe can use it
|
||||
localStorage.setItem('experience_token', token);
|
||||
|
||||
lmsApi.getMe()
|
||||
.then((user) => {
|
||||
login(user, token);
|
||||
router.push("/");
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("SSO Error:", err);
|
||||
localStorage.removeItem('experience_token');
|
||||
router.push("/auth/login?error=sso_failed");
|
||||
});
|
||||
} else {
|
||||
router.push("/auth/login");
|
||||
}
|
||||
}, [searchParams, login, router]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<Loader2 className="w-12 h-12 text-indigo-500 animate-spin" />
|
||||
<h2 className="text-xl font-bold text-white text-center">
|
||||
Completando tu inicio de sesión...
|
||||
</h2>
|
||||
<p className="text-gray-400">Por favor espera un momento.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AuthCallbackPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-950 flex items-center justify-center p-4">
|
||||
<Suspense fallback={
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<Loader2 className="w-12 h-12 text-indigo-500 animate-spin" />
|
||||
</div>
|
||||
}>
|
||||
<CallbackHandler />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,8 @@ export default function ExperienceLoginPage() {
|
||||
const [fullName, setFullName] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [ssoMode, setSSOMode] = useState(false);
|
||||
const [orgIdForSSO, setOrgIdForSSO] = useState("");
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -69,20 +71,32 @@ export default function ExperienceLoginPage() {
|
||||
<div className="bg-white/5 backdrop-blur-xl border border-white/10 rounded-3xl p-8">
|
||||
<div className="flex gap-2 mb-6 bg-white/5 rounded-xl p-1">
|
||||
<button
|
||||
onClick={() => setIsLogin(true)}
|
||||
className={`flex-1 py-2 px-4 rounded-lg font-bold transition-all ${isLogin ? "bg-indigo-600 text-white" : "text-gray-400 hover:text-white"
|
||||
onClick={() => {
|
||||
setIsLogin(true);
|
||||
setSSOMode(false);
|
||||
}}
|
||||
className={`flex-1 py-2 px-4 rounded-lg font-bold transition-all ${isLogin && !ssoMode ? "bg-indigo-600 text-white" : "text-gray-400 hover:text-white"
|
||||
}`}
|
||||
Iniciar Sesión/button>
|
||||
>
|
||||
Iniciar Sesión
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setIsLogin(false)}
|
||||
className={`flex-1 py-2 px-4 rounded-lg font-bold transition-all ${!isLogin ? "bg-indigo-600 text-white" : "text-gray-400 hover:text-white"
|
||||
onClick={() => {
|
||||
setIsLogin(false);
|
||||
setSSOMode(false);
|
||||
}}
|
||||
className={`flex-1 py-2 px-4 rounded-lg font-bold transition-all ${!isLogin && !ssoMode ? "bg-indigo-600 text-white" : "text-gray-400 hover:text-white"
|
||||
}`}
|
||||
> Registrarse
|
||||
>
|
||||
Registrarse
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{!ssoMode ? (
|
||||
<>
|
||||
{!isLogin && (
|
||||
<>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-300 mb-2">
|
||||
Nombre Completo
|
||||
@@ -99,8 +113,6 @@ export default function ExperienceLoginPage() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!isLogin && (
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-300 mb-2">
|
||||
Nombre de la Organización (Opcional)
|
||||
@@ -117,6 +129,7 @@ export default function ExperienceLoginPage() {
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-2 pl-1">Si se deja en blanco, se creará una organización basada en el dominio de tu correo electrónico.</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div>
|
||||
@@ -138,7 +151,7 @@ export default function ExperienceLoginPage() {
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-300 mb-2">
|
||||
Contraseña
|
||||
Contraseña
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
|
||||
@@ -152,6 +165,28 @@ Contraseña
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-300 mb-2">
|
||||
ID de la Organización
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Building2 className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={orgIdForSSO}
|
||||
onChange={(e) => setOrgIdForSSO(e.target.value)}
|
||||
className="w-full bg-white/5 border border-white/10 rounded-xl py-3 pl-11 pr-4 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
placeholder="00000000-0000-0000-0000-000000000000"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-2 pl-1">
|
||||
Contacta a tu administrador si no conoces el ID de tu organización.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-500/10 border border-red-500/20 rounded-xl p-3 text-red-400 text-sm">
|
||||
@@ -162,9 +197,39 @@ Contraseña
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
if (ssoMode) {
|
||||
e.preventDefault();
|
||||
if (!orgIdForSSO) {
|
||||
setError("El ID de la organización es requerido");
|
||||
return;
|
||||
}
|
||||
lmsApi.initSSOLogin(orgIdForSSO);
|
||||
}
|
||||
}}
|
||||
className="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? "Procesando..." : isLogin ? "Iniciar Sesión" : "Crear Cuenta"}
|
||||
{loading ? "Procesando..." : ssoMode ? "Continuar con SSO" : isLogin ? "Iniciar Sesión" : "Crear Cuenta"}
|
||||
</button>
|
||||
|
||||
<div className="relative my-6">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t border-white/10"></span>
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-slate-950 px-2 text-gray-500">O bien</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSSOMode(!ssoMode);
|
||||
setError("");
|
||||
}}
|
||||
className="w-full bg-white/5 hover:bg-white/10 text-white font-bold py-3 rounded-xl border border-white/10 transition-colors"
|
||||
>
|
||||
{ssoMode ? "Usar Correo y Contraseña" : "Iniciar Sesión con SSO de Empresa"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -303,7 +303,7 @@ export default function LessonPlayerPage({ params }: { params: { id: string, les
|
||||
{hasTranscription && transcriptOpen && (
|
||||
<aside className="w-[400px] border-l border-white/5 bg-black/20 animate-in slide-in-from-right duration-500">
|
||||
<InteractiveTranscript
|
||||
cues={lesson.transcription!.cues!}
|
||||
transcription={lesson.transcription!}
|
||||
currentTime={currentTime}
|
||||
onSeek={handleSeek}
|
||||
/>
|
||||
|
||||
@@ -1,24 +1,85 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { lmsApi } from "@/lib/api";
|
||||
import { Save, Shield, Mail, User as UserIcon, Building, Trophy, Flame } from "lucide-react";
|
||||
import { lmsApi, CMS_API_URL } from "@/lib/api";
|
||||
import {
|
||||
Save,
|
||||
Shield,
|
||||
Mail,
|
||||
User as UserIcon,
|
||||
Trophy,
|
||||
Flame,
|
||||
Camera,
|
||||
Languages,
|
||||
FileText,
|
||||
LogOut,
|
||||
Trash2,
|
||||
Award
|
||||
} from "lucide-react";
|
||||
|
||||
export default function ProfilePage() {
|
||||
const { user, logout } = useAuth();
|
||||
const [fullName, setFullName] = useState(user?.full_name || "");
|
||||
const [email, setEmail] = useState(user?.email || "");
|
||||
const [bio, setBio] = useState(user?.bio || "");
|
||||
const [language, setLanguage] = useState(user?.language || "es");
|
||||
const [avatarUrl, setAvatarUrl] = useState(user?.avatar_url || "");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);
|
||||
const [gamification, setGamification] = useState<any>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setFullName(user.full_name);
|
||||
setEmail(user.email);
|
||||
setBio(user.bio || "");
|
||||
setLanguage(user.language || "es");
|
||||
setAvatarUrl(user.avatar_url || "");
|
||||
fetchGamification();
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const fetchGamification = async () => {
|
||||
if (!user) return;
|
||||
try {
|
||||
const data = await lmsApi.getGamification(user.id);
|
||||
setGamification(data);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch gamification:", err);
|
||||
}
|
||||
};
|
||||
|
||||
const getImageUrl = (path?: string) => {
|
||||
if (!path) return '';
|
||||
if (path.startsWith('http')) return path;
|
||||
const cleanPath = path.startsWith('/uploads') ? path.replace('/uploads', '/assets') : path;
|
||||
const finalPath = cleanPath.startsWith('/') ? cleanPath : `/${cleanPath}`;
|
||||
return `${CMS_API_URL}${finalPath}`;
|
||||
};
|
||||
|
||||
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file || !user) return;
|
||||
|
||||
try {
|
||||
setUploading(true);
|
||||
const res = await lmsApi.uploadAsset(file);
|
||||
setAvatarUrl(res.url);
|
||||
|
||||
// Auto-save the new avatar URL
|
||||
await lmsApi.updateUser(user.id, { avatar_url: res.url });
|
||||
setMessage({ type: 'success', text: '¡Avatar actualizado con éxito!' });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setMessage({ type: 'error', text: 'Error al subir el avatar.' });
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!user) return;
|
||||
@@ -28,7 +89,10 @@ export default function ProfilePage() {
|
||||
setMessage(null);
|
||||
|
||||
await lmsApi.updateUser(user.id, {
|
||||
full_name: fullName
|
||||
full_name: fullName,
|
||||
bio,
|
||||
language,
|
||||
avatar_url: avatarUrl
|
||||
});
|
||||
|
||||
setMessage({ type: 'success', text: '¡Perfil actualizado con éxito!' });
|
||||
@@ -43,111 +107,220 @@ export default function ProfilePage() {
|
||||
if (!user) return null;
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto py-12 px-6">
|
||||
<div className="max-w-5xl mx-auto py-12 px-6">
|
||||
<div className="mb-12">
|
||||
<h1 className="text-4xl font-black tracking-tight text-white mb-2">Mi Perfil</h1>
|
||||
<p className="text-gray-400">Personaliza tu experiencia de aprendizaje y sigue tu progreso.</p>
|
||||
<p className="text-gray-400">Personaliza tu identidad y sigue tu progreso de aprendizaje.</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||
{/* Profile Card & Stats */}
|
||||
<div className="md:col-span-1 space-y-6">
|
||||
<div className="glass p-8 rounded-3xl border border-white/5 flex flex-col items-center text-center">
|
||||
<div className="w-24 h-24 rounded-full bg-blue-600/20 border-2 border-blue-500/30 flex items-center justify-center font-black text-3xl text-blue-400 mb-4 shadow-2xl shadow-blue-500/20">
|
||||
{user.full_name.charAt(0)}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
||||
{/* Left Column: Stats & Profile */}
|
||||
<div className="lg:col-span-1 space-y-6">
|
||||
<div className="glass p-8 rounded-[2rem] border border-white/5 flex flex-col items-center text-center relative overflow-hidden group">
|
||||
{/* Avatar Section */}
|
||||
<div className="relative mb-6">
|
||||
<div className="w-32 h-32 rounded-full bg-blue-600/20 border-4 border-white/5 flex items-center justify-center overflow-hidden shadow-2xl relative">
|
||||
{avatarUrl ? (
|
||||
<img
|
||||
src={getImageUrl(avatarUrl)}
|
||||
alt={fullName}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-5xl font-black text-blue-400">
|
||||
{fullName.charAt(0)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{uploading && (
|
||||
<div className="absolute inset-0 bg-black/60 flex items-center justify-center">
|
||||
<div className="w-8 h-8 border-2 border-white/20 border-t-white rounded-full animate-spin" />
|
||||
</div>
|
||||
<h2 className="text-xl font-bold text-white">{user.full_name}</h2>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="absolute bottom-0 right-0 w-10 h-10 bg-blue-600 hover:bg-blue-500 rounded-full flex items-center justify-center text-white shadow-xl border-4 border-[#0a0a0b] transition-transform active:scale-90"
|
||||
>
|
||||
<Camera size={18} />
|
||||
</button>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
accept="image/*"
|
||||
onChange={handleAvatarUpload}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h2 className="text-2xl font-black text-white">{fullName}</h2>
|
||||
<span className="text-xs font-black uppercase tracking-widest text-blue-500 mt-1">Estudiante</span>
|
||||
|
||||
<div className="w-full h-px bg-white/5 my-6" />
|
||||
<div className="w-full h-px bg-white/5 my-8" />
|
||||
|
||||
<div className="w-full flex flex-col gap-4 text-left">
|
||||
<div className="flex items-center justify-between p-3 rounded-xl bg-white/5 border border-white/5">
|
||||
<div className="flex items-center gap-3">
|
||||
<Trophy size={16} className="text-yellow-500" />
|
||||
<span className="text-xs font-bold text-white uppercase tracking-tighter">Nivel</span>
|
||||
{/* Gamification Stats */}
|
||||
<div className="w-full grid grid-cols-2 gap-4">
|
||||
<div className="flex flex-col items-center p-4 rounded-2xl bg-white/5 border border-white/5 ring-1 ring-white/5">
|
||||
<Trophy size={20} className="text-yellow-500 mb-2" />
|
||||
<p className="text-[10px] font-black uppercase tracking-tighter text-gray-500">Nivel</p>
|
||||
<p className="text-2xl font-black text-white">{user.level || 1}</p>
|
||||
</div>
|
||||
<span className="text-lg font-black text-white">{user.level || 1}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between p-3 rounded-xl bg-white/5 border border-white/5">
|
||||
<div className="flex items-center gap-3">
|
||||
<Flame size={16} className="text-orange-500" />
|
||||
<span className="text-xs font-bold text-white uppercase tracking-tighter">XP</span>
|
||||
</div>
|
||||
<span className="text-lg font-black text-white">{user.xp || 0}</span>
|
||||
<div className="flex flex-col items-center p-4 rounded-2xl bg-white/5 border border-white/5 ring-1 ring-white/5">
|
||||
<Flame size={20} className="text-orange-500 mb-2" />
|
||||
<p className="text-[10px] font-black uppercase tracking-tighter text-gray-500">XP Total</p>
|
||||
<p className="text-2xl font-black text-white">{user.xp || 0}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={logout}
|
||||
className="mt-8 w-full py-3 rounded-xl border border-white/10 text-sm font-bold text-gray-400 hover:text-white hover:bg-white/5 transition-all"
|
||||
className="mt-10 w-full py-4 rounded-2xl border border-white/5 bg-white/5 text-sm font-black text-gray-400 hover:text-white hover:bg-red-500/10 hover:border-red-500/20 transition-all flex items-center justify-center gap-3 group/logout"
|
||||
>
|
||||
<LogOut size={18} className="group-hover/logout:-translate-x-1 transition-transform" />
|
||||
Cerrar Sesión
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Badges Section */}
|
||||
<div className="glass p-6 rounded-[2rem] border border-white/5">
|
||||
<h3 className="text-sm font-black uppercase tracking-widest text-white mb-6 flex items-center gap-2">
|
||||
<Award size={18} className="text-yellow-500" /> Logros Obtenidos
|
||||
</h3>
|
||||
{gamification?.badges && gamification.badges.length > 0 ? (
|
||||
<div className="grid grid-cols-4 gap-3">
|
||||
{gamification.badges.map((badge: any) => (
|
||||
<div key={badge.id} className="group relative">
|
||||
<div className="w-full aspect-square rounded-xl bg-white/5 border border-white/5 flex items-center justify-center hover:bg-white/10 transition-colors">
|
||||
{badge.icon_url ? (
|
||||
<img src={badge.icon_url} alt={badge.name} className="w-8 h-8 opacity-60 grayscale group-hover:grayscale-0 group-hover:opacity-100 transition-all" />
|
||||
) : (
|
||||
<Award size={24} className="text-gray-600 group-hover:text-yellow-500 transition-colors" />
|
||||
)}
|
||||
</div>
|
||||
<div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 p-2 bg-black border border-white/10 rounded-lg text-[10px] font-bold text-white whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10">
|
||||
{badge.name}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-8 px-4 rounded-2xl bg-white/5 border border-dashed border-white/10">
|
||||
<Award size={32} className="text-gray-700 mx-auto mb-3" />
|
||||
<p className="text-xs text-gray-500 font-bold uppercase tracking-tight">¡Completa lecciones para ganar insignias!</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Settings Form */}
|
||||
<div className="md:col-span-2 space-y-6">
|
||||
<form onSubmit={handleSave} className="glass p-8 rounded-3xl border border-white/5 space-y-6">
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-black uppercase tracking-widest text-gray-500 flex items-center gap-2">
|
||||
<UserIcon size={14} /> Nombre Completo
|
||||
{/* Right Column: Settings Form */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<form onSubmit={handleSave} className="glass p-10 rounded-[2.5rem] border border-white/5 space-y-8">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div className="space-y-3">
|
||||
<label className="text-xs font-black uppercase tracking-[0.2em] text-gray-500 flex items-center gap-2">
|
||||
<UserIcon size={14} className="text-blue-500" /> Nombre Completo
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={fullName}
|
||||
onChange={(e) => setFullName(e.target.value)}
|
||||
className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-blue-500/50 transition-colors placeholder:text-gray-700"
|
||||
className="w-full bg-black/40 border border-white/10 rounded-2xl px-6 py-4 text-white focus:outline-none focus:border-blue-500/50 focus:ring-4 focus:ring-blue-500/5 transition-all outline-none"
|
||||
placeholder="Introduce tu nombre completo"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 opacity-60">
|
||||
<label className="text-xs font-black uppercase tracking-widest text-gray-500 flex items-center gap-2">
|
||||
<Mail size={14} /> Dirección de Correo Electrónico
|
||||
<div className="space-y-3 opacity-60">
|
||||
<label className="text-xs font-black uppercase tracking-[0.2em] text-gray-500 flex items-center gap-2">
|
||||
<Mail size={14} className="text-blue-500" /> Correo Electrónico
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
disabled
|
||||
className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-3 text-white/50 cursor-not-allowed"
|
||||
className="w-full bg-black/20 border border-white/5 rounded-2xl px-6 py-4 text-white/50 cursor-not-allowed"
|
||||
/>
|
||||
<p className="text-[10px] text-gray-500 italic">El correo electrónico no se puede cambiar actualmente.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<label className="text-xs font-black uppercase tracking-[0.2em] text-gray-500 flex items-center gap-2">
|
||||
<FileText size={14} className="text-blue-500" /> Biografía
|
||||
</label>
|
||||
<textarea
|
||||
value={bio}
|
||||
onChange={(e) => setBio(e.target.value)}
|
||||
className="w-full bg-black/40 border border-white/10 rounded-2xl px-6 py-4 text-white focus:outline-none focus:border-blue-500/50 focus:ring-4 focus:ring-blue-500/5 transition-all min-h-[140px] resize-none outline-none"
|
||||
placeholder="Cuéntanos un poco sobre ti..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<label className="text-xs font-black uppercase tracking-[0.2em] text-gray-500 flex items-center gap-2">
|
||||
<Languages size={14} className="text-blue-500" /> Idioma Preferido
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{[
|
||||
{ code: 'en', label: 'English', flag: '🇺🇸' },
|
||||
{ code: 'es', label: 'Español', flag: '🇪🇸' },
|
||||
{ code: 'pt', label: 'Português', flag: '🇧🇷' }
|
||||
].map((lang) => (
|
||||
<button
|
||||
key={lang.code}
|
||||
type="button"
|
||||
onClick={() => setLanguage(lang.code)}
|
||||
className={`flex items-center justify-center gap-3 p-4 rounded-2xl border transition-all ${language === lang.code
|
||||
? 'bg-blue-600 border-blue-500 text-white shadow-lg shadow-blue-500/20'
|
||||
: 'bg-black/20 border-white/5 text-gray-400 hover:border-white/20 hover:text-white'
|
||||
}`}
|
||||
>
|
||||
<span className="text-xl">{lang.flag}</span>
|
||||
<span className="text-sm font-bold">{lang.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className={`p-4 rounded-xl text-sm font-medium ${message.type === 'success' ? 'bg-green-500/10 text-green-400 border border-green-500/20' : 'bg-red-500/10 text-red-400 border border-red-500/20'}`}>
|
||||
<div className={`p-5 rounded-2xl text-sm font-bold animate-in fade-in slide-in-from-top-4 ${message.type === 'success'
|
||||
? 'bg-green-500/10 text-green-400 border border-green-500/20'
|
||||
: 'bg-red-500/10 text-red-400 border border-red-500/20'
|
||||
}`}>
|
||||
{message.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="pt-4">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="w-full py-4 bg-blue-600 hover:bg-blue-500 disabled:bg-blue-600/50 rounded-xl font-black text-white shadow-lg shadow-blue-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-3"
|
||||
className="w-full py-5 bg-blue-600 hover:bg-blue-500 disabled:bg-blue-600/50 rounded-2xl font-black text-white shadow-2xl shadow-blue-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-3 text-lg"
|
||||
>
|
||||
{saving ? (
|
||||
<div className="w-5 h-5 border-2 border-white/20 border-t-white rounded-full animate-spin" />
|
||||
<div className="w-6 h-6 border-3 border-white/20 border-t-white rounded-full animate-spin" />
|
||||
) : (
|
||||
<Save size={20} />
|
||||
<Save size={24} />
|
||||
)}
|
||||
Guardar Cambios
|
||||
Sincronizar Datos de Perfil
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="glass p-6 rounded-3xl border border-white/5 flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-10 h-10 rounded-xl bg-white/5 flex items-center justify-center">
|
||||
<Shield size={18} className="text-gray-400" />
|
||||
{/* Danger Zone */}
|
||||
<div className="glass p-8 rounded-[2rem] border border-red-500/10 bg-red-500/5 flex items-center justify-between">
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="w-14 h-14 rounded-2xl bg-red-500/10 flex items-center justify-center text-red-400 border border-red-500/20 shadow-lg">
|
||||
<Trash2 size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-white font-bold text-sm">Organización</h3>
|
||||
<p className="text-xs text-gray-500 mt-0.5 truncate max-w-[200px]">{user.organization_id}</p>
|
||||
<h3 className="text-red-400 font-black text-lg">Zona Peligrosa</h3>
|
||||
<p className="text-xs text-red-400/60 mt-1">Esto eliminará permanentemente tu identidad y datos.</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-[10px] font-black uppercase tracking-widest text-blue-500 bg-blue-500/10 px-3 py-1 rounded-full border border-blue-500/20">Inquilino Activo</span>
|
||||
<button className="px-8 py-3 border border-red-500/20 rounded-xl text-xs font-black text-red-400 hover:bg-red-500/10 transition-all uppercase tracking-widest active:scale-95">
|
||||
Eliminar Cuenta
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Clock } from "lucide-react";
|
||||
|
||||
interface Cue {
|
||||
@@ -10,15 +10,22 @@ interface Cue {
|
||||
}
|
||||
|
||||
interface InteractiveTranscriptProps {
|
||||
cues: Cue[];
|
||||
transcription: {
|
||||
en?: string;
|
||||
es?: string;
|
||||
cues?: Cue[];
|
||||
};
|
||||
currentTime: number;
|
||||
onSeek: (time: number) => void;
|
||||
}
|
||||
|
||||
export default function InteractiveTranscript({ cues, currentTime, onSeek }: InteractiveTranscriptProps) {
|
||||
export default function InteractiveTranscript({ transcription, currentTime, onSeek }: InteractiveTranscriptProps) {
|
||||
const [lang, setLang] = useState<'en' | 'es'>('es'); // Default to Spanish as per Experience portal target
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const activeCueRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const cues = transcription.cues || [];
|
||||
|
||||
// Auto-scroll to active cue
|
||||
useEffect(() => {
|
||||
if (activeCueRef.current && scrollRef.current) {
|
||||
@@ -41,9 +48,25 @@ export default function InteractiveTranscript({ cues, currentTime, onSeek }: Int
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full glass-card overflow-hidden border-white/5 bg-black/20">
|
||||
<div className="p-6 border-b border-white/5 flex items-center gap-3 bg-white/5">
|
||||
<div className="p-6 border-b border-white/5 flex items-center justify-between bg-white/5">
|
||||
<div className="flex items-center gap-3">
|
||||
<Clock className="w-4 h-4 text-blue-400" />
|
||||
<h3 className="text-[10px] font-black uppercase tracking-[0.2em] text-gray-400">Transcriptor Interactivo</h3>
|
||||
<h3 className="text-[10px] font-black uppercase tracking-[0.2em] text-gray-400">Transcripción</h3>
|
||||
</div>
|
||||
<div className="flex bg-black/40 rounded-lg p-1 border border-white/5">
|
||||
<button
|
||||
onClick={() => setLang('en')}
|
||||
className={`px-3 py-1 text-[10px] font-black rounded-md transition-all ${lang === 'en' ? 'bg-blue-600 text-white' : 'text-gray-500 hover:text-white'}`}
|
||||
>
|
||||
EN
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setLang('es')}
|
||||
className={`px-3 py-1 text-[10px] font-black rounded-md transition-all ${lang === 'es' ? 'bg-blue-600 text-white' : 'text-gray-500 hover:text-white'}`}
|
||||
>
|
||||
ES
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -53,11 +76,14 @@ export default function InteractiveTranscript({ cues, currentTime, onSeek }: Int
|
||||
{cues.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-full text-center p-8">
|
||||
<span className="text-4xl mb-4">🤐</span>
|
||||
<p className="text-xs text-gray-500 uppercase tracking-widest font-bold">No hay transcripción disponible para este contenido</p>
|
||||
<p className="text-xs text-gray-500 uppercase tracking-widest font-bold">No hay transcripción disponible</p>
|
||||
</div>
|
||||
) : (
|
||||
cues.map((cue, index) => {
|
||||
const active = isCueActive(cue);
|
||||
// In a more advanced implementation, we'd have translated cues.
|
||||
// For now, if lang is 'es' and we have a full translation but no cue-level translation,
|
||||
// we'd ideally align them. To keep it simple and working:
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
@@ -80,10 +106,19 @@ export default function InteractiveTranscript({ cues, currentTime, onSeek }: Int
|
||||
);
|
||||
})
|
||||
)}
|
||||
|
||||
{lang === 'es' && transcription.es && cues.length > 0 && (
|
||||
<div className="mt-8 pt-8 border-t border-white/10">
|
||||
<h4 className="text-[10px] font-black uppercase tracking-widest text-blue-400 mb-4">Traducción Completa (Beta)</h4>
|
||||
<p className="text-sm text-gray-400 leading-relaxed italic">
|
||||
{transcription.es}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-white/5 border-t border-white/5 flex items-center justify-between">
|
||||
<span className="text-[8px] font-bold text-gray-500 uppercase tracking-widest">Haz clic en cualquier segmento para saltar</span>
|
||||
<span className="text-[8px] font-bold text-gray-500 uppercase tracking-widest">Haz clic para saltar al tiempo</span>
|
||||
<div className="flex gap-1">
|
||||
<div className="w-1 h-1 rounded-full bg-blue-500 animate-pulse"></div>
|
||||
<div className="w-1 h-1 rounded-full bg-blue-500/50"></div>
|
||||
|
||||
@@ -5,18 +5,20 @@ import { Play, Lock, AlertCircle } from "lucide-react";
|
||||
|
||||
interface MediaPlayerProps {
|
||||
id: string;
|
||||
lessonId?: string;
|
||||
title?: string;
|
||||
url: string;
|
||||
media_type: 'video' | 'audio';
|
||||
config?: {
|
||||
maxPlays?: number;
|
||||
};
|
||||
hasTranscription?: boolean;
|
||||
initialPlayCount?: number;
|
||||
onTimeUpdate?: (time: number) => void;
|
||||
onPlay?: () => void;
|
||||
}
|
||||
|
||||
export default function MediaPlayer({ id, title, url, media_type, config, initialPlayCount, onTimeUpdate, onPlay }: MediaPlayerProps) {
|
||||
export default function MediaPlayer({ id, lessonId, title, url, media_type, config, hasTranscription, initialPlayCount, onTimeUpdate, onPlay }: MediaPlayerProps) {
|
||||
const [playCount, setPlayCount] = useState(initialPlayCount || 0);
|
||||
const [hasStarted, setHasStarted] = useState(false);
|
||||
const [locked, setLocked] = useState(false);
|
||||
@@ -86,6 +88,16 @@ export default function MediaPlayer({ id, title, url, media_type, config, initia
|
||||
return rawUrl;
|
||||
};
|
||||
|
||||
const getToken = () => typeof window !== 'undefined' ? localStorage.getItem('experience_token') : null;
|
||||
const selectedOrgId = typeof window !== 'undefined' ? localStorage.getItem('experience_selected_org_id') : null;
|
||||
|
||||
// Construct VTT URLs with auth if possible, or assume public/handled by backend
|
||||
// Since browser <track> doesn't support custom headers easily,
|
||||
// we might need to handle this via a proxy or temporary signed URLs.
|
||||
// For now, we'll assume the backend allows VTT access if requested with the correct lesson ID.
|
||||
const vttEn = lessonId ? `${CMS_API_URL}/lessons/${lessonId}/vtt?lang=en` : null;
|
||||
const vttEs = lessonId ? `${CMS_API_URL}/lessons/${lessonId}/vtt?lang=es` : null;
|
||||
|
||||
return (
|
||||
<div className="space-y-6" id={id}>
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -102,6 +114,7 @@ export default function MediaPlayer({ id, title, url, media_type, config, initia
|
||||
<video
|
||||
src={getFullUrl(url)}
|
||||
controls
|
||||
crossOrigin="anonymous"
|
||||
className="w-full h-full rounded-xl"
|
||||
onPlay={handlePlay}
|
||||
onTimeUpdate={(e) => {
|
||||
@@ -109,7 +122,14 @@ export default function MediaPlayer({ id, title, url, media_type, config, initia
|
||||
onTimeUpdate(e.currentTarget.currentTime);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
>
|
||||
{hasTranscription && vttEn && (
|
||||
<track kind="subtitles" src={vttEn} srcLang="en" label="English" />
|
||||
)}
|
||||
{hasTranscription && vttEs && (
|
||||
<track kind="subtitles" src={vttEs} srcLang="es" label="Español" />
|
||||
)}
|
||||
</video>
|
||||
) : (
|
||||
<iframe
|
||||
src={getEmbedUrl(url)}
|
||||
|
||||
@@ -99,6 +99,9 @@ export interface User {
|
||||
organization_id: string;
|
||||
xp?: number;
|
||||
level?: number;
|
||||
avatar_url?: string;
|
||||
bio?: string;
|
||||
language?: string;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
@@ -179,6 +182,14 @@ export const lmsApi = {
|
||||
});
|
||||
},
|
||||
|
||||
async getMe(): Promise<User> {
|
||||
return apiFetch('/auth/me', {}, true); // isCMS = true
|
||||
},
|
||||
|
||||
initSSOLogin(orgId: string): void {
|
||||
window.location.href = `${CMS_API_URL}/auth/sso/login/${orgId}`;
|
||||
},
|
||||
|
||||
async enroll(courseId: string, userId: string): Promise<void> {
|
||||
return apiFetch('/enroll', {
|
||||
method: 'POST',
|
||||
@@ -213,10 +224,23 @@ export const lmsApi = {
|
||||
return apiFetch(`/organizations/${orgId}/branding`, {}, true);
|
||||
},
|
||||
|
||||
async updateUser(userId: string, payload: { full_name?: string }): Promise<void> {
|
||||
async updateUser(userId: string, payload: { full_name?: string, avatar_url?: string, bio?: string, language?: string }): Promise<void> {
|
||||
return apiFetch(`/users/${userId}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
},
|
||||
|
||||
async uploadAsset(file: File): Promise<{ id: string, filename: string, url: string }> {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const token = getToken();
|
||||
return fetch(`${CMS_API_URL}/assets/upload`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...(token ? { 'Authorization': `Bearer ${token}` } : {})
|
||||
},
|
||||
body: formData
|
||||
}).then(res => res.json());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useState, useEffect } from 'react';
|
||||
import { cmsApi, Organization, getImageUrl } from '@/lib/api';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
import Image from 'next/image';
|
||||
import { Plus, Building2, Globe, Calendar, ExternalLink, ShieldCheck, Palette, Upload, Save, X } from 'lucide-react';
|
||||
import { Plus, Building2, Globe, Calendar, ExternalLink, ShieldCheck, Palette, Upload, Save, X, Fingerprint, Key, Settings2 } from 'lucide-react';
|
||||
|
||||
export default function OrganizationsPage() {
|
||||
const [organizations, setOrganizations] = useState<Organization[]>([]);
|
||||
@@ -21,6 +21,14 @@ export default function OrganizationsPage() {
|
||||
const [isSavingBranding, setIsSavingBranding] = useState(false);
|
||||
const [uploadingLogo, setUploadingLogo] = useState(false);
|
||||
|
||||
// SSO States
|
||||
const [isSSOModalOpen, setIsSSOModalOpen] = useState(false);
|
||||
const [issuerUrl, setIssuerUrl] = useState('');
|
||||
const [clientId, setClientId] = useState('');
|
||||
const [clientSecret, setClientSecret] = useState('');
|
||||
const [ssoEnabled, setSsoEnabled] = useState(false);
|
||||
const [isSavingSSO, setIsSavingSSO] = useState(false);
|
||||
|
||||
const { user } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -96,6 +104,50 @@ export default function OrganizationsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const openSSOConfig = async (org: Organization) => {
|
||||
setSelectedOrg(org);
|
||||
setIsSSOModalOpen(true);
|
||||
// Temporarily set org in localStorage for API calls
|
||||
localStorage.setItem('studio_selected_org_id', org.id);
|
||||
try {
|
||||
const config = await cmsApi.getSSOConfig();
|
||||
if (config) {
|
||||
setIssuerUrl(config.issuer_url);
|
||||
setClientId(config.client_id);
|
||||
setClientSecret(config.client_secret);
|
||||
setSsoEnabled(config.enabled);
|
||||
} else {
|
||||
setIssuerUrl('');
|
||||
setClientId('');
|
||||
setClientSecret('');
|
||||
setSsoEnabled(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load SSO config', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSSOSave = async () => {
|
||||
if (!selectedOrg) return;
|
||||
|
||||
setIsSavingSSO(true);
|
||||
try {
|
||||
await cmsApi.updateSSOConfig({
|
||||
issuer_url: issuerUrl,
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
enabled: ssoEnabled
|
||||
});
|
||||
setIsSSOModalOpen(false);
|
||||
alert('SSO configuration saved successfully!');
|
||||
} catch (error) {
|
||||
console.error('Failed to save SSO config', error);
|
||||
alert('Failed to save SSO config. Please ensure all fields are correct.');
|
||||
} finally {
|
||||
setIsSavingSSO(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (user?.role !== 'admin') {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-[60vh] text-center">
|
||||
@@ -173,15 +225,21 @@ export default function OrganizationsPage() {
|
||||
{org.id.split('-')[0]}...
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<button
|
||||
onClick={() => openBranding(org)}
|
||||
className="py-2 px-4 text-sm font-medium border border-blue-500/20 bg-blue-500/5 hover:bg-blue-500/10 text-blue-400 rounded-lg transition-colors flex items-center justify-center gap-2"
|
||||
className="py-2 px-2 text-[10px] font-medium border border-blue-500/20 bg-blue-500/5 hover:bg-blue-500/10 text-blue-400 rounded-lg transition-colors flex items-center justify-center gap-1"
|
||||
>
|
||||
<Palette className="w-3 h-3" /> Branding
|
||||
<Palette className="w-3 h-3" /> Brand
|
||||
</button>
|
||||
<button className="py-2 px-4 text-sm font-medium border border-white/5 bg-white/5 hover:bg-white/10 rounded-lg transition-colors flex items-center justify-center gap-2">
|
||||
Details <ExternalLink className="w-3 h-3" />
|
||||
<button
|
||||
onClick={() => openSSOConfig(org)}
|
||||
className="py-2 px-2 text-[10px] font-medium border border-blue-500/20 bg-blue-500/5 hover:bg-blue-500/10 text-blue-400 rounded-lg transition-colors flex items-center justify-center gap-1"
|
||||
>
|
||||
<Fingerprint className="w-3 h-3" /> SSO
|
||||
</button>
|
||||
<button className="py-2 px-2 text-[10px] font-medium border border-white/5 bg-white/5 hover:bg-white/10 rounded-lg transition-colors flex items-center justify-center gap-1 text-gray-400">
|
||||
Docs <ExternalLink className="w-3 h-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -376,6 +434,114 @@ export default function OrganizationsPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* SSO Configuration Modal */}
|
||||
{isSSOModalOpen && selectedOrg && (
|
||||
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-in fade-in duration-200">
|
||||
<div className="w-full max-w-xl glass border border-white/10 rounded-2xl p-8 shadow-2xl">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 rounded-lg bg-blue-500/10 text-blue-400">
|
||||
<Fingerprint className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-xl font-bold">Single Sign-On (OIDC)</h2>
|
||||
<p className="text-sm text-gray-400">{selectedOrg.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={() => setIsSSOModalOpen(false)} className="p-2 hover:bg-white/5 rounded-full transition-colors">
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between p-4 rounded-xl bg-white/5 border border-white/10">
|
||||
<div>
|
||||
<h3 className="font-medium text-white">Enable OIDC SSO</h3>
|
||||
<p className="text-xs text-gray-500">Allow users to log in via your identity provider.</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setSsoEnabled(!ssoEnabled)}
|
||||
className={`w-12 h-6 rounded-full transition-colors relative ${ssoEnabled ? 'bg-blue-600' : 'bg-gray-700'}`}
|
||||
>
|
||||
<div className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-all ${ssoEnabled ? 'right-1' : 'left-1'}`} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 pt-2">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-400 mb-1.5">Issuer URL</label>
|
||||
<div className="relative">
|
||||
<Globe className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="url"
|
||||
value={issuerUrl}
|
||||
onChange={(e) => setIssuerUrl(e.target.value)}
|
||||
className="w-full bg-black/40 border border-white/10 rounded-lg pl-10 pr-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all font-mono text-sm"
|
||||
placeholder="https://accounts.google.com or https://okta.com/..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-400 mb-1.5">Client ID</label>
|
||||
<div className="relative">
|
||||
<ShieldCheck className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="text"
|
||||
value={clientId}
|
||||
onChange={(e) => setClientId(e.target.value)}
|
||||
className="w-full bg-black/40 border border-white/10 rounded-lg pl-10 pr-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all font-mono text-sm"
|
||||
placeholder="Your OIDC Client ID"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-400 mb-1.5">Client Secret</label>
|
||||
<div className="relative">
|
||||
<Key className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="password"
|
||||
value={clientSecret}
|
||||
onChange={(e) => setClientSecret(e.target.value)}
|
||||
className="w-full bg-black/40 border border-white/10 rounded-lg pl-10 pr-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all font-mono text-sm"
|
||||
placeholder="••••••••••••••••"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4 rounded-xl bg-blue-500/10 border border-blue-500/20 space-y-2">
|
||||
<div className="flex items-center gap-2 text-blue-400 text-xs font-bold">
|
||||
<Settings2 className="w-4 h-4" /> CONFIGURATION STEPS
|
||||
</div>
|
||||
<p className="text-[10px] text-blue-300 leading-relaxed">
|
||||
1. Register OpenCCB as an application in your Identity Provider (Okta, Google, Azure AD).<br />
|
||||
2. Set the Redirect URI to: <span className="font-mono bg-blue-500/20 px-1">http://localhost:3001/auth/sso/callback</span><br />
|
||||
3. Copy the Issuer URL, Client ID, and Client Secret here.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 mt-8">
|
||||
<button
|
||||
onClick={() => setIsSSOModalOpen(false)}
|
||||
className="flex-1 px-4 py-3 bg-white/5 hover:bg-white/10 border border-white/10 rounded-xl transition-all font-medium"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSSOSave}
|
||||
disabled={isSavingSSO}
|
||||
className="flex-[2] px-8 py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-xl transition-all shadow-lg shadow-blue-500/20 font-bold flex items-center justify-center gap-2"
|
||||
>
|
||||
{isSavingSSO ? <div className="w-5 h-5 border-2 border-white/20 border-t-white rounded-full animate-spin" /> : <Save className="w-5 h-5" />}
|
||||
Save SSO Settings
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, Suspense } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { cmsApi } from "@/lib/api";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
function CallbackHandler() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { login } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
const token = searchParams.get("token");
|
||||
if (token) {
|
||||
// Temporarily store token so getMe can use it
|
||||
localStorage.setItem('studio_token', token);
|
||||
|
||||
cmsApi.getMe()
|
||||
.then((user) => {
|
||||
login(user, token);
|
||||
router.push("/");
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("SSO Error:", err);
|
||||
localStorage.removeItem('studio_token');
|
||||
router.push("/auth/login?error=sso_failed");
|
||||
});
|
||||
} else {
|
||||
router.push("/auth/login");
|
||||
}
|
||||
}, [searchParams, login, router]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<Loader2 className="w-12 h-12 text-blue-500 animate-spin" />
|
||||
<h2 className="text-xl font-bold text-white text-center">
|
||||
Completing your sign in...
|
||||
</h2>
|
||||
<p className="text-gray-400">Please wait a moment.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AuthCallbackPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-950 flex items-center justify-center p-4">
|
||||
<Suspense fallback={
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<Loader2 className="w-12 h-12 text-blue-500 animate-spin" />
|
||||
</div>
|
||||
}>
|
||||
<CallbackHandler />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,8 @@ export default function StudioLoginPage() {
|
||||
const [fullName, setFullName] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [ssoMode, setSSOMode] = useState(false);
|
||||
const [orgIdForSSO, setOrgIdForSSO] = useState("");
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -86,6 +88,8 @@ export default function StudioLoginPage() {
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{!ssoMode ? (
|
||||
<>
|
||||
{!isLogin && (
|
||||
<>
|
||||
<div>
|
||||
@@ -162,6 +166,28 @@ export default function StudioLoginPage() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-300 mb-2">
|
||||
Organization ID
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Building2 className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={orgIdForSSO}
|
||||
onChange={(e) => setOrgIdForSSO(e.target.value)}
|
||||
className="w-full bg-white/5 border border-white/10 rounded-xl py-3 pl-11 pr-4 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="00000000-0000-0000-0000-000000000000"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-2 pl-1">
|
||||
Contact your administrator if you don't know your Organization ID.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-500/10 border border-red-500/20 rounded-xl p-3 text-red-400 text-sm">
|
||||
@@ -172,9 +198,39 @@ export default function StudioLoginPage() {
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
if (ssoMode) {
|
||||
e.preventDefault();
|
||||
if (!orgIdForSSO) {
|
||||
setError("Organization ID is required");
|
||||
return;
|
||||
}
|
||||
cmsApi.initSSOLogin(orgIdForSSO);
|
||||
}
|
||||
}}
|
||||
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? "Processing..." : isLogin ? "Sign In" : "Create Account"}
|
||||
{loading ? "Processing..." : ssoMode ? "Continue with SSO" : isLogin ? "Sign In" : "Create Account"}
|
||||
</button>
|
||||
|
||||
<div className="relative my-6">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t border-white/10"></span>
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-[#020617] px-2 text-gray-500">Or</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSSOMode(!ssoMode);
|
||||
setError("");
|
||||
}}
|
||||
className="w-full bg-white/5 hover:bg-white/10 text-white font-bold py-3 rounded-xl border border-white/10 transition-colors"
|
||||
>
|
||||
{ssoMode ? "Use Email & Password" : "Login with Enterprise SSO"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -434,7 +434,7 @@ export default function LessonEditor({ params }: { params: { id: string; lessonI
|
||||
<span className="text-2xl">🪄</span>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold italic tracking-tight">AI Content Assistant</h3>
|
||||
<p className="text-xs text-gray-400 mt-1 uppercase tracking-widest font-bold">Automate your content creation</p>
|
||||
<p className="text-xs text-gray-400 mt-1 uppercase tracking-widest font-bold">Automate your content creation with Local AI</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -453,14 +453,17 @@ export default function LessonEditor({ params }: { params: { id: string; lessonI
|
||||
<span className="text-xl">
|
||||
{lesson.transcription_status === 'queued' || lesson.transcription_status === 'processing' ? '⏳' : '🎤'}
|
||||
</span>
|
||||
<div className="text-[10px] font-black uppercase tracking-widest opacity-80">Video/Audio</div>
|
||||
<div className="text-[10px] font-black uppercase tracking-widest opacity-80">Transcription & Translation</div>
|
||||
<div className="font-bold">
|
||||
{lesson.transcription_status === 'queued'
|
||||
? `Queued (${formatTime(transcriptionTimer)})`
|
||||
: lesson.transcription_status === 'processing'
|
||||
? `Transcribing (${formatTime(transcriptionTimer)})`
|
||||
: lesson.transcription ? 'Update Transcript' : 'Transcribe Video'}
|
||||
? `Processing (${formatTime(transcriptionTimer)})`
|
||||
: lesson.transcription ? 'Regenerate Content' : 'Transcribe & Translate'}
|
||||
</div>
|
||||
{lesson.transcription && !lesson.transcription.es && lesson.transcription_status === 'completed' && (
|
||||
<div className="text-[8px] text-amber-500 font-bold uppercase">Translation missing</div>
|
||||
)}
|
||||
{(lesson.transcription_status === 'queued' || lesson.transcription_status === 'processing') && (
|
||||
<div className="absolute bottom-0 left-0 h-1 bg-blue-500 animate-[progress_2s_ease-in-out_infinite]" style={{ width: '100%' }}></div>
|
||||
)}
|
||||
@@ -502,7 +505,7 @@ export default function LessonEditor({ params }: { params: { id: string; lessonI
|
||||
<span className="text-2xl">✨</span>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold font-black italic tracking-tight">AI Lesson Summary</h3>
|
||||
<p className="text-xs text-gray-400 mt-1 uppercase tracking-widest font-bold">Key insights generated by intelligence</p>
|
||||
<p className="text-xs text-gray-400 mt-1 uppercase tracking-widest font-bold">Key insights generated from content</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,24 +1,63 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { cmsApi } from "@/lib/api";
|
||||
import { Save, Shield, Mail, User as UserIcon, Building } from "lucide-react";
|
||||
import { cmsApi, getImageUrl } from "@/lib/api";
|
||||
import {
|
||||
Save,
|
||||
Shield,
|
||||
Mail,
|
||||
User as UserIcon,
|
||||
Building,
|
||||
Camera,
|
||||
Languages,
|
||||
FileText,
|
||||
LogOut,
|
||||
Trash2
|
||||
} from "lucide-react";
|
||||
|
||||
export default function ProfilePage() {
|
||||
const { user, logout } = useAuth();
|
||||
const [fullName, setFullName] = useState(user?.full_name || "");
|
||||
const [email, setEmail] = useState(user?.email || "");
|
||||
const [bio, setBio] = useState(user?.bio || "");
|
||||
const [language, setLanguage] = useState(user?.language || "en");
|
||||
const [avatarUrl, setAvatarUrl] = useState(user?.avatar_url || "");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setFullName(user.full_name);
|
||||
setEmail(user.email);
|
||||
setBio(user.bio || "");
|
||||
setLanguage(user.language || "en");
|
||||
setAvatarUrl(user.avatar_url || "");
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file || !user) return;
|
||||
|
||||
try {
|
||||
setUploading(true);
|
||||
const res = await cmsApi.uploadAsset(file);
|
||||
setAvatarUrl(res.url);
|
||||
|
||||
// Auto-save the new avatar URL
|
||||
await cmsApi.updateUser(user.id, { avatar_url: res.url });
|
||||
setMessage({ type: 'success', text: 'Avatar updated successfully!' });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setMessage({ type: 'error', text: 'Failed to upload avatar.' });
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!user) return;
|
||||
@@ -29,14 +68,12 @@ export default function ProfilePage() {
|
||||
|
||||
await cmsApi.updateUser(user.id, {
|
||||
full_name: fullName,
|
||||
// In this simplified version, we don't allow email change here to avoid complexity
|
||||
bio,
|
||||
language,
|
||||
avatar_url: avatarUrl
|
||||
});
|
||||
|
||||
setMessage({ type: 'success', text: 'Profile updated successfully!' });
|
||||
|
||||
// Optionally update the local user state if needed,
|
||||
// but usually a page refresh or context update would be better.
|
||||
// For now, let's just show the message.
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setMessage({ type: 'error', text: 'Failed to update profile.' });
|
||||
@@ -48,101 +85,196 @@ export default function ProfilePage() {
|
||||
if (!user) return null;
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto py-12 px-6">
|
||||
<div className="max-w-5xl mx-auto py-12 px-6">
|
||||
<div className="mb-12">
|
||||
<h1 className="text-4xl font-black tracking-tight text-white mb-2">User Profile</h1>
|
||||
<p className="text-gray-400">Manage your personal information and account settings.</p>
|
||||
<p className="text-gray-400">Manage your identity and preferences across the platform.</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||
{/* Profile Card */}
|
||||
<div className="md:col-span-1">
|
||||
<div className="glass p-8 rounded-3xl border border-white/5 flex flex-col items-center text-center">
|
||||
<div className="w-24 h-24 rounded-full bg-blue-600/20 border-2 border-blue-500/30 flex items-center justify-center font-black text-3xl text-blue-400 mb-4 shadow-2xl shadow-blue-500/20">
|
||||
{user.full_name.charAt(0)}
|
||||
</div>
|
||||
<h2 className="text-xl font-bold text-white">{user.full_name}</h2>
|
||||
<span className="text-xs font-black uppercase tracking-widest text-blue-500 mt-1">{user.role}</span>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
||||
{/* Left Column: Profile Card */}
|
||||
<div className="lg:col-span-1 space-y-6">
|
||||
<div className="glass p-8 rounded-[2rem] border border-white/5 flex flex-col items-center text-center relative overflow-hidden group">
|
||||
{/* Avatar Section */}
|
||||
<div className="relative mb-6">
|
||||
<div className="w-32 h-32 rounded-full bg-blue-600/20 border-4 border-white/5 flex items-center justify-center overflow-hidden shadow-2xl relative">
|
||||
{avatarUrl ? (
|
||||
<img
|
||||
src={getImageUrl(avatarUrl)}
|
||||
alt={fullName}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-5xl font-black text-blue-400">
|
||||
{fullName.charAt(0)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<div className="w-full h-px bg-white/5 my-6" />
|
||||
|
||||
<div className="w-full flex flex-col gap-4 text-left">
|
||||
<div className="flex items-center gap-3 text-sm text-gray-400">
|
||||
<Building size={16} className="text-gray-600" />
|
||||
<span className="truncate">Org: {user.organization_id}</span>
|
||||
{uploading && (
|
||||
<div className="absolute inset-0 bg-black/60 flex items-center justify-center">
|
||||
<div className="w-8 h-8 border-2 border-white/20 border-t-white rounded-full animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="absolute bottom-0 right-0 w-10 h-10 bg-blue-600 hover:bg-blue-500 rounded-full flex items-center justify-center text-white shadow-xl border-4 border-[#0a0a0b] transition-transform active:scale-90"
|
||||
>
|
||||
<Camera size={18} />
|
||||
</button>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
accept="image/*"
|
||||
onChange={handleAvatarUpload}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h2 className="text-2xl font-black text-white">{fullName}</h2>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<span className="text-[10px] font-black uppercase tracking-widest text-blue-500 bg-blue-500/10 px-3 py-1 rounded-full border border-blue-500/10">
|
||||
{user.role}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="w-full h-px bg-white/5 my-8" />
|
||||
|
||||
<div className="w-full space-y-4 text-left">
|
||||
<div className="flex items-center gap-4 p-3 rounded-2xl bg-white/5 border border-white/5">
|
||||
<Building size={18} className="text-gray-500" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-[10px] font-black uppercase tracking-tighter text-gray-500">Organization</p>
|
||||
<p className="text-xs font-bold text-white truncate">{user.organization_id}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 p-3 rounded-2xl bg-white/5 border border-white/5">
|
||||
<Shield size={18} className="text-gray-500" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-[10px] font-black uppercase tracking-tighter text-gray-500">Access Level</p>
|
||||
<p className="text-xs font-bold text-white truncate capitalize">{user.role}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-sm text-gray-400">
|
||||
<Shield size={16} className="text-gray-600" />
|
||||
<span>Role: {user.role}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={logout}
|
||||
className="mt-8 w-full py-3 rounded-xl border border-white/10 text-sm font-bold text-gray-400 hover:text-white hover:bg-white/5 transition-all"
|
||||
className="mt-10 w-full py-4 rounded-2xl border border-white/5 bg-white/5 text-sm font-black text-gray-400 hover:text-white hover:bg-red-500/10 hover:border-red-500/20 transition-all flex items-center justify-center gap-3 group/logout"
|
||||
>
|
||||
Logout Session
|
||||
<LogOut size={18} className="group-hover/logout:-translate-x-1 transition-transform" />
|
||||
Sign Out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Settings Form */}
|
||||
<div className="md:col-span-2 space-y-6">
|
||||
<form onSubmit={handleSave} className="glass p-8 rounded-3xl border border-white/5 space-y-6">
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-black uppercase tracking-widest text-gray-500 flex items-center gap-2">
|
||||
<UserIcon size={14} /> Full Name
|
||||
{/* Right Column: Settings Form */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<form onSubmit={handleSave} className="glass p-10 rounded-[2.5rem] border border-white/5 space-y-8">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div className="space-y-3">
|
||||
<label className="text-xs font-black uppercase tracking-[0.2em] text-gray-500 flex items-center gap-2">
|
||||
<UserIcon size={14} className="text-blue-500" /> Personal Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={fullName}
|
||||
onChange={(e) => setFullName(e.target.value)}
|
||||
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-blue-500/50 transition-colors"
|
||||
className="w-full bg-black/40 border border-white/10 rounded-2xl px-6 py-4 text-white focus:outline-none focus:border-blue-500/50 focus:ring-4 focus:ring-blue-500/5 transition-all outline-none"
|
||||
placeholder="Enter your full name"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 opacity-60">
|
||||
<label className="text-xs font-black uppercase tracking-widest text-gray-500 flex items-center gap-2">
|
||||
<Mail size={14} /> Email Address
|
||||
<div className="space-y-3 opacity-60">
|
||||
<label className="text-xs font-black uppercase tracking-[0.2em] text-gray-500 flex items-center gap-2">
|
||||
<Mail size={14} className="text-blue-500" /> Email Address
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
disabled
|
||||
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white/50 cursor-not-allowed"
|
||||
className="w-full bg-black/20 border border-white/5 rounded-2xl px-6 py-4 text-white/50 cursor-not-allowed"
|
||||
/>
|
||||
<p className="text-[10px] text-gray-500 italic">Email cannot be changed currently.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<label className="text-xs font-black uppercase tracking-[0.2em] text-gray-500 flex items-center gap-2">
|
||||
<FileText size={14} className="text-blue-500" /> Biography
|
||||
</label>
|
||||
<textarea
|
||||
value={bio}
|
||||
onChange={(e) => setBio(e.target.value)}
|
||||
className="w-full bg-black/40 border border-white/10 rounded-2xl px-6 py-4 text-white focus:outline-none focus:border-blue-500/50 focus:ring-4 focus:ring-blue-500/5 transition-all min-h-[140px] resize-none outline-none"
|
||||
placeholder="Tell us a bit about yourself..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<label className="text-xs font-black uppercase tracking-[0.2em] text-gray-500 flex items-center gap-2">
|
||||
<Languages size={14} className="text-blue-500" /> Preferred Language
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{[
|
||||
{ code: 'en', label: 'English', flag: '🇺🇸' },
|
||||
{ code: 'es', label: 'Spanish', flag: '🇪🇸' },
|
||||
{ code: 'pt', label: 'Portuguese', flag: '🇧🇷' }
|
||||
].map((lang) => (
|
||||
<button
|
||||
key={lang.code}
|
||||
type="button"
|
||||
onClick={() => setLanguage(lang.code)}
|
||||
className={`flex items-center justify-center gap-3 p-4 rounded-2xl border transition-all ${language === lang.code
|
||||
? 'bg-blue-600 border-blue-500 text-white shadow-lg shadow-blue-500/20'
|
||||
: 'bg-black/20 border-white/5 text-gray-400 hover:border-white/20 hover:text-white'
|
||||
}`}
|
||||
>
|
||||
<span className="text-xl">{lang.flag}</span>
|
||||
<span className="text-sm font-bold">{lang.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className={`p-4 rounded-xl text-sm font-medium ${message.type === 'success' ? 'bg-green-500/10 text-green-400 border border-green-500/20' : 'bg-red-500/10 text-red-400 border border-red-500/20'}`}>
|
||||
<div className={`p-5 rounded-2xl text-sm font-bold animate-in fade-in slide-in-from-top-4 ${message.type === 'success'
|
||||
? 'bg-green-500/10 text-green-400 border border-green-500/20'
|
||||
: 'bg-red-500/10 text-red-400 border border-red-500/20'
|
||||
}`}>
|
||||
{message.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="pt-4">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="w-full py-4 bg-blue-600 hover:bg-blue-500 disabled:bg-blue-600/50 rounded-xl font-black text-white shadow-lg shadow-blue-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-3"
|
||||
className="w-full py-5 bg-blue-600 hover:bg-blue-500 disabled:bg-blue-600/50 rounded-2xl font-black text-white shadow-2xl shadow-blue-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-3 text-lg"
|
||||
>
|
||||
{saving ? (
|
||||
<div className="w-5 h-5 border-2 border-white/20 border-t-white rounded-full animate-spin" />
|
||||
<div className="w-6 h-6 border-3 border-white/20 border-t-white rounded-full animate-spin" />
|
||||
) : (
|
||||
<Save size={20} />
|
||||
<Save size={24} />
|
||||
)}
|
||||
Save Changes
|
||||
Sync Profile Data
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="glass p-6 rounded-3xl border border-red-500/10 bg-red-500/5 items-center justify-between flex">
|
||||
<div>
|
||||
<h3 className="text-red-400 font-bold">Danger Zone</h3>
|
||||
<p className="text-xs text-red-400/60 mt-0.5">Deleting your account is permanent.</p>
|
||||
{/* Danger Zone */}
|
||||
<div className="glass p-8 rounded-[2rem] border border-red-500/10 bg-red-500/5 flex items-center justify-between">
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="w-14 h-14 rounded-2xl bg-red-500/10 flex items-center justify-center text-red-400 border border-red-500/20 shadow-lg">
|
||||
<Trash2 size={24} />
|
||||
</div>
|
||||
<button className="px-4 py-2 border border-red-500/20 rounded-lg text-xs font-black text-red-400 hover:bg-red-500/10 transition-colors uppercase tracking-widest">
|
||||
Delete Account
|
||||
<div>
|
||||
<h3 className="text-red-400 font-black text-lg">Danger Zone</h3>
|
||||
<p className="text-xs text-red-400/60 mt-1">This will permanently delete your identity and data.</p>
|
||||
</div>
|
||||
</div>
|
||||
<button className="px-8 py-3 border border-red-500/20 rounded-xl text-xs font-black text-red-400 hover:bg-red-500/10 transition-all uppercase tracking-widest active:scale-95">
|
||||
Purge Account
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -107,6 +107,19 @@ export interface User {
|
||||
full_name: string;
|
||||
role: string;
|
||||
organization_id?: string;
|
||||
avatar_url?: string;
|
||||
bio?: string;
|
||||
language?: string;
|
||||
}
|
||||
|
||||
export interface OrganizationSSOConfig {
|
||||
organization_id: string;
|
||||
issuer_url: string;
|
||||
client_id: string;
|
||||
client_secret: string;
|
||||
enabled: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
@@ -231,6 +244,7 @@ export const cmsApi = {
|
||||
// Auth
|
||||
register: (payload: AuthPayload): Promise<AuthResponse> => apiFetch('/auth/register', { method: 'POST', body: JSON.stringify(payload) }),
|
||||
login: (payload: AuthPayload): Promise<AuthResponse> => apiFetch('/auth/login', { method: 'POST', body: JSON.stringify(payload) }),
|
||||
getMe: (): Promise<User> => apiFetch('/auth/me'),
|
||||
|
||||
// Courses
|
||||
getCourses: (): Promise<Course[]> => apiFetch('/courses'),
|
||||
@@ -266,7 +280,7 @@ export const cmsApi = {
|
||||
|
||||
// Users
|
||||
getAllUsers: (): Promise<User[]> => apiFetch('/users'),
|
||||
updateUser: (id: string, payload: { role?: string, organization_id?: string, full_name?: string }): Promise<void> => apiFetch(`/users/${id}`, { method: 'PUT', body: JSON.stringify(payload) }),
|
||||
updateUser: (id: string, payload: { role?: string, organization_id?: string, full_name?: string, avatar_url?: string, bio?: string, language?: string }): Promise<void> => apiFetch(`/users/${id}`, { method: 'PUT', body: JSON.stringify(payload) }),
|
||||
|
||||
// Webhooks
|
||||
getWebhooks: (): Promise<Webhook[]> => apiFetch('/webhooks'),
|
||||
@@ -332,6 +346,13 @@ export const cmsApi = {
|
||||
});
|
||||
},
|
||||
|
||||
// SSO
|
||||
getSSOConfig: (): Promise<OrganizationSSOConfig | null> => apiFetch('/organization/sso'),
|
||||
updateSSOConfig: (payload: Partial<OrganizationSSOConfig>): Promise<OrganizationSSOConfig> => apiFetch('/organization/sso', { method: 'PUT', body: JSON.stringify(payload) }),
|
||||
initSSOLogin: (orgId: string): void => {
|
||||
window.location.href = `${API_BASE_URL}/auth/sso/login/${orgId}`;
|
||||
},
|
||||
|
||||
// Background Tasks
|
||||
getBackgroundTasks: (): Promise<BackgroundTask[]> => apiFetch('/tasks'),
|
||||
retryTask: (id: string): Promise<void> => apiFetch(`/tasks/${id}/retry`, { method: 'POST' }),
|
||||
|
||||
Reference in New Issue
Block a user