Compare commits
No commits in common. "develop" and "main" have entirely different histories.
|
|
@ -1,30 +0,0 @@
|
||||||
---
|
|
||||||
name: ponytail-review
|
|
||||||
description: >
|
|
||||||
Code review focused exclusively on over-engineering. Finds what to delete:
|
|
||||||
reinvented standard library, unneeded dependencies, speculative abstractions,
|
|
||||||
and dead flexibility.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Ponytail Review
|
|
||||||
|
|
||||||
Review the current diff for unnecessary complexity only. Do not review
|
|
||||||
correctness, security, performance, or style.
|
|
||||||
|
|
||||||
Report one line per finding using:
|
|
||||||
|
|
||||||
`<file>:L<line>: <tag> <what to cut>. <replacement>.`
|
|
||||||
|
|
||||||
Allowed tags:
|
|
||||||
|
|
||||||
- `delete`: dead code or speculative feature; replacement is nothing.
|
|
||||||
- `stdlib`: hand-rolled functionality provided by the standard library.
|
|
||||||
- `native`: code or dependency replaceable by a platform feature.
|
|
||||||
- `yagni`: abstraction with one implementation or one caller.
|
|
||||||
- `shrink`: same logic expressed with fewer lines.
|
|
||||||
|
|
||||||
End with `net: -<N> lines possible.` If there is nothing to cut, report
|
|
||||||
`Lean already. Ship.`
|
|
||||||
|
|
||||||
The review does not apply fixes. A smoke test is the minimum acceptable
|
|
||||||
validation and must not be flagged for deletion.
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
---
|
|
||||||
name: "🐛 Bug Report"
|
|
||||||
about: "Reportar un fallo, error o comportamiento inesperado"
|
|
||||||
title: "fix: "
|
|
||||||
labels: ["type:bug"]
|
|
||||||
---
|
|
||||||
|
|
||||||
### Descripción del Fallo
|
|
||||||
<!-- Descripción clara del error -->
|
|
||||||
|
|
||||||
### Pasos para Reproducir
|
|
||||||
1. Ir a '...'
|
|
||||||
2. Ejecutar '...'
|
|
||||||
3. Ver el fallo
|
|
||||||
|
|
||||||
### Comportamiento Esperado
|
|
||||||
<!-- Qué debería suceder -->
|
|
||||||
|
|
||||||
### Logs o Evidencia
|
|
||||||
<!-- Traza de error, logs de red o capturas -->
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
---
|
|
||||||
name: "✨ Feature Request"
|
|
||||||
about: "Proponer una nueva funcionalidad o módulo para el portafolio"
|
|
||||||
title: "feat: "
|
|
||||||
labels: ["type:feature"]
|
|
||||||
---
|
|
||||||
|
|
||||||
### Descripción de la Funcionalidad
|
|
||||||
<!-- Explicación clara y concisa de lo que se desea lograr -->
|
|
||||||
|
|
||||||
### Justificación / Caso de Uso
|
|
||||||
<!-- ¿Por qué es necesario este cambio o característica? -->
|
|
||||||
|
|
||||||
### Criterios de Aceptación
|
|
||||||
- [ ] Criterio 1
|
|
||||||
- [ ] Criterio 2
|
|
||||||
|
|
||||||
### Consideraciones Técnicas
|
|
||||||
<!-- Frontend Angular, Backend .NET, BD MySQL o UI -->
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
---
|
|
||||||
name: "🛠️ Tarea Técnica / Chore"
|
|
||||||
about: "Mantenimiento, dependencias, refactorización o infraestructura CI/CD"
|
|
||||||
title: "chore: "
|
|
||||||
labels: ["type:chore"]
|
|
||||||
---
|
|
||||||
|
|
||||||
### Objetivo Técnico
|
|
||||||
<!-- Descripción del cambio técnico o de infraestructura -->
|
|
||||||
|
|
||||||
### Tareas a Ejecutar
|
|
||||||
- [ ] Tarea 1
|
|
||||||
- [ ] Tarea 2
|
|
||||||
|
|
||||||
### Criterios de Aceptación
|
|
||||||
- [ ] Pipeline CI exitoso (build y escaneo de secretos)
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
## Tipo de Cambio
|
|
||||||
- [ ] `feat`: Nueva funcionalidad
|
|
||||||
- [ ] `fix`: Corrección de bug
|
|
||||||
- [ ] `chore`: Tarea de mantenimiento / CI
|
|
||||||
- [ ] `refactor`: Refactorización de código
|
|
||||||
- [ ] `docs`: Actualización de documentación
|
|
||||||
|
|
||||||
## Resumen del Cambio
|
|
||||||
<!-- Explica brevemente qué resuelve o implementa este Pull Request -->
|
|
||||||
|
|
||||||
## Verificaciones
|
|
||||||
- [ ] El título sigue la convención Conventional Commits (ej. `feat(auth): mensaje`, `chore(ci): mensaje`)
|
|
||||||
- [ ] La rama de origen sigue el estándar (`feature/*`, `chore/*`, `fix/*`, etc.)
|
|
||||||
- [ ] No contiene secretos, tokens ni contraseñas
|
|
||||||
- [ ] Compila exitosamente en local
|
|
||||||
|
|
@ -1,163 +0,0 @@
|
||||||
name: CI Pipeline - Quality & Build
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- develop
|
|
||||||
- main
|
|
||||||
- master
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- develop
|
|
||||||
- main
|
|
||||||
- master
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
validate-frontend:
|
|
||||||
name: Build & Validate Frontend
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout Code
|
|
||||||
run: |
|
|
||||||
git config --global --add safe.directory "*"
|
|
||||||
git init
|
|
||||||
git remote add origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git 2>/dev/null || git remote set-url origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git
|
|
||||||
git fetch --depth 1 origin ${{ github.sha }}
|
|
||||||
git checkout --force FETCH_HEAD
|
|
||||||
|
|
||||||
- name: Validate Pull Request Metadata
|
|
||||||
if: github.event_name == 'pull_request'
|
|
||||||
env:
|
|
||||||
PR_HEAD_REF: ${{ github.head_ref }}
|
|
||||||
PR_BASE_REF: ${{ github.base_ref }}
|
|
||||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
|
||||||
PR_BODY: ${{ github.event.pull_request.body }}
|
|
||||||
run: |
|
|
||||||
echo "==> Validando Pull Request: '$PR_TITLE'"
|
|
||||||
echo " Rama origen: $PR_HEAD_REF -> Rama destino: $PR_BASE_REF"
|
|
||||||
|
|
||||||
if [[ "$PR_BASE_REF" == "develop" ]]; then
|
|
||||||
if ! [[ "$PR_HEAD_REF" =~ ^(feature|feat|chore|fix|bugfix|refactor|docs|test|perf)/ ]]; then
|
|
||||||
echo "❌ Error de Rama: Pull Requests hacia 'develop' deben provenir de una rama específica (feature/*, chore/*, fix/*, refactor/*, etc.)."
|
|
||||||
echo " Rama recibida: '$PR_HEAD_REF'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
elif [[ "$PR_BASE_REF" == "main" || "$PR_BASE_REF" == "master" ]]; then
|
|
||||||
if ! [[ "$PR_HEAD_REF" =~ ^(release|hotfix)/ || "$PR_HEAD_REF" == "develop" ]]; then
|
|
||||||
echo "❌ Error de Rama: Pull Requests hacia producción ('main') deben provenir de 'develop', 'release/*' o 'hotfix/*'."
|
|
||||||
echo " Rama recibida: '$PR_HEAD_REF'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
TITLE_REGEX="^(feat|fix|chore|docs|style|refactor|perf|test|build|ci|revert)(\([a-zA-Z0-9_\-\./]+\))?!?: .+"
|
|
||||||
if ! [[ "$PR_TITLE" =~ $TITLE_REGEX ]]; then
|
|
||||||
echo "❌ Error de Título: El título del PR debe seguir Conventional Commits."
|
|
||||||
echo " Formato: <tipo>(<ámbito opcional>): <descripción>"
|
|
||||||
echo " Ejemplos: feat(auth): add login form, fix: resolve token refresh, chore(ci): update runner"
|
|
||||||
echo " Título recibido: '$PR_TITLE'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
CLEAN_BODY=$(echo "$PR_BODY" | tr -d '[:space:]')
|
|
||||||
if [[ ${#CLEAN_BODY} -lt 15 ]]; then
|
|
||||||
echo "❌ Error de Descripción: La descripción del Pull Request no puede estar vacía."
|
|
||||||
echo " Por favor explica brevemente qué cambios incluye este PR para facilitar la revisión."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "✅ Validaciones de Pull Request aprobadas."
|
|
||||||
|
|
||||||
- name: Scan for Leaked Secrets & Credentials
|
|
||||||
run: |
|
|
||||||
ARCH=$(uname -m)
|
|
||||||
case "$ARCH" in
|
|
||||||
x86_64) GITLEAKS_ARCH="x64" ;;
|
|
||||||
aarch64|arm64) GITLEAKS_ARCH="arm64" ;;
|
|
||||||
*) GITLEAKS_ARCH="x64" ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
mkdir -p /tmp/bin
|
|
||||||
if ! command -v gitleaks &> /dev/null; then
|
|
||||||
echo "Descargando Gitleaks para $ARCH ($GITLEAKS_ARCH)..."
|
|
||||||
curl -sSL "https://github.com/gitleaks/gitleaks/releases/download/v8.18.4/gitleaks_8.18.4_linux_${GITLEAKS_ARCH}.tar.gz" | tar -xz -C /tmp/bin gitleaks
|
|
||||||
export PATH="/tmp/bin:$PATH"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Ejecutando escaneo de credenciales y secretos..."
|
|
||||||
gitleaks detect --source . --verbose --no-git
|
|
||||||
|
|
||||||
- name: Install Frontend Dependencies
|
|
||||||
run: |
|
|
||||||
cd src/frontend
|
|
||||||
npm ci
|
|
||||||
|
|
||||||
- name: Build Angular 20 Production Bundle
|
|
||||||
run: |
|
|
||||||
cd src/frontend
|
|
||||||
npm run build -- --configuration production
|
|
||||||
|
|
||||||
validate-backend:
|
|
||||||
name: Build & Test Backend (.NET)
|
|
||||||
runs-on: dotnet-runner
|
|
||||||
steps:
|
|
||||||
- name: Checkout Code
|
|
||||||
run: |
|
|
||||||
command -v git >/dev/null || (apt-get update && apt-get install -y --no-install-recommends git)
|
|
||||||
git config --global --add safe.directory "*"
|
|
||||||
git init
|
|
||||||
git remote add origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git 2>/dev/null || git remote set-url origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git
|
|
||||||
git fetch --depth 1 origin ${{ github.sha }}
|
|
||||||
git checkout --force FETCH_HEAD
|
|
||||||
|
|
||||||
- name: Build & Run Backend Unit Tests
|
|
||||||
run: |
|
|
||||||
dotnet test src/backend/Portfolio.sln -c Release --verbosity normal
|
|
||||||
|
|
||||||
- name: Validate Backend Production Publish
|
|
||||||
run: |
|
|
||||||
dotnet publish src/backend/src/Portfolio.WebApi/Portfolio.WebApi.csproj -c Release -o /tmp/publish
|
|
||||||
|
|
||||||
deploy-backend:
|
|
||||||
name: Continuous Deployment to Production VPS
|
|
||||||
needs: [validate-frontend, validate-backend]
|
|
||||||
if: github.event_name == 'push' && (github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/main')
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Deploy Docker Stack on VPS via SSH
|
|
||||||
env:
|
|
||||||
SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
|
|
||||||
VPS_HOST: ${{ secrets.VPS_HOST }}
|
|
||||||
VPS_USER: ${{ secrets.VPS_USER }}
|
|
||||||
VPS_PORT: ${{ secrets.VPS_PORT }}
|
|
||||||
VPS_DEPLOY_PATH: ${{ secrets.VPS_DEPLOY_PATH }}
|
|
||||||
run: |
|
|
||||||
if [ -z "$SSH_KEY" ] || [ -z "$VPS_HOST" ]; then
|
|
||||||
echo "ℹ️ Modo Standby de Despliegue Automático:"
|
|
||||||
echo " Los secretos VPS_SSH_KEY o VPS_HOST aún no están configurados en Forgejo (Settings -> Actions -> Secrets)."
|
|
||||||
echo " Para habilitar despliegue desatendido en cada push, añade estos secretos."
|
|
||||||
echo " Alternativamente, puedes ejecutar en tu VPS: cd /opt/portfolio/deploy && ./deploy.sh"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "==> Iniciando conexión SSH segura con el VPS ($VPS_HOST)..."
|
|
||||||
mkdir -p ~/.ssh
|
|
||||||
echo "$SSH_KEY" > ~/.ssh/id_rsa
|
|
||||||
chmod 600 ~/.ssh/id_rsa
|
|
||||||
|
|
||||||
ssh -o StrictHostKeyChecking=no -p "${VPS_PORT:-22}" "${VPS_USER:-root}@${VPS_HOST}" "bash -s" << 'EOF'
|
|
||||||
set -e
|
|
||||||
echo "==> Conectado al VPS. Actualizando repositorio..."
|
|
||||||
TARGET_DIR="${VPS_DEPLOY_PATH:-/opt/portfolio}"
|
|
||||||
if [ ! -d "$TARGET_DIR" ]; then
|
|
||||||
TARGET_DIR="$HOME/portfolio"
|
|
||||||
fi
|
|
||||||
cd "$TARGET_DIR"
|
|
||||||
git fetch origin develop
|
|
||||||
git checkout develop
|
|
||||||
git pull origin develop
|
|
||||||
echo "==> Reconstruyendo contenedor de la API en producción..."
|
|
||||||
cd deploy
|
|
||||||
docker compose -f docker-compose.prod.yml up -d --build portfolio-api
|
|
||||||
echo "✅ Despliegue continuo completado con éxito."
|
|
||||||
EOF
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
---
|
|
||||||
name: "🐛 Bug Report"
|
|
||||||
about: "Reportar un fallo, error o comportamiento inesperado"
|
|
||||||
title: "fix: "
|
|
||||||
labels: ["type:bug"]
|
|
||||||
---
|
|
||||||
|
|
||||||
### Descripción del Fallo
|
|
||||||
<!-- Descripción clara del error -->
|
|
||||||
|
|
||||||
### Pasos para Reproducir
|
|
||||||
1. Ir a '...'
|
|
||||||
2. Ejecutar '...'
|
|
||||||
3. Ver el fallo
|
|
||||||
|
|
||||||
### Comportamiento Esperado
|
|
||||||
<!-- Qué debería suceder -->
|
|
||||||
|
|
||||||
### Logs o Evidencia
|
|
||||||
<!-- Traza de error, logs de red o capturas -->
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
---
|
|
||||||
name: "✨ Feature Request"
|
|
||||||
about: "Proponer una nueva funcionalidad o módulo para el portafolio"
|
|
||||||
title: "feat: "
|
|
||||||
labels: ["type:feature"]
|
|
||||||
---
|
|
||||||
|
|
||||||
### Descripción de la Funcionalidad
|
|
||||||
<!-- Explicación clara y concisa de lo que se desea lograr -->
|
|
||||||
|
|
||||||
### Justificación / Caso de Uso
|
|
||||||
<!-- ¿Por qué es necesario este cambio o característica? -->
|
|
||||||
|
|
||||||
### Criterios de Aceptación
|
|
||||||
- [ ] Criterio 1
|
|
||||||
- [ ] Criterio 2
|
|
||||||
|
|
||||||
### Consideraciones Técnicas
|
|
||||||
<!-- Frontend Angular, Backend .NET, BD MySQL o UI -->
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
---
|
|
||||||
name: "🛠️ Tarea Técnica / Chore"
|
|
||||||
about: "Mantenimiento, dependencias, refactorización o infraestructura CI/CD"
|
|
||||||
title: "chore: "
|
|
||||||
labels: ["type:chore"]
|
|
||||||
---
|
|
||||||
|
|
||||||
### Objetivo Técnico
|
|
||||||
<!-- Descripción del cambio técnico o de infraestructura -->
|
|
||||||
|
|
||||||
### Tareas a Ejecutar
|
|
||||||
- [ ] Tarea 1
|
|
||||||
- [ ] Tarea 2
|
|
||||||
|
|
||||||
### Criterios de Aceptación
|
|
||||||
- [ ] Pipeline CI exitoso (build y escaneo de secretos)
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
## Tipo de Cambio
|
|
||||||
- [ ] `feat`: Nueva funcionalidad
|
|
||||||
- [ ] `fix`: Corrección de bug
|
|
||||||
- [ ] `chore`: Tarea de mantenimiento / CI
|
|
||||||
- [ ] `refactor`: Refactorización de código
|
|
||||||
- [ ] `docs`: Actualización de documentación
|
|
||||||
|
|
||||||
## Resumen del Cambio
|
|
||||||
<!-- Explica brevemente qué resuelve o implementa este Pull Request -->
|
|
||||||
|
|
||||||
## Verificaciones
|
|
||||||
- [ ] El título sigue la convención Conventional Commits (ej. `feat(auth): mensaje`, `chore(ci): mensaje`)
|
|
||||||
- [ ] La rama de origen sigue el estándar (`feature/*`, `chore/*`, `fix/*`, etc.)
|
|
||||||
- [ ] No contiene secretos, tokens ni contraseñas
|
|
||||||
- [ ] Compila exitosamente en local
|
|
||||||
|
|
@ -1,161 +0,0 @@
|
||||||
name: CI Pipeline - Quality & Build
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- develop
|
|
||||||
- main
|
|
||||||
- master
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- develop
|
|
||||||
- main
|
|
||||||
- master
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
validate-frontend:
|
|
||||||
name: Build & Validate Frontend
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout Code
|
|
||||||
run: |
|
|
||||||
git config --global --add safe.directory "*"
|
|
||||||
git init
|
|
||||||
git remote add origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git 2>/dev/null || git remote set-url origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git
|
|
||||||
git fetch --depth 1 origin ${{ github.sha }}
|
|
||||||
git checkout --force FETCH_HEAD
|
|
||||||
|
|
||||||
- name: Validate Pull Request Metadata
|
|
||||||
if: github.event_name == 'pull_request'
|
|
||||||
env:
|
|
||||||
PR_HEAD_REF: ${{ github.head_ref }}
|
|
||||||
PR_BASE_REF: ${{ github.base_ref }}
|
|
||||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
|
||||||
PR_BODY: ${{ github.event.pull_request.body }}
|
|
||||||
run: |
|
|
||||||
echo "==> Validando Pull Request: '$PR_TITLE'"
|
|
||||||
echo " Rama origen: $PR_HEAD_REF -> Rama destino: $PR_BASE_REF"
|
|
||||||
|
|
||||||
if [[ "$PR_BASE_REF" == "develop" ]]; then
|
|
||||||
if ! [[ "$PR_HEAD_REF" =~ ^(feature|feat|chore|fix|bugfix|refactor|docs|test|perf)/ ]]; then
|
|
||||||
echo "❌ Error de Rama: Pull Requests hacia 'develop' deben provenir de una rama específica (feature/*, chore/*, fix/*, refactor/*, etc.)."
|
|
||||||
echo " Rama recibida: '$PR_HEAD_REF'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
elif [[ "$PR_BASE_REF" == "main" || "$PR_BASE_REF" == "master" ]]; then
|
|
||||||
if ! [[ "$PR_HEAD_REF" =~ ^(release|hotfix)/ || "$PR_HEAD_REF" == "develop" ]]; then
|
|
||||||
echo "❌ Error de Rama: Pull Requests hacia producción ('main') deben provenir de 'develop', 'release/*' o 'hotfix/*'."
|
|
||||||
echo " Rama recibida: '$PR_HEAD_REF'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
TITLE_REGEX="^(feat|fix|chore|docs|style|refactor|perf|test|build|ci|revert)(\([a-zA-Z0-9_\-\./]+\))?!?: .+"
|
|
||||||
if ! [[ "$PR_TITLE" =~ $TITLE_REGEX ]]; then
|
|
||||||
echo "❌ Error de Título: El título del PR debe seguir Conventional Commits."
|
|
||||||
echo " Formato: <tipo>(<ámbito opcional>): <descripción>"
|
|
||||||
echo " Ejemplos: feat(auth): add login form, fix: resolve token refresh, chore(ci): update runner"
|
|
||||||
echo " Título recibido: '$PR_TITLE'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
CLEAN_BODY=$(echo "$PR_BODY" | tr -d '[:space:]')
|
|
||||||
if [[ ${#CLEAN_BODY} -lt 15 ]]; then
|
|
||||||
echo "❌ Error de Descripción: La descripción del Pull Request no puede estar vacía."
|
|
||||||
echo " Por favor explica brevemente qué cambios incluye este PR para facilitar la revisión."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "✅ Validaciones de Pull Request aprobadas."
|
|
||||||
|
|
||||||
- name: Scan for Leaked Secrets & Credentials
|
|
||||||
run: |
|
|
||||||
ARCH=$(uname -m)
|
|
||||||
case "$ARCH" in
|
|
||||||
x86_64) GITLEAKS_ARCH="x64" ;;
|
|
||||||
aarch64|arm64) GITLEAKS_ARCH="arm64" ;;
|
|
||||||
*) GITLEAKS_ARCH="x64" ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
mkdir -p /tmp/bin
|
|
||||||
if ! command -v gitleaks &> /dev/null; then
|
|
||||||
echo "Descargando Gitleaks para $ARCH ($GITLEAKS_ARCH)..."
|
|
||||||
curl -sSL "https://github.com/gitleaks/gitleaks/releases/download/v8.18.4/gitleaks_8.18.4_linux_${GITLEAKS_ARCH}.tar.gz" | tar -xz -C /tmp/bin gitleaks
|
|
||||||
export PATH="/tmp/bin:$PATH"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Ejecutando escaneo de credenciales y secretos..."
|
|
||||||
gitleaks detect --source . --verbose --no-git
|
|
||||||
|
|
||||||
- name: Install Frontend Dependencies
|
|
||||||
run: |
|
|
||||||
cd src/frontend
|
|
||||||
npm ci
|
|
||||||
|
|
||||||
- name: Build Angular 20 Production Bundle
|
|
||||||
run: |
|
|
||||||
cd src/frontend
|
|
||||||
npm run build -- --configuration production
|
|
||||||
|
|
||||||
validate-backend:
|
|
||||||
name: Build & Test Backend (.NET)
|
|
||||||
runs-on: dotnet-runner
|
|
||||||
steps:
|
|
||||||
- name: Checkout Code
|
|
||||||
run: |
|
|
||||||
command -v git >/dev/null || (apt-get update && apt-get install -y --no-install-recommends git)
|
|
||||||
git config --global --add safe.directory "*"
|
|
||||||
git init
|
|
||||||
git remote add origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git 2>/dev/null || git remote set-url origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git
|
|
||||||
git fetch --depth 1 origin ${{ github.sha }}
|
|
||||||
git checkout --force FETCH_HEAD
|
|
||||||
|
|
||||||
- name: Build & Run Backend Unit Tests
|
|
||||||
run: |
|
|
||||||
dotnet test src/backend/Portfolio.sln -c Release --verbosity normal
|
|
||||||
|
|
||||||
- name: Validate Backend Production Publish
|
|
||||||
run: |
|
|
||||||
dotnet publish src/backend/src/Portfolio.WebApi/Portfolio.WebApi.csproj -c Release -o /tmp/publish
|
|
||||||
|
|
||||||
deploy-backend:
|
|
||||||
name: Continuous Deployment to Production VPS
|
|
||||||
needs: [validate-frontend, validate-backend]
|
|
||||||
if: github.event_name == 'push' && (github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/main')
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Deploy Docker Stack on VPS via SSH
|
|
||||||
env:
|
|
||||||
SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
|
|
||||||
VPS_HOST: ${{ secrets.VPS_HOST }}
|
|
||||||
VPS_USER: ${{ secrets.VPS_USER }}
|
|
||||||
VPS_PORT: ${{ secrets.VPS_PORT }}
|
|
||||||
VPS_DEPLOY_PATH: ${{ secrets.VPS_DEPLOY_PATH }}
|
|
||||||
run: |
|
|
||||||
if [ -z "$SSH_KEY" ] || [ -z "$VPS_HOST" ]; then
|
|
||||||
echo "ℹ️ Modo Standby de Despliegue Automático:"
|
|
||||||
echo " Los secretos VPS_SSH_KEY o VPS_HOST aún no están configurados."
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "==> Iniciando conexión SSH segura con el VPS ($VPS_HOST)..."
|
|
||||||
mkdir -p ~/.ssh
|
|
||||||
echo "$SSH_KEY" > ~/.ssh/id_rsa
|
|
||||||
chmod 600 ~/.ssh/id_rsa
|
|
||||||
|
|
||||||
ssh -o StrictHostKeyChecking=no -p "${VPS_PORT:-22}" "${VPS_USER:-root}@${VPS_HOST}" "bash -s" << 'EOF'
|
|
||||||
set -e
|
|
||||||
echo "==> Conectado al VPS. Actualizando repositorio..."
|
|
||||||
TARGET_DIR="${VPS_DEPLOY_PATH:-/opt/portfolio}"
|
|
||||||
if [ ! -d "$TARGET_DIR" ]; then
|
|
||||||
TARGET_DIR="$HOME/portfolio"
|
|
||||||
fi
|
|
||||||
cd "$TARGET_DIR"
|
|
||||||
git fetch origin develop
|
|
||||||
git checkout develop
|
|
||||||
git pull origin develop
|
|
||||||
echo "==> Reconstruyendo contenedor de la API en producción..."
|
|
||||||
cd deploy
|
|
||||||
docker compose -f docker-compose.prod.yml up -d --build portfolio-api
|
|
||||||
echo "✅ Despliegue continuo completado con éxito."
|
|
||||||
EOF
|
|
||||||
|
|
@ -33,17 +33,5 @@ Thumbs.db
|
||||||
desktop.ini
|
desktop.ini
|
||||||
|
|
||||||
# Variables de entorno y secretos locales
|
# Variables de entorno y secretos locales
|
||||||
.env
|
|
||||||
.env.*
|
|
||||||
*.env
|
*.env
|
||||||
*.env.*
|
|
||||||
*.env.local
|
*.env.local
|
||||||
*.pem
|
|
||||||
*.key
|
|
||||||
*.pfx
|
|
||||||
|
|
||||||
# .NET Configuration & Sensitive AppSettings
|
|
||||||
**/appsettings.json
|
|
||||||
**/appsettings.Production.json
|
|
||||||
!**/appsettingsdevelop.json
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
title = "Portfolio Gitleaks Configuration"
|
|
||||||
|
|
||||||
[allowlist]
|
|
||||||
description = "Exclusiones globales de documentación, dependencias compiladas y falsos positivos"
|
|
||||||
paths = [
|
|
||||||
'''(?i)package-lock\.json$''',
|
|
||||||
'''(?i)\.angular/.*''',
|
|
||||||
'''(?i)node_modules/.*''',
|
|
||||||
'''(?i)dist/.*''',
|
|
||||||
'''(?i)\.git/.*'''
|
|
||||||
]
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# Gitleaks Ignore List
|
|
||||||
# Añade aquí fingerprints (huellas) de secretos detectados que sean falsos positivos confirmados.
|
|
||||||
# Formato: una huella o regla por línea.
|
|
||||||
#
|
|
||||||
# Para ignorar un falso positivo directamente en el código fuente, añade el comentario:
|
|
||||||
# const fakeToken = "example_dummy_token"; // gitleaks:allow
|
|
||||||
|
|
@ -1,89 +0,0 @@
|
||||||
# Guía de Despliegue y Puesta en Producción: n8n + Gemini Gratuito + Cloudflare
|
|
||||||
|
|
||||||
Esta guía contiene los pasos exactos para tener tu agente conversacional funcionando en producción 100% gratis.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Paso 1: Obtener la API Key Gratuita de Google Gemini
|
|
||||||
1. Ingresa en [Google AI Studio](https://aistudio.google.com/).
|
|
||||||
2. Inicia sesión con tu cuenta de Google.
|
|
||||||
3. Haz clic en **"Get API key"** -> **"Create API key in new project"**.
|
|
||||||
4. Copia tu API key generada.
|
|
||||||
- *Nota*: La capa gratuita de Gemini 2.0 Flash / 1.5 Flash incluye **15 RPM (peticiones por minuto)** y **1,500 peticiones diarias gratis**, con 1,000,000 de tokens de contexto, lo cual cubre de sobra el tráfico de tu portafolio.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Paso 2: Despliegue de n8n en Oracle Cloud Always Free (o Localmente)
|
|
||||||
|
|
||||||
### Opción A: En tu VPS Gratuito de Oracle Cloud (Recomendado 24/7)
|
|
||||||
1. Inicia sesión en tu consola de Oracle Cloud (Always Free).
|
|
||||||
2. Crea una instancia Compute gratuita (ej. Ubuntu 24.04 ARM Ampere o AMD x86 micro).
|
|
||||||
3. Instala Docker y Docker Compose:
|
|
||||||
```bash
|
|
||||||
sudo apt update && sudo apt install -y docker.io docker-compose
|
|
||||||
sudo usermod -aG docker $USER
|
|
||||||
```
|
|
||||||
4. Clona o copia la carpeta `automation/n8n/` en tu servidor.
|
|
||||||
5. Inicia el contenedor:
|
|
||||||
```bash
|
|
||||||
cd automation/n8n
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
6. n8n estará corriendo en el puerto interno `5678`.
|
|
||||||
|
|
||||||
### Opción B: Probar primero en tu máquina local
|
|
||||||
1. En tu terminal (Arch Linux):
|
|
||||||
```bash
|
|
||||||
cd /home/bryan/Projects/PORTFOLIO/automation/n8n
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
2. Abre tu navegador en `http://localhost:5678`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Paso 3: Conectar Cloudflare Tunnel (SSL Gratuito y Sin Puertos Abiertos)
|
|
||||||
Dado que tu dominio y frontend ya están en Cloudflare:
|
|
||||||
1. Ve a [Cloudflare Zero Trust Dashboard](https://one.dash.cloudflare.com/) -> **Networks** -> **Tunnels**.
|
|
||||||
2. Haz clic en **"Create a Tunnel"** (nombre: `portfolio-n8n`).
|
|
||||||
3. Selecciona **Docker** y copia el token provisto (`eyJh...`).
|
|
||||||
4. En el archivo `automation/n8n/.env` (o directamente en tu servidor):
|
|
||||||
```env
|
|
||||||
CLOUDFLARE_TUNNEL_TOKEN=eyJh...tu_token_aqui...
|
|
||||||
N8N_PUBLIC_WEBHOOK_URL=https://chat-api.tudominio.com/
|
|
||||||
```
|
|
||||||
5. En la pestaña **Public Hostname** del túnel en Cloudflare:
|
|
||||||
- **Subdomain**: `chat-api` (o `n8n`)
|
|
||||||
- **Domain**: Tu dominio gestionado en Cloudflare (ej. `bryanbano.com`)
|
|
||||||
- **Service**: `HTTP` -> `n8n:5678` (o `localhost:5678` si ejecutas cloudflared como servicio).
|
|
||||||
6. ¡Listo! Tu n8n tendrá URL pública segura `https://chat-api.tudominio.com` con HTTPS y protección anti-DDoS sin tocar puertos de router.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Paso 4: Importar el Flujo de Trabajo en n8n
|
|
||||||
1. Abre tu panel de n8n (`http://localhost:5678` o tu subdominio de Cloudflare).
|
|
||||||
2. Crea tu cuenta de administrador de n8n en el primer inicio.
|
|
||||||
3. En el menú de la izquierda, haz clic en **"Workflows"** -> botón de **"..."** (arriba a la derecha) -> **"Import from File"**.
|
|
||||||
4. Selecciona el archivo `portfolio-chat-workflow.json`.
|
|
||||||
5. En el nodo **"Google Gemini Chat Model"**:
|
|
||||||
- Haz clic en **Credentials** -> **Create New**.
|
|
||||||
- Pega tu API Key obtenida en el Paso 1.
|
|
||||||
6. Haz clic en **Save** y enciende el interruptor **"Active"** (arriba a la derecha).
|
|
||||||
7. La URL de tu webhook será:
|
|
||||||
`https://chat-api.tudominio.com/webhook/portfolio-chat` (o `http://localhost:5678/webhook/portfolio-chat` en local).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Paso 5: Probar el Webhook desde la Terminal
|
|
||||||
Puedes verificar que n8n responde correctamente antes de probar el frontend ejecutando:
|
|
||||||
```bash
|
|
||||||
curl -X POST http://localhost:5678/webhook/portfolio-chat \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-d '{"message": "¿Cuál es tu stack principal Bryan?", "sessionId": "test-123"}'
|
|
||||||
```
|
|
||||||
Respuesta esperada:
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"reply": "Hola. Mi stack principal es .NET 8/9 con Clean Architecture y CQRS en backend, y Angular con Signals en frontend...",
|
|
||||||
"sessionId": "test-123"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
@ -1,86 +0,0 @@
|
||||||
# BASE DE CONOCIMIENTO: BRYAN BAÑO (FULLSTACK SOFTWARE ENGINEER)
|
|
||||||
|
|
||||||
## 1. Identidad y Perfil Profesional
|
|
||||||
- **Nombre**: Bryan Baño
|
|
||||||
- **Ubicación**: Quito, Ecuador (Zona horaria: America/Guayaquil / UTC-5)
|
|
||||||
- **Título**: Fullstack Software Engineer | Especialista en .NET Clean Architecture & Angular Signals
|
|
||||||
- **Formación Académica**: Egresado de Ingeniería en Computación de la Escuela Politécnica Nacional (EPN), Quito, Ecuador.
|
|
||||||
- **Disponibilidad**: Abierto a nuevos retos profesionales, proyectos de consultoría, desarrollo de software a medida y posiciones Fullstack / Backend / Frontend de alto impacto.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Filosofía de Ingeniería y Arquitectura
|
|
||||||
- **Clean Architecture (Arquitectura Limpia / Hexagonal)**:
|
|
||||||
- Desacoplamiento estricto de capas: Dominio puro (independiente de frameworks), Aplicación (Casos de uso / CQRS), Infraestructura (Adaptadores externos, BD, APIs) y Presentación.
|
|
||||||
- Inversión de Dependencias (DIP) y puertos & adaptadores.
|
|
||||||
- **Filosofía Ponytail (Simplicidad & Rendimiento)**:
|
|
||||||
- Rechazo a la sobreingeniería: priorizar la librería estándar, APIs nativas del navegador (Canvas 2D, Web Audio API, IntersectionObserver) y patrones limpios antes de instalar librerías pesadas de terceros.
|
|
||||||
- Código mantenible, testeable y optimizado para 60 FPS en web.
|
|
||||||
- **Estándares & Resiliencia**:
|
|
||||||
- Manejo de errores uniforme con RFC 7807 (ProblemDetails).
|
|
||||||
- Tipado estricto extremo, inmutabilidad y DTOs bien definidos.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Stack Tecnológico Principal
|
|
||||||
- **Backend**:
|
|
||||||
- .NET 8 / 9 (C#)
|
|
||||||
- MediatR & Patrón CQRS (Command Query Responsibility Segregation)
|
|
||||||
- Entity Framework Core (EF Core) con optimización de queries y migraciones
|
|
||||||
- FluentValidation para validación declarativa de casos de uso
|
|
||||||
- RESTful APIs seguras, autenticación JWT y autorización basada en roles (RBAC)
|
|
||||||
- **Frontend**:
|
|
||||||
- Angular (versiones modernas 18, 19, 20)
|
|
||||||
- Angular Signals reactivos nativos (`signal`, `computed`, `effect`)
|
|
||||||
- Estrategia de detección de cambios `ChangeDetectionStrategy.OnPush`
|
|
||||||
- Sintaxis moderna de control de flujo (`@if`, `@for`, `@switch`)
|
|
||||||
- HTML5 Canvas 2D acelerado, CSS moderno, diseño Cyber-Zen / Dark Mode
|
|
||||||
- **Bases de Datos & Almacenamiento**:
|
|
||||||
- MySQL / MariaDB (indexación, optimización de queries relacionales)
|
|
||||||
- PostgreSQL
|
|
||||||
- Redis (caching y sesiones)
|
|
||||||
- **DevOps, Cloud & Entorno**:
|
|
||||||
- Docker & Docker Compose para contenerización consistente
|
|
||||||
- Cloudflare (Pages, Workers, Tunnels, DNS, WAF)
|
|
||||||
- AWS (EC2, S3, RDS)
|
|
||||||
- Sistema operativo de desarrollo diario: Arch Linux con Fish Shell
|
|
||||||
- Automatización con n8n, GitHub Actions y herramientas de IA
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Certificaciones y Seguridad
|
|
||||||
- **EC-Council**: NDE (Network Defense Essentials).
|
|
||||||
- **Cisco Networking Academy**: Redes y Endpoint Security.
|
|
||||||
- Buenas prácticas de seguridad en la nube, hardening de contenedores y protección de APIs.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Proyectos Destacados del Portafolio
|
|
||||||
1. **Sistema de Auditoría & Acreditación CACES**:
|
|
||||||
- Plataforma robusta desarrollada para gestión y validación de evidencias académicas para acreditación universitaria.
|
|
||||||
- Arquitectura limpia en .NET, control de acceso granular y trazabilidad documental.
|
|
||||||
2. **Simulador de Respuesta a Incidentes Cloud (Interactive Security Simulator)**:
|
|
||||||
- Módulo interactivo dentro del portafolio que simula ataques en tiempo real y muestra la mitigación mediante arquitecturas serverless y seguridad en la nube.
|
|
||||||
3. **Portafolio Profesional Interactivo (Cyber-Zen & Retro Computing)**:
|
|
||||||
- Aplicación web desarrollada con Angular 20, Clean Architecture, Signals, OnPush.
|
|
||||||
- Incluye experiencia 3D en scroll (laptop desarmable con Three.js), terminal interactiva Linux, mini-sistema operativo retro (ZenOS) con minijuegos en Canvas 2D y probador de API en vivo.
|
|
||||||
4. **Agente Conversacional con n8n & Gemini**:
|
|
||||||
- Chatbot inteligente integrado que responde dudas técnicas y filtra oportunidades laborales en tiempo real.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Canales de Contacto Oficiales
|
|
||||||
- **Email**: Disponible mediante el formulario de contacto del portafolio.
|
|
||||||
- **LinkedIn**: Perfil profesional de Bryan Baño.
|
|
||||||
- **GitHub**: Repositorios de código y proyectos de código abierto.
|
|
||||||
- **Ubicación**: Quito, Ecuador (remoto a nivel global).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Instrucciones y Directrices para el Asistente de IA
|
|
||||||
- **Rol**: Eres el asistente virtual oficial de Bryan Baño en su portafolio web.
|
|
||||||
- **Tono**: Profesional, empático, técnico, conciso y elegante.
|
|
||||||
- **Idioma**: Responde siempre en el mismo idioma en el que te escribe el usuario (Español o Inglés).
|
|
||||||
- **Extensión**: Respuestas breves y precisas (máximo 2-3 párrafos cortos o viñetas claras). No abrumes con textos interminables.
|
|
||||||
- **Exactitud**: Limítate a los datos provistos en esta base de conocimiento. Si te preguntan algo que no conoces de Bryan, sugiere amablemente que le escriban directamente a través de la sección de Contacto del portafolio.
|
|
||||||
- **Llamado a la acción (CTA)**: Si el usuario muestra interés en contratarlo o colaborar, anímalo a dejar un mensaje en el formulario de contacto o conectar por LinkedIn.
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
version: '3.8'
|
|
||||||
|
|
||||||
services:
|
|
||||||
n8n:
|
|
||||||
image: docker.n8n.io/n8nio/n8n:latest
|
|
||||||
container_name: portfolio_n8n
|
|
||||||
restart: always
|
|
||||||
ports:
|
|
||||||
- "5678:5678"
|
|
||||||
environment:
|
|
||||||
- N8N_HOST=0.0.0.0
|
|
||||||
- N8N_PORT=5678
|
|
||||||
- N8N_PROTOCOL=http
|
|
||||||
- WEBHOOK_URL=${N8N_PUBLIC_WEBHOOK_URL:-http://localhost:5678/}
|
|
||||||
- GENERIC_TIMEZONE=America/Guayaquil
|
|
||||||
- N8N_DEFAULT_BINARY_DATA_MODE=filesystem
|
|
||||||
- EXECUTIONS_DATA_PRUNE=true
|
|
||||||
- EXECUTIONS_DATA_MAX_AGE=168
|
|
||||||
volumes:
|
|
||||||
- n8n_data:/home/node/.n8n
|
|
||||||
|
|
||||||
# Cloudflare Tunnel: Expone n8n a internet de forma segura, con HTTPS y sin abrir puertos en el router/firewall
|
|
||||||
# Para activarlo: obtén el token de tu túnel en el panel de Cloudflare Zero Trust y colócalo en el archivo .env
|
|
||||||
cloudflared:
|
|
||||||
image: cloudflare/cloudflared:latest
|
|
||||||
container_name: portfolio_tunnel
|
|
||||||
restart: always
|
|
||||||
command: tunnel run
|
|
||||||
environment:
|
|
||||||
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN:-}
|
|
||||||
depends_on:
|
|
||||||
- n8n
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
n8n_data:
|
|
||||||
|
|
@ -1,256 +0,0 @@
|
||||||
{
|
|
||||||
"name": "Portfolio Bryan - AI Chatbot",
|
|
||||||
"nodes": [
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"httpMethod": "POST",
|
|
||||||
"path": "portfolio-chat",
|
|
||||||
"responseMode": "responseNode",
|
|
||||||
"options": {
|
|
||||||
"allowedOrigins": "*"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"type": "n8n-nodes-base.webhook",
|
|
||||||
"typeVersion": 2,
|
|
||||||
"position": [
|
|
||||||
220,
|
|
||||||
340
|
|
||||||
],
|
|
||||||
"id": "webhook-trigger",
|
|
||||||
"name": "Webhook - Incoming Chat"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"jsCode": "// Sanitización y validación de entrada para proteger cuota de API y prevenir abusos\nconst body = $input.item.json.body || {};\nconst rawMessage = typeof body.message === 'string' ? body.message.trim() : '';\nconst sessionId = typeof body.sessionId === 'string' && body.sessionId ? body.sessionId.slice(0, 64) : 'anon-' + Date.now();\n\nif (!rawMessage) {\n return [{\n json: {\n isValid: false,\n errorMessage: 'El mensaje no puede estar vacío.',\n sessionId\n }\n }];\n}\n\n// Limitar a máximo 400 caracteres para cuidar tokens gratuitos\nconst cleanMessage = rawMessage.slice(0, 400).replace(/<[^>]*>?/gm, '');\n\nreturn [{\n json: {\n isValid: true,\n cleanMessage,\n sessionId\n }\n}];"
|
|
||||||
},
|
|
||||||
"type": "n8n-nodes-base.code",
|
|
||||||
"typeVersion": 2,
|
|
||||||
"position": [
|
|
||||||
460,
|
|
||||||
340
|
|
||||||
],
|
|
||||||
"id": "code-sanitizer",
|
|
||||||
"name": "Sanitize & Validate"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"conditions": {
|
|
||||||
"options": {
|
|
||||||
"caseSensitive": true,
|
|
||||||
"leftValue": "",
|
|
||||||
"typeValidation": "strict"
|
|
||||||
},
|
|
||||||
"conditions": [
|
|
||||||
{
|
|
||||||
"id": "cond-is-valid",
|
|
||||||
"leftValue": "={{ $json.isValid }}",
|
|
||||||
"rightValue": true,
|
|
||||||
"operator": {
|
|
||||||
"type": "boolean",
|
|
||||||
"operation": "equals"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"combinator": "and"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"type": "n8n-nodes-base.if",
|
|
||||||
"typeVersion": 2,
|
|
||||||
"position": [
|
|
||||||
680,
|
|
||||||
340
|
|
||||||
],
|
|
||||||
"id": "if-valid-input",
|
|
||||||
"name": "Is Input Valid?"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"promptType": "define",
|
|
||||||
"text": "={{ $('Sanitize & Validate').item.json.cleanMessage }}",
|
|
||||||
"options": {
|
|
||||||
"systemMessage": "=Eres el asistente virtual oficial de Bryan Baño en su portafolio web personal.\n\n### CONTEXTO DE BRYAN BAÑO:\n- Ingeniero en Computación (EPN, Quito - Ecuador).\n- Especialidad: .NET 8/9 Clean Architecture (CQRS MediatR, EF Core MySQL) y Angular Signals (OnPush, Canvas 2D).\n- Filosofía de Software: Ponytail (Simplicidad extrema, YAGNI, cero sobreingeniería, Web Platform nativa, 60 FPS).\n- Proyectos Destacados: Auditoría CACES (.NET), Incident Simulator Cloud Security (Serverless), Portafolio Interactivo Cyber-Zen.\n- Certificaciones: EC-Council Network Defense Essentials (NDE), Cisco Networking Academy.\n- Ubicación: Quito, Ecuador. Disponible para proyectos y contrataciones remotas globales.\n\n### REGLAS DE RESPUESTA:\n1. Responde siempre en el MISMO idioma del usuario (Español o Inglés).\n2. Sé técnico, conciso, profesional y cálido (máximo 2 a 3 párrafos o viñetas breves).\n3. No inventes experiencia que no esté en este contexto.\n4. Si el visitante desea contactar a Bryan o contratarlo, indícale amablemente que use el formulario de contacto del portafolio o su perfil de LinkedIn."
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"type": "@n8n/n8n-nodes-langchain.agent",
|
|
||||||
"typeVersion": 1.7,
|
|
||||||
"position": [
|
|
||||||
920,
|
|
||||||
240
|
|
||||||
],
|
|
||||||
"id": "ai-agent-bryan",
|
|
||||||
"name": "AI Agent - Bryan Assistant"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"modelName": "models/gemini-2.0-flash",
|
|
||||||
"options": {
|
|
||||||
"temperature": 0.4
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
|
|
||||||
"typeVersion": 1,
|
|
||||||
"position": [
|
|
||||||
880,
|
|
||||||
480
|
|
||||||
],
|
|
||||||
"id": "gemini-model",
|
|
||||||
"name": "Google Gemini Chat Model",
|
|
||||||
"credentials": {
|
|
||||||
"googleGeminiApi": {
|
|
||||||
"id": "gemini-free-cred",
|
|
||||||
"name": "Google Gemini Free API"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"sessionKey": "={{ $('Sanitize & Validate').item.json.sessionId }}",
|
|
||||||
"contextWindowLength": 8
|
|
||||||
},
|
|
||||||
"type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
|
|
||||||
"typeVersion": 1.3,
|
|
||||||
"position": [
|
|
||||||
1040,
|
|
||||||
480
|
|
||||||
],
|
|
||||||
"id": "window-memory",
|
|
||||||
"name": "Window Buffer Memory"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"respondWith": "json",
|
|
||||||
"responseBody": "={\n \"reply\": {{ JSON.stringify($json.output) }},\n \"sessionId\": {{ JSON.stringify($('Sanitize & Validate').item.json.sessionId) }}\n}",
|
|
||||||
"options": {
|
|
||||||
"responseCode": 200,
|
|
||||||
"responseHeaders": {
|
|
||||||
"entries": [
|
|
||||||
{
|
|
||||||
"name": "Access-Control-Allow-Origin",
|
|
||||||
"value": "*"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Access-Control-Allow-Methods",
|
|
||||||
"value": "POST, OPTIONS"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Access-Control-Allow-Headers",
|
|
||||||
"value": "Content-Type"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"type": "n8n-nodes-base.respondToWebhook",
|
|
||||||
"typeVersion": 1.1,
|
|
||||||
"position": [
|
|
||||||
1220,
|
|
||||||
240
|
|
||||||
],
|
|
||||||
"id": "respond-success",
|
|
||||||
"name": "Respond - Success"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"parameters": {
|
|
||||||
"respondWith": "json",
|
|
||||||
"responseBody": "={\n \"reply\": {{ JSON.stringify($json.errorMessage || 'Mensaje no válido.') }},\n \"sessionId\": {{ JSON.stringify($json.sessionId) }}\n}",
|
|
||||||
"options": {
|
|
||||||
"responseCode": 400,
|
|
||||||
"responseHeaders": {
|
|
||||||
"entries": [
|
|
||||||
{
|
|
||||||
"name": "Access-Control-Allow-Origin",
|
|
||||||
"value": "*"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"type": "n8n-nodes-base.respondToWebhook",
|
|
||||||
"typeVersion": 1.1,
|
|
||||||
"position": [
|
|
||||||
1220,
|
|
||||||
420
|
|
||||||
],
|
|
||||||
"id": "respond-error",
|
|
||||||
"name": "Respond - Error"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"connections": {
|
|
||||||
"Webhook - Incoming Chat": {
|
|
||||||
"main": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "Sanitize & Validate",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"Sanitize & Validate": {
|
|
||||||
"main": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "Is Input Valid?",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"Is Input Valid?": {
|
|
||||||
"main": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "AI Agent - Bryan Assistant",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
],
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "Respond - Error",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"AI Agent - Bryan Assistant": {
|
|
||||||
"main": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "Respond - Success",
|
|
||||||
"type": "main",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"Google Gemini Chat Model": {
|
|
||||||
"ai_languageModel": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "AI Agent - Bryan Assistant",
|
|
||||||
"type": "ai_languageModel",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"Window Buffer Memory": {
|
|
||||||
"ai_memory": [
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"node": "AI Agent - Bryan Assistant",
|
|
||||||
"type": "ai_memory",
|
|
||||||
"index": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"settings": {
|
|
||||||
"executionOrder": "v1"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -118,7 +118,24 @@ CREATE TABLE IF NOT EXISTS `project_skills` (
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
-- ------------------------------------------------------------------------------
|
-- ------------------------------------------------------------------------------
|
||||||
-- 6. TABLA: interactive_messages (Libro de Visitas / Mensajes Interactivos)
|
-- 6. TABLA: retro_scores (Tabla de Puntuaciones de Minijuegos Retro)
|
||||||
|
-- Justificación: Soporta la interactividad del videojuego retro en la ventana de
|
||||||
|
-- Retro OS. Los visitantes pueden ingresar su tag arcade de 3-4 letras (ej. 'BRY',
|
||||||
|
-- 'JDO') y competir por el Top 10 en tiempo real. Proporciona un endpoint público
|
||||||
|
-- interactivo perfecto para demostrar llamadas reales al backend .NET y MySQL.
|
||||||
|
-- ------------------------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS `retro_scores` (
|
||||||
|
`id` CHAR(36) NOT NULL,
|
||||||
|
`player_tag` VARCHAR(4) NOT NULL,
|
||||||
|
`game_code` VARCHAR(20) NOT NULL DEFAULT 'ZEN_SNAKE',
|
||||||
|
`score` INT UNSIGNED NOT NULL,
|
||||||
|
`created_at_utc` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
KEY `idx_retro_leaderboard` (`game_code`, `score` DESC, `created_at_utc` ASC)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------------------------
|
||||||
|
-- 7. TABLA: interactive_messages (Libro de Visitas / Mensajes Interactivos)
|
||||||
-- Justificación: Permite a reclutadores y visitantes dejar una firma o mensaje
|
-- Justificación: Permite a reclutadores y visitantes dejar una firma o mensaje
|
||||||
-- desde el comando interactivo de la terminal Linux (`guestbook sign "Mensaje"`)
|
-- desde el comando interactivo de la terminal Linux (`guestbook sign "Mensaje"`)
|
||||||
-- o el probador de API en vivo. Demuestra operaciones de escritura inmediatas
|
-- o el probador de API en vivo. Demuestra operaciones de escritura inmediatas
|
||||||
|
|
@ -136,28 +153,6 @@ CREATE TABLE IF NOT EXISTS `interactive_messages` (
|
||||||
KEY `idx_messages_approved_date` (`is_approved`, `created_at_utc` DESC)
|
KEY `idx_messages_approved_date` (`is_approved`, `created_at_utc` DESC)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
-- ------------------------------------------------------------------------------
|
|
||||||
-- 7. TABLA: contact_inquiries (Consultas Técnicas & Solicitudes de Propuesta)
|
|
||||||
-- Justificación: Almacena leads comerciales B2B y requerimientos de clientes de
|
|
||||||
-- forma privada y segura. Separada estrictamente de 'interactive_messages' (que es
|
|
||||||
-- un libro de visitas público). Soporta filtrado por estado y auditoría por IP.
|
|
||||||
-- ------------------------------------------------------------------------------
|
|
||||||
CREATE TABLE IF NOT EXISTS `contact_inquiries` (
|
|
||||||
`id` CHAR(36) NOT NULL,
|
|
||||||
`full_name_or_company` VARCHAR(100) NOT NULL,
|
|
||||||
`email` VARCHAR(100) NOT NULL,
|
|
||||||
`phone` VARCHAR(30) NULL DEFAULT NULL,
|
|
||||||
`service_type` VARCHAR(50) NOT NULL DEFAULT 'Otro',
|
|
||||||
`project_details` TEXT NOT NULL,
|
|
||||||
`status` ENUM('New', 'Read', 'Replied', 'Archived') NOT NULL DEFAULT 'New',
|
|
||||||
`ip_address` VARCHAR(45) NULL DEFAULT NULL,
|
|
||||||
`created_at_utc` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
`replied_at_utc` DATETIME NULL DEFAULT NULL,
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
KEY `idx_inquiries_status_created` (`status`, `created_at_utc` DESC),
|
|
||||||
KEY `idx_inquiries_created` (`created_at_utc` DESC)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
||||||
|
|
||||||
-- ==============================================================================
|
-- ==============================================================================
|
||||||
-- SEED DATA INICIAL (Datos de prueba para arranque inmediato)
|
-- SEED DATA INICIAL (Datos de prueba para arranque inmediato)
|
||||||
-- ==============================================================================
|
-- ==============================================================================
|
||||||
|
|
@ -206,7 +201,15 @@ VALUES
|
||||||
('33333333-0001-0000-0000-000000000001', '22222222-0004-0000-0000-000000000004')
|
('33333333-0001-0000-0000-000000000001', '22222222-0004-0000-0000-000000000004')
|
||||||
ON DUPLICATE KEY UPDATE `project_id` = `project_id`;
|
ON DUPLICATE KEY UPDATE `project_id` = `project_id`;
|
||||||
|
|
||||||
-- 5. Mensaje de Bienvenida en el Libro de Visitas
|
-- 5. Scores de Prueba para el Minijuego Retro
|
||||||
|
INSERT INTO `retro_scores` (`id`, `player_tag`, `game_code`, `score`)
|
||||||
|
VALUES
|
||||||
|
(UUID(), 'ZEN', 'ZEN_SNAKE', 1450),
|
||||||
|
(UUID(), 'NEO', 'ZEN_SNAKE', 1120),
|
||||||
|
(UUID(), 'BRY', 'ZEN_SNAKE', 980)
|
||||||
|
ON DUPLICATE KEY UPDATE `player_tag` = `player_tag`;
|
||||||
|
|
||||||
|
-- 6. Mensaje de Bienvenida en el Libro de Visitas
|
||||||
INSERT INTO `interactive_messages` (`id`, `sender_name`, `sender_contact`, `message`, `origin`)
|
INSERT INTO `interactive_messages` (`id`, `sender_name`, `sender_contact`, `message`, `origin`)
|
||||||
VALUES (
|
VALUES (
|
||||||
UUID(),
|
UUID(),
|
||||||
|
|
@ -215,16 +218,3 @@ VALUES (
|
||||||
'Bienvenido a la terminal interactiva. Ejecuta "help" para comenzar.',
|
'Bienvenido a la terminal interactiva. Ejecuta "help" para comenzar.',
|
||||||
'Terminal'
|
'Terminal'
|
||||||
) ON DUPLICATE KEY UPDATE `sender_name` = `sender_name`;
|
) ON DUPLICATE KEY UPDATE `sender_name` = `sender_name`;
|
||||||
|
|
||||||
-- 6. Consulta de Contacto Inicial de Prueba
|
|
||||||
INSERT INTO `contact_inquiries` (`id`, `full_name_or_company`, `email`, `phone`, `service_type`, `project_details`, `status`)
|
|
||||||
VALUES (
|
|
||||||
'44444444-0001-0000-0000-000000000001',
|
|
||||||
'Enterprise Solutions Corp',
|
|
||||||
'contacto@enterprisesolutions.com',
|
|
||||||
'+593 99 123 4567',
|
|
||||||
'Desarrollo Backend',
|
|
||||||
'Requerimos modernización de arquitectura monolítica a microservicios con .NET 9, Clean Architecture y CQRS.',
|
|
||||||
'New'
|
|
||||||
) ON DUPLICATE KEY UPDATE `full_name_or_company` = `full_name_or_company`;
|
|
||||||
|
|
||||||
|
|
|
||||||
149
deploy/README.md
149
deploy/README.md
|
|
@ -1,149 +0,0 @@
|
||||||
# Guía de Despliegue en Producción: Backend .NET, MySQL & Cloudflare Tunnel
|
|
||||||
|
|
||||||
Este directorio contiene la orquestación completa para desplegar el backend (.NET 8/9 Clean Architecture) y la base de datos MySQL 8.0 en tu servidor VPS de Oracle Cloud (`srv-personal-core`), exponiéndola de forma segura a través de **Cloudflare Zero Trust Tunnel** sin abrir puertos directos en el firewall.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Arquitectura de Despliegue
|
|
||||||
|
|
||||||
```
|
|
||||||
[Internet / Visitantes]
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
[Cloudflare Edge Network & WAF]
|
|
||||||
│ (Túnel cifrado WireGuard / QUIC)
|
|
||||||
▼
|
|
||||||
[cloudflared (Tunnel Daemon)]
|
|
||||||
│ (Red interna de Docker: portfolio-network)
|
|
||||||
┌─────────────┴─────────────┐
|
|
||||||
▼ ▼
|
|
||||||
[portfolio_api] [portfolio_n8n]
|
|
||||||
(.NET 8 Kestrel :8080) (n8n Engine :5678)
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
[portfolio_mysql]
|
|
||||||
(MySQL 8.0 :3306)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Preparación en el VPS (Oracle Cloud)
|
|
||||||
|
|
||||||
### Paso 2.1: Navegar al directorio del proyecto
|
|
||||||
Conéctate por SSH a tu VPS y clona o actualiza el repositorio:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Si es la primera vez:
|
|
||||||
cd /opt # o tu directorio preferido, e.g. ~/portfolio
|
|
||||||
git clone https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git
|
|
||||||
cd PORTFOLIO
|
|
||||||
|
|
||||||
# Si ya tienes el repositorio, actualiza la rama develop:
|
|
||||||
git checkout develop
|
|
||||||
git pull origin develop
|
|
||||||
```
|
|
||||||
|
|
||||||
### Paso 2.2: Configurar Variables de Entorno (`.env`)
|
|
||||||
Copia la plantilla de entorno:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd deploy
|
|
||||||
cp .env.example .env
|
|
||||||
```
|
|
||||||
|
|
||||||
Edita `.env` con tu editor preferido (`nano .env` o `vim .env`):
|
|
||||||
- **`DB_ROOT_PASSWORD`**: Genera una contraseña segura para el usuario root de MySQL.
|
|
||||||
- **`DB_PASSWORD`**: Genera una contraseña para el usuario `portfolio_user`.
|
|
||||||
- **`JWT_SECRET_KEY`**: Genera una clave criptográfica de al menos 32 caracteres ejecutando:
|
|
||||||
```bash
|
|
||||||
openssl rand -base64 48
|
|
||||||
```
|
|
||||||
- **`CLOUDFLARE_TUNNEL_TOKEN`**: Pega aquí el token de tu túnel de Cloudflare (obtenido en el Paso 3).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Configuración en el Panel de Cloudflare Zero Trust
|
|
||||||
|
|
||||||
Para que `https://api.bryan-bano.com` enrute automáticamente al backend en tu VPS:
|
|
||||||
|
|
||||||
1. Ingresa a **[Cloudflare Zero Trust Dashboard](https://one.dash.cloudflare.com/)**.
|
|
||||||
2. Ve a **Networks** -> **Tunnels**.
|
|
||||||
3. Selecciona tu túnel activo (por ejemplo el que ya usas para `git.bryan-bano.com` o `n8n.bryan-bano.com`), o haz clic en **Create a Tunnel** si prefieres uno independiente.
|
|
||||||
4. En la pestaña **Public Hostnames**, haz clic en **Add a public hostname**:
|
|
||||||
- **Subdomain:** `api`
|
|
||||||
- **Domain:** `bryan-bano.com`
|
|
||||||
- **Path:** (dejar vacío)
|
|
||||||
- **Type:** `HTTP`
|
|
||||||
- **URL:**
|
|
||||||
- Si usas el contenedor `portfolio_tunnel` de este compose: `portfolio-api:8080`
|
|
||||||
- Si ya tienes `cloudflared` corriendo como servicio en el host o en otro contenedor compartido: `localhost:8080` (o `127.0.0.1:8080`)
|
|
||||||
5. Haz clic en **Save hostname**.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Iniciar los Servicios con Docker Compose
|
|
||||||
|
|
||||||
Desde la carpeta `deploy/` del VPS, ejecuta:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose -f docker-compose.prod.yml up -d --build
|
|
||||||
```
|
|
||||||
|
|
||||||
### ¿Qué hace este comando automáticamente?
|
|
||||||
1. **Compila la API .NET en Release:** Usa el `Dockerfile` multi-stage, compila con el SDK de .NET y genera el contenedor ligero en `aspnet:8.0`.
|
|
||||||
2. **Inicia MySQL 8.0:** Crea el volumen persistente `portfolio_mysql_data` y ejecuta el script `init-db.sql` con los esquemas y datos iniciales (proyectos, habilidades y récords).
|
|
||||||
3. **Sincroniza el Esquema de EF Core:** Al arrancar, el backend ejecuta `EnsureCreated()` para verificar y garantizar que todas las tablas y relaciones estén en sincronía.
|
|
||||||
4. **Levanta el Cloudflare Tunnel:** Conecta la API a la red perimetral de Cloudflare con HTTPS y SSL automáticos.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Verificación y Pruebas en Vivo
|
|
||||||
|
|
||||||
Una vez iniciado el contenedor, ejecuta las siguientes comprobaciones:
|
|
||||||
|
|
||||||
### 5.1 Verificar estado de los contenedores
|
|
||||||
```bash
|
|
||||||
docker compose -f docker-compose.prod.yml ps
|
|
||||||
```
|
|
||||||
Deberías ver `portfolio_api`, `portfolio_mysql` (healthy) y `portfolio_tunnel` (opcional) en estado `Up`.
|
|
||||||
|
|
||||||
### 5.2 Probar la API localmente en el VPS
|
|
||||||
```bash
|
|
||||||
curl http://localhost:8080/
|
|
||||||
# Respuesta esperada:
|
|
||||||
# {"service":"Portfolio Backend API","status":"Online","version":"1.0.0","docs":"/swagger"}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5.3 Probar la API pública con SSL
|
|
||||||
```bash
|
|
||||||
curl https://api.bryan-bano.com/
|
|
||||||
curl https://api.bryan-bano.com/api/v1/telemetry
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5.4 Documentación Swagger en Producción
|
|
||||||
Abre en tu navegador:
|
|
||||||
```
|
|
||||||
https://api.bryan-bano.com/swagger
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Mantenimiento y Comandos Útiles
|
|
||||||
|
|
||||||
- **Ver logs de la API en tiempo real:**
|
|
||||||
```bash
|
|
||||||
docker logs -f portfolio_api
|
|
||||||
```
|
|
||||||
- **Ver logs de la base de datos:**
|
|
||||||
```bash
|
|
||||||
docker logs -f portfolio_mysql
|
|
||||||
```
|
|
||||||
- **Reiniciar la API tras una actualización de código:**
|
|
||||||
```bash
|
|
||||||
git pull origin develop
|
|
||||||
docker compose -f docker-compose.prod.yml up -d --build portfolio-api
|
|
||||||
```
|
|
||||||
- **Realizar backup de la base de datos MySQL:**
|
|
||||||
```bash
|
|
||||||
docker exec portfolio_mysql mysqldump -u portfolio_user -p portfolio_db > backup_$(date +%F).sql
|
|
||||||
```
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# ==============================================================================
|
|
||||||
# Script de Despliegue Continuo / Actualización en el VPS
|
|
||||||
# ==============================================================================
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
||||||
ROOT_DIR="$(dirname "$SCRIPT_DIR")"
|
|
||||||
|
|
||||||
echo "========================================================"
|
|
||||||
echo "🚀 INICIANDO DESPLIEGUE EN PRODUCCIÓN (PORTFOLIO)"
|
|
||||||
echo "========================================================"
|
|
||||||
|
|
||||||
cd "$ROOT_DIR"
|
|
||||||
|
|
||||||
echo "==> [1/4] Actualizando rama develop desde Forgejo..."
|
|
||||||
git fetch origin develop
|
|
||||||
git checkout develop
|
|
||||||
git pull origin develop
|
|
||||||
|
|
||||||
echo "==> [2/4] Verificando variables de entorno en deploy/.env..."
|
|
||||||
if [ ! -f "$SCRIPT_DIR/.env" ]; then
|
|
||||||
echo "❌ Error: No existe el archivo $SCRIPT_DIR/.env"
|
|
||||||
echo " Copia $SCRIPT_DIR/.env.example a $SCRIPT_DIR/.env y rellena tus claves."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "==> [3/4] Compilando y levantando contenedores Docker..."
|
|
||||||
cd "$SCRIPT_DIR"
|
|
||||||
docker compose -f docker-compose.prod.yml up -d --build
|
|
||||||
|
|
||||||
echo "==> [4/4] Comprobando salud de los servicios..."
|
|
||||||
sleep 5
|
|
||||||
docker compose -f docker-compose.prod.yml ps
|
|
||||||
|
|
||||||
echo "========================================================"
|
|
||||||
echo "✅ DESPLIEGUE COMPLETADO EXITOSAMENTE"
|
|
||||||
echo " API disponible en: http://localhost:8080 o https://api.bryan-bano.com"
|
|
||||||
echo "========================================================"
|
|
||||||
|
|
@ -1,75 +0,0 @@
|
||||||
services:
|
|
||||||
portfolio-api:
|
|
||||||
build:
|
|
||||||
context: ../src/backend
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
image: portfolio-backend:latest
|
|
||||||
container_name: portfolio_api
|
|
||||||
restart: unless-stopped
|
|
||||||
ports:
|
|
||||||
- "8080:8080"
|
|
||||||
environment:
|
|
||||||
- ASPNETCORE_ENVIRONMENT=Production
|
|
||||||
- ASPNETCORE_URLS=http://+:8080
|
|
||||||
- ConnectionStrings__DefaultConnection=Server=portfolio-mysql;Port=3306;Database=portfolio_db;User=portfolio_user;Password=${DB_PASSWORD};CharSet=utf8mb4;
|
|
||||||
- JwtSettings__SecretKey=${JWT_SECRET_KEY}
|
|
||||||
- JwtSettings__Issuer=https://api.bryan-bano.com
|
|
||||||
- JwtSettings__Audience=https://bryan-bano.com
|
|
||||||
- CorsSettings__AllowedOrigins__0=https://bryan-bano.com
|
|
||||||
- CorsSettings__AllowedOrigins__1=https://portfolio.bryan-bano.com
|
|
||||||
- CorsSettings__AllowedOrigins__2=https://git.bryan-bano.com
|
|
||||||
- CorsSettings__AllowedOrigins__3=http://localhost:4200
|
|
||||||
- EnableSwaggerInProd=${ENABLE_SWAGGER:-true}
|
|
||||||
depends_on:
|
|
||||||
portfolio-mysql:
|
|
||||||
condition: service_healthy
|
|
||||||
networks:
|
|
||||||
- portfolio-network
|
|
||||||
|
|
||||||
portfolio-mysql:
|
|
||||||
image: mysql:8.0
|
|
||||||
container_name: portfolio_mysql
|
|
||||||
restart: unless-stopped
|
|
||||||
command:
|
|
||||||
- --default-authentication-plugin=mysql_native_password
|
|
||||||
- --character-set-server=utf8mb4
|
|
||||||
- --collation-server=utf8mb4_unicode_ci
|
|
||||||
- --innodb-buffer-pool-size=256M
|
|
||||||
- --max-connections=100
|
|
||||||
environment:
|
|
||||||
- MYSQL_ROOT_PASSWORD=${DB_ROOT_PASSWORD}
|
|
||||||
- MYSQL_DATABASE=portfolio_db
|
|
||||||
- MYSQL_USER=portfolio_user
|
|
||||||
- MYSQL_PASSWORD=${DB_PASSWORD}
|
|
||||||
volumes:
|
|
||||||
- mysql_data:/var/lib/mysql
|
|
||||||
- ./init-db.sql:/docker-entrypoint-initdb.d/01-init.sql:ro
|
|
||||||
healthcheck:
|
|
||||||
test: ["CMD-SHELL", "mysqladmin ping -h localhost -u root -p$${MYSQL_ROOT_PASSWORD} || exit 1"]
|
|
||||||
interval: 10s
|
|
||||||
timeout: 5s
|
|
||||||
retries: 5
|
|
||||||
start_period: 20s
|
|
||||||
networks:
|
|
||||||
- portfolio-network
|
|
||||||
|
|
||||||
portfolio-tunnel:
|
|
||||||
image: cloudflare/cloudflared:latest
|
|
||||||
container_name: portfolio_tunnel
|
|
||||||
restart: unless-stopped
|
|
||||||
command: tunnel run
|
|
||||||
environment:
|
|
||||||
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN}
|
|
||||||
depends_on:
|
|
||||||
- portfolio-api
|
|
||||||
networks:
|
|
||||||
- portfolio-network
|
|
||||||
|
|
||||||
networks:
|
|
||||||
portfolio-network:
|
|
||||||
driver: bridge
|
|
||||||
name: portfolio_network
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
mysql_data:
|
|
||||||
name: portfolio_mysql_data
|
|
||||||
|
|
@ -1,116 +0,0 @@
|
||||||
-- ==============================================================================
|
|
||||||
-- Portfolio MySQL Database Initialization & Seed Script
|
|
||||||
-- ==============================================================================
|
|
||||||
|
|
||||||
CREATE DATABASE IF NOT EXISTS `portfolio_db` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
|
||||||
USE `portfolio_db`;
|
|
||||||
|
|
||||||
-- 1. Tabla de Habilidades Técnicas
|
|
||||||
CREATE TABLE IF NOT EXISTS `Skills` (
|
|
||||||
`Id` VARCHAR(36) NOT NULL,
|
|
||||||
`Name` VARCHAR(60) NOT NULL,
|
|
||||||
`Category` INT NOT NULL,
|
|
||||||
`ProficiencyPercentage` INT NOT NULL,
|
|
||||||
`IconUrl` VARCHAR(255) NULL,
|
|
||||||
`IsFeatured` TINYINT(1) NOT NULL DEFAULT 0,
|
|
||||||
`CreatedAt` DATETIME(6) NOT NULL,
|
|
||||||
`UpdatedAt` DATETIME(6) NULL,
|
|
||||||
PRIMARY KEY (`Id`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
||||||
|
|
||||||
-- 2. Tabla de Proyectos de Producción
|
|
||||||
CREATE TABLE IF NOT EXISTS `Projects` (
|
|
||||||
`Id` VARCHAR(36) NOT NULL,
|
|
||||||
`Title` VARCHAR(120) NOT NULL,
|
|
||||||
`Slug` VARCHAR(140) NOT NULL,
|
|
||||||
`Summary` VARCHAR(300) NOT NULL,
|
|
||||||
`Description` TEXT NOT NULL,
|
|
||||||
`ArchitectureOverview` TEXT NOT NULL,
|
|
||||||
`ThumbnailUrl` VARCHAR(255) NULL,
|
|
||||||
`DemoUrl` VARCHAR(255) NULL,
|
|
||||||
`RepositoryUrl` VARCHAR(255) NULL,
|
|
||||||
`IsFeatured` TINYINT(1) NOT NULL DEFAULT 0,
|
|
||||||
`OrderPriority` INT NOT NULL DEFAULT 0,
|
|
||||||
`CreatedAt` DATETIME(6) NOT NULL,
|
|
||||||
`UpdatedAt` DATETIME(6) NULL,
|
|
||||||
PRIMARY KEY (`Id`),
|
|
||||||
UNIQUE KEY `UX_Projects_Slug` (`Slug`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
||||||
|
|
||||||
-- 3. Tabla Intermedia Proyecto - Habilidad (Muchos a Muchos)
|
|
||||||
CREATE TABLE IF NOT EXISTS `ProjectSkills` (
|
|
||||||
`ProjectId` VARCHAR(36) NOT NULL,
|
|
||||||
`SkillId` VARCHAR(36) NOT NULL,
|
|
||||||
PRIMARY KEY (`ProjectId`, `SkillId`),
|
|
||||||
CONSTRAINT `FK_ProjectSkills_Projects` FOREIGN KEY (`ProjectId`) REFERENCES `Projects` (`Id`) ON DELETE CASCADE,
|
|
||||||
CONSTRAINT `FK_ProjectSkills_Skills` FOREIGN KEY (`SkillId`) REFERENCES `Skills` (`Id`) ON DELETE CASCADE
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
||||||
|
|
||||||
-- 4. Tabla de Firmas del Muro (Guestbook Wall)
|
|
||||||
CREATE TABLE IF NOT EXISTS `InteractiveMessages` (
|
|
||||||
`Id` VARCHAR(36) NOT NULL,
|
|
||||||
`SenderName` VARCHAR(80) NOT NULL,
|
|
||||||
`SenderContact` VARCHAR(100) NULL,
|
|
||||||
`Message` VARCHAR(500) NOT NULL,
|
|
||||||
`Origin` INT NOT NULL DEFAULT 0,
|
|
||||||
`IsApproved` TINYINT(1) NOT NULL DEFAULT 1,
|
|
||||||
`LikesCount` INT NOT NULL DEFAULT 0,
|
|
||||||
`CreatedAt` DATETIME(6) NOT NULL,
|
|
||||||
`UpdatedAt` DATETIME(6) NULL,
|
|
||||||
PRIMARY KEY (`Id`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
||||||
|
|
||||||
-- 5. Tabla de Récords de Videojuegos Retro (Buscaminas)
|
|
||||||
CREATE TABLE IF NOT EXISTS `GameScores` (
|
|
||||||
`Id` VARCHAR(36) NOT NULL,
|
|
||||||
`GameCode` VARCHAR(30) NOT NULL,
|
|
||||||
`PlayerTag` VARCHAR(10) NOT NULL,
|
|
||||||
`Score` INT NOT NULL,
|
|
||||||
`Difficulty` VARCHAR(20) NOT NULL DEFAULT 'NORMAL',
|
|
||||||
`SessionMetadataJson` TEXT NULL,
|
|
||||||
`CreatedAt` DATETIME(6) NOT NULL,
|
|
||||||
`UpdatedAt` DATETIME(6) NULL,
|
|
||||||
PRIMARY KEY (`Id`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
||||||
|
|
||||||
-- 6. Tabla de Contacto y Solicitudes
|
|
||||||
CREATE TABLE IF NOT EXISTS `ContactInquiries` (
|
|
||||||
`Id` VARCHAR(36) NOT NULL,
|
|
||||||
`FullName` VARCHAR(100) NOT NULL,
|
|
||||||
`Email` VARCHAR(120) NOT NULL,
|
|
||||||
`Phone` VARCHAR(30) NULL,
|
|
||||||
`ServiceType` VARCHAR(80) NOT NULL,
|
|
||||||
`Details` TEXT NOT NULL,
|
|
||||||
`Status` INT NOT NULL DEFAULT 0,
|
|
||||||
`CreatedAt` DATETIME(6) NOT NULL,
|
|
||||||
`UpdatedAt` DATETIME(6) NULL,
|
|
||||||
PRIMARY KEY (`Id`)
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
||||||
|
|
||||||
-- -----------------------------------------------------------------------------
|
|
||||||
-- Datos Iniciales Semilla (Seeds de Producción)
|
|
||||||
-- -----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
INSERT IGNORE INTO `Skills` (`Id`, `Name`, `Category`, `ProficiencyPercentage`, `IsFeatured`, `CreatedAt`) VALUES
|
|
||||||
('skill-dotnet', '.NET 8 / .NET 9 Clean Architecture', 0, 95, 1, UTC_TIMESTAMP()),
|
|
||||||
('skill-csharp', 'C# Moderno (CQRS, MediatR, EF Core)', 0, 95, 1, UTC_TIMESTAMP()),
|
|
||||||
('skill-angular', 'Angular 20 Standalone & Signals', 1, 92, 1, UTC_TIMESTAMP()),
|
|
||||||
('skill-mysql', 'MySQL / PostgreSQL / Pomelo', 2, 88, 1, UTC_TIMESTAMP()),
|
|
||||||
('skill-docker', 'Docker Multi-Stage & Linux ARM64', 3, 90, 1, UTC_TIMESTAMP()),
|
|
||||||
('skill-n8n', 'n8n Workflow Automation & AI Agents', 4, 92, 1, UTC_TIMESTAMP());
|
|
||||||
|
|
||||||
INSERT IGNORE INTO `Projects` (`Id`, `Title`, `Slug`, `Summary`, `Description`, `ArchitectureOverview`, `IsFeatured`, `OrderPriority`, `CreatedAt`) VALUES
|
|
||||||
('proj-portfolio', 'High-Impact Full-Stack Portfolio', 'high-impact-portfolio',
|
|
||||||
'Vitrina técnica de alto impacto con Clean Architecture en .NET 8/9, Signals en Angular 20, monitor Retro CRT y automatización con n8n.',
|
|
||||||
'Portafolio interactivo desarrollado desde cero para demostrar maestría en ingeniería de software, observabilidad en tiempo real y micro-interacciones de 60 FPS.',
|
|
||||||
'Clean Architecture (.NET Domain, Application con CQRS, Infrastructure Pomelo MySQL, WebApi RFC 7807) + Angular 20 Signals Hexagonal.',
|
|
||||||
1, 1, UTC_TIMESTAMP());
|
|
||||||
|
|
||||||
INSERT IGNORE INTO `GameScores` (`Id`, `GameCode`, `PlayerTag`, `Score`, `Difficulty`, `CreatedAt`) VALUES
|
|
||||||
('score-1', 'MINESWEEPER', 'ZEN', 42, 'NORMAL', UTC_TIMESTAMP()),
|
|
||||||
('score-2', 'MINESWEEPER', 'NEO', 68, 'NORMAL', UTC_TIMESTAMP()),
|
|
||||||
('score-3', 'MINESWEEPER', 'BRY', 95, 'NORMAL', UTC_TIMESTAMP());
|
|
||||||
|
|
||||||
INSERT IGNORE INTO `InteractiveMessages` (`Id`, `SenderName`, `SenderContact`, `Message`, `Origin`, `IsApproved`, `CreatedAt`) VALUES
|
|
||||||
('msg-1', 'Kenji Sato', 'Tokio, Japón', 'Excelente combinación de arquitectura limpia y estética Zen con retro monitor.', 1, 1, UTC_TIMESTAMP()),
|
|
||||||
('msg-2', 'Sophia Lindqvist', 'Estocolmo, Suecia', 'El packet tracer visual en vivo demuestra un dominio real de redes y backend.', 0, 1, UTC_TIMESTAMP());
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
**/.git
|
|
||||||
**/.vs
|
|
||||||
**/.vscode
|
|
||||||
**/bin
|
|
||||||
**/obj
|
|
||||||
**/appsettings.json
|
|
||||||
**/appsettings.Development.json
|
|
||||||
**/*.user
|
|
||||||
**/*.suo
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
<Project>
|
|
||||||
<PropertyGroup>
|
|
||||||
<RollForward>LatestMajor</RollForward>
|
|
||||||
</PropertyGroup>
|
|
||||||
</Project>
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
# ==============================================================================
|
|
||||||
# Dockerfile Multi-Stage: Backend .NET 8/9 Clean Architecture (ARM64 / x86_64)
|
|
||||||
# ==============================================================================
|
|
||||||
|
|
||||||
# Stage 1: Build & Publish
|
|
||||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
|
||||||
WORKDIR /src
|
|
||||||
|
|
||||||
# Copiar definiciones de solución y proyectos para aprovechar caché de Docker
|
|
||||||
COPY ["Directory.Build.props", "./"]
|
|
||||||
COPY ["src/Portfolio.Domain/Portfolio.Domain.csproj", "src/Portfolio.Domain/"]
|
|
||||||
COPY ["src/Portfolio.Application/Portfolio.Application.csproj", "src/Portfolio.Application/"]
|
|
||||||
COPY ["src/Portfolio.Infrastructure/Portfolio.Infrastructure.csproj", "src/Portfolio.Infrastructure/"]
|
|
||||||
COPY ["src/Portfolio.WebApi/Portfolio.WebApi.csproj", "src/Portfolio.WebApi/"]
|
|
||||||
|
|
||||||
RUN dotnet restore "src/Portfolio.WebApi/Portfolio.WebApi.csproj"
|
|
||||||
|
|
||||||
# Copiar código fuente y publicar artefactos optimizados
|
|
||||||
COPY ["src/", "src/"]
|
|
||||||
WORKDIR "/src/src/Portfolio.WebApi"
|
|
||||||
RUN dotnet publish "Portfolio.WebApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------------------
|
|
||||||
# Stage 2: Runtime Production Container
|
|
||||||
# ------------------------------------------------------------------------------
|
|
||||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
# Puerto no-root estándar de .NET 8/9
|
|
||||||
EXPOSE 8080
|
|
||||||
ENV ASPNETCORE_URLS=http://+:8080 \
|
|
||||||
ASPNETCORE_ENVIRONMENT=Production \
|
|
||||||
DOTNET_RUNNING_IN_CONTAINER=true
|
|
||||||
|
|
||||||
COPY --from=build /app/publish .
|
|
||||||
|
|
||||||
# Usuario con privilegios mínimos (UID predeterminado de Microsoft en .NET 8)
|
|
||||||
USER $APP_UID
|
|
||||||
|
|
||||||
ENTRYPOINT ["dotnet", "Portfolio.WebApi.dll"]
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
|
||||||
# Visual Studio Version 17
|
|
||||||
VisualStudioVersion = 17.0.31903.59
|
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.Domain", "src\Portfolio.Domain\Portfolio.Domain.csproj", "{36CD767F-7762-4EDF-B71E-94A78B020FE0}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.Application", "src\Portfolio.Application\Portfolio.Application.csproj", "{A279BB0E-7D67-4BCB-81FC-F487737A568C}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.Infrastructure", "src\Portfolio.Infrastructure\Portfolio.Infrastructure.csproj", "{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.WebApi", "src\Portfolio.WebApi\Portfolio.WebApi.csproj", "{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}"
|
|
||||||
EndProject
|
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{E7DB5FDA-B947-4EC2-9868-421E8E4FCCD6}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.UnitTests", "tests\Portfolio.UnitTests\Portfolio.UnitTests.csproj", "{EF9CB490-2460-42FF-A58D-616191B87DAC}"
|
|
||||||
EndProject
|
|
||||||
Global
|
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
|
||||||
Debug|Any CPU = Debug|Any CPU
|
|
||||||
Release|Any CPU = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
|
||||||
HideSolutionNode = FALSE
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
|
||||||
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(NestedProjects) = preSolution
|
|
||||||
{36CD767F-7762-4EDF-B71E-94A78B020FE0} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
|
|
||||||
{A279BB0E-7D67-4BCB-81FC-F487737A568C} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
|
|
||||||
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
|
|
||||||
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
|
|
||||||
{EF9CB490-2460-42FF-A58D-616191B87DAC} = {E7DB5FDA-B947-4EC2-9868-421E8E4FCCD6}
|
|
||||||
EndGlobalSection
|
|
||||||
EndGlobal
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
using FluentValidation;
|
|
||||||
using MediatR;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Common.Behaviors;
|
|
||||||
|
|
||||||
public sealed class ValidationBehavior<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
|
|
||||||
: IPipelineBehavior<TRequest, TResponse>
|
|
||||||
where TRequest : notnull
|
|
||||||
{
|
|
||||||
public async Task<TResponse> Handle(
|
|
||||||
TRequest request,
|
|
||||||
RequestHandlerDelegate<TResponse> next,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
if (!validators.Any())
|
|
||||||
{
|
|
||||||
return await next();
|
|
||||||
}
|
|
||||||
|
|
||||||
var context = new ValidationContext<TRequest>(request);
|
|
||||||
var validationResults = await Task.WhenAll(
|
|
||||||
validators.Select(v => v.ValidateAsync(context, cancellationToken)));
|
|
||||||
|
|
||||||
var failures = validationResults
|
|
||||||
.SelectMany(r => r.Errors)
|
|
||||||
.Where(f => f is not null)
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
if (failures.Count != 0)
|
|
||||||
{
|
|
||||||
throw new ValidationException(failures);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await next();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Common.Interfaces;
|
|
||||||
|
|
||||||
public interface IJwtTokenGenerator
|
|
||||||
{
|
|
||||||
string GenerateAccessToken(User user);
|
|
||||||
string GenerateRefreshToken();
|
|
||||||
}
|
|
||||||
|
|
||||||
public interface IPasswordHasher
|
|
||||||
{
|
|
||||||
string Hash(string password);
|
|
||||||
bool Verify(string password, string passwordHash);
|
|
||||||
}
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
using System.Reflection;
|
|
||||||
using FluentValidation;
|
|
||||||
using MediatR;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Portfolio.Application.Common.Behaviors;
|
|
||||||
|
|
||||||
namespace Portfolio.Application;
|
|
||||||
|
|
||||||
public static class DependencyInjection
|
|
||||||
{
|
|
||||||
public static IServiceCollection AddApplication(this IServiceCollection services)
|
|
||||||
{
|
|
||||||
var assembly = Assembly.GetExecutingAssembly();
|
|
||||||
|
|
||||||
services.AddMediatR(cfg =>
|
|
||||||
{
|
|
||||||
cfg.RegisterServicesFromAssembly(assembly);
|
|
||||||
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
|
|
||||||
});
|
|
||||||
|
|
||||||
services.AddValidatorsFromAssembly(assembly);
|
|
||||||
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Portfolio.Application.Features.Guestbook.DTOs;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Guestbook.Commands;
|
|
||||||
|
|
||||||
public sealed record CreateGuestbookMessageCommand(
|
|
||||||
string SenderName,
|
|
||||||
string Message,
|
|
||||||
MessageOrigin Origin = MessageOrigin.WebForm,
|
|
||||||
string? SenderContact = null
|
|
||||||
) : IRequest<GuestbookMessageResponseDto>;
|
|
||||||
|
|
||||||
public sealed class CreateGuestbookMessageCommandHandler(IInteractiveMessageRepository messageRepository)
|
|
||||||
: IRequestHandler<CreateGuestbookMessageCommand, GuestbookMessageResponseDto>
|
|
||||||
{
|
|
||||||
public async Task<GuestbookMessageResponseDto> Handle(CreateGuestbookMessageCommand request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var message = InteractiveMessage.Create(
|
|
||||||
request.SenderName,
|
|
||||||
request.Message,
|
|
||||||
request.Origin,
|
|
||||||
request.SenderContact
|
|
||||||
);
|
|
||||||
|
|
||||||
await messageRepository.AddAsync(message, cancellationToken);
|
|
||||||
await messageRepository.SaveChangesAsync(cancellationToken);
|
|
||||||
|
|
||||||
return new GuestbookMessageResponseDto(
|
|
||||||
message.Id,
|
|
||||||
message.SenderName,
|
|
||||||
message.Message,
|
|
||||||
message.Origin,
|
|
||||||
message.CreatedAtUtc
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,18 +0,0 @@
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Guestbook.DTOs;
|
|
||||||
|
|
||||||
public sealed record GuestbookMessageResponseDto(
|
|
||||||
Guid Id,
|
|
||||||
string SenderName,
|
|
||||||
string Message,
|
|
||||||
MessageOrigin Origin,
|
|
||||||
DateTime CreatedAtUtc
|
|
||||||
);
|
|
||||||
|
|
||||||
public sealed record CreateGuestbookMessageRequestDto(
|
|
||||||
string SenderName,
|
|
||||||
string Message,
|
|
||||||
MessageOrigin Origin = MessageOrigin.WebForm,
|
|
||||||
string? SenderContact = null
|
|
||||||
);
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Portfolio.Application.Features.Guestbook.DTOs;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Guestbook.Queries;
|
|
||||||
|
|
||||||
public sealed record GetGuestbookMessagesQuery(int Limit = 50) : IRequest<IReadOnlyList<GuestbookMessageResponseDto>>;
|
|
||||||
|
|
||||||
public sealed class GetGuestbookMessagesQueryHandler(IInteractiveMessageRepository messageRepository)
|
|
||||||
: IRequestHandler<GetGuestbookMessagesQuery, IReadOnlyList<GuestbookMessageResponseDto>>
|
|
||||||
{
|
|
||||||
public async Task<IReadOnlyList<GuestbookMessageResponseDto>> Handle(GetGuestbookMessagesQuery request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var messages = await messageRepository.GetRecentApprovedAsync(request.Limit, cancellationToken);
|
|
||||||
|
|
||||||
return messages.Select(m => new GuestbookMessageResponseDto(
|
|
||||||
m.Id,
|
|
||||||
m.SenderName,
|
|
||||||
m.Message,
|
|
||||||
m.Origin,
|
|
||||||
m.CreatedAtUtc
|
|
||||||
)).ToList();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
using FluentValidation;
|
|
||||||
using Portfolio.Application.Features.Guestbook.Commands;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Guestbook.Validators;
|
|
||||||
|
|
||||||
public sealed class CreateGuestbookMessageCommandValidator : AbstractValidator<CreateGuestbookMessageCommand>
|
|
||||||
{
|
|
||||||
public CreateGuestbookMessageCommandValidator()
|
|
||||||
{
|
|
||||||
RuleFor(x => x.SenderName)
|
|
||||||
.NotEmpty().WithMessage("El nombre o alias del remitente es obligatorio.")
|
|
||||||
.MaximumLength(60).WithMessage("El nombre no puede exceder 60 caracteres.");
|
|
||||||
|
|
||||||
RuleFor(x => x.Message)
|
|
||||||
.NotEmpty().WithMessage("El mensaje no puede estar vacío.")
|
|
||||||
.MinimumLength(3).WithMessage("El mensaje debe contener al menos 3 caracteres.")
|
|
||||||
.MaximumLength(500).WithMessage("El mensaje no puede exceder 500 caracteres.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Portfolio.Application.Features.Leaderboard.DTOs;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Leaderboard.Commands;
|
|
||||||
|
|
||||||
public sealed record SubmitGameScoreCommand(
|
|
||||||
string PlayerName,
|
|
||||||
string GameName,
|
|
||||||
int Score,
|
|
||||||
int DurationSeconds,
|
|
||||||
string? CountryCode = null
|
|
||||||
) : IRequest<GameScoreResponseDto>;
|
|
||||||
|
|
||||||
public sealed class SubmitGameScoreCommandHandler(IGameScoreRepository scoreRepository)
|
|
||||||
: IRequestHandler<SubmitGameScoreCommand, GameScoreResponseDto>
|
|
||||||
{
|
|
||||||
public async Task<GameScoreResponseDto> Handle(SubmitGameScoreCommand request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var gameScore = GameScore.Create(
|
|
||||||
request.PlayerName,
|
|
||||||
request.GameName,
|
|
||||||
request.Score,
|
|
||||||
request.DurationSeconds,
|
|
||||||
request.CountryCode
|
|
||||||
);
|
|
||||||
|
|
||||||
await scoreRepository.AddAsync(gameScore, cancellationToken);
|
|
||||||
await scoreRepository.SaveChangesAsync(cancellationToken);
|
|
||||||
|
|
||||||
return new GameScoreResponseDto(
|
|
||||||
gameScore.Id,
|
|
||||||
gameScore.PlayerName,
|
|
||||||
gameScore.GameName,
|
|
||||||
gameScore.Score,
|
|
||||||
gameScore.DurationSeconds,
|
|
||||||
gameScore.CountryCode,
|
|
||||||
gameScore.CreatedAtUtc
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
namespace Portfolio.Application.Features.Leaderboard.DTOs;
|
|
||||||
|
|
||||||
public sealed record GameScoreResponseDto(
|
|
||||||
Guid Id,
|
|
||||||
string PlayerName,
|
|
||||||
string GameName,
|
|
||||||
int Score,
|
|
||||||
int DurationSeconds,
|
|
||||||
string? CountryCode,
|
|
||||||
DateTime CreatedAtUtc
|
|
||||||
);
|
|
||||||
|
|
||||||
public sealed record SubmitGameScoreRequestDto(
|
|
||||||
string PlayerName,
|
|
||||||
string GameName,
|
|
||||||
int Score,
|
|
||||||
int DurationSeconds,
|
|
||||||
string? CountryCode = null
|
|
||||||
);
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Portfolio.Application.Features.Leaderboard.DTOs;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Leaderboard.Queries;
|
|
||||||
|
|
||||||
public sealed record GetLeaderboardQuery(string GameName = "Minesweeper", int Limit = 10)
|
|
||||||
: IRequest<IReadOnlyList<GameScoreResponseDto>>;
|
|
||||||
|
|
||||||
public sealed class GetLeaderboardQueryHandler(IGameScoreRepository scoreRepository)
|
|
||||||
: IRequestHandler<GetLeaderboardQuery, IReadOnlyList<GameScoreResponseDto>>
|
|
||||||
{
|
|
||||||
public async Task<IReadOnlyList<GameScoreResponseDto>> Handle(GetLeaderboardQuery request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var scores = await scoreRepository.GetTopScoresAsync(request.GameName, request.Limit, cancellationToken);
|
|
||||||
|
|
||||||
return scores.Select(s => new GameScoreResponseDto(
|
|
||||||
s.Id,
|
|
||||||
s.PlayerName,
|
|
||||||
s.GameName,
|
|
||||||
s.Score,
|
|
||||||
s.DurationSeconds,
|
|
||||||
s.CountryCode,
|
|
||||||
s.CreatedAtUtc
|
|
||||||
)).ToList();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
using FluentValidation;
|
|
||||||
using Portfolio.Application.Features.Leaderboard.Commands;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Leaderboard.Validators;
|
|
||||||
|
|
||||||
public sealed class SubmitGameScoreCommandValidator : AbstractValidator<SubmitGameScoreCommand>
|
|
||||||
{
|
|
||||||
public SubmitGameScoreCommandValidator()
|
|
||||||
{
|
|
||||||
RuleFor(x => x.PlayerName)
|
|
||||||
.NotEmpty().WithMessage("El nombre del jugador es obligatorio.")
|
|
||||||
.MaximumLength(30).WithMessage("El nombre no puede exceder 30 caracteres.");
|
|
||||||
|
|
||||||
RuleFor(x => x.GameName)
|
|
||||||
.NotEmpty().WithMessage("El nombre del juego es obligatorio.")
|
|
||||||
.MaximumLength(30);
|
|
||||||
|
|
||||||
RuleFor(x => x.Score)
|
|
||||||
.GreaterThanOrEqualTo(0).WithMessage("La puntuación no puede ser negativa.");
|
|
||||||
|
|
||||||
RuleFor(x => x.DurationSeconds)
|
|
||||||
.GreaterThanOrEqualTo(0).WithMessage("La duración no puede ser negativa.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
namespace Portfolio.Application.Features.Projects.DTOs;
|
|
||||||
|
|
||||||
public sealed record ProjectResponseDto(
|
|
||||||
Guid Id,
|
|
||||||
string Slug,
|
|
||||||
string Title,
|
|
||||||
string ShortDescription,
|
|
||||||
string FullDescription,
|
|
||||||
string RepositoryUrl,
|
|
||||||
string? LiveDemoUrl,
|
|
||||||
string? ThumbnailUrl,
|
|
||||||
bool IsFeatured,
|
|
||||||
ushort DisplayOrder,
|
|
||||||
IReadOnlyList<string> Skills
|
|
||||||
);
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Portfolio.Application.Features.Projects.DTOs;
|
|
||||||
using Portfolio.Domain.Exceptions;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Projects.Queries;
|
|
||||||
|
|
||||||
public sealed record GetProjectBySlugQuery(string Slug) : IRequest<ProjectResponseDto>;
|
|
||||||
|
|
||||||
public sealed class GetProjectBySlugQueryHandler(IProjectRepository projectRepository)
|
|
||||||
: IRequestHandler<GetProjectBySlugQuery, ProjectResponseDto>
|
|
||||||
{
|
|
||||||
public async Task<ProjectResponseDto> Handle(GetProjectBySlugQuery request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var p = await projectRepository.GetBySlugAsync(request.Slug, cancellationToken)
|
|
||||||
?? throw new NotFoundException("Project", request.Slug);
|
|
||||||
|
|
||||||
return new ProjectResponseDto(
|
|
||||||
p.Id,
|
|
||||||
p.Slug,
|
|
||||||
p.Title,
|
|
||||||
p.ShortDescription,
|
|
||||||
p.FullDescription,
|
|
||||||
p.RepositoryUrl,
|
|
||||||
p.LiveDemoUrl,
|
|
||||||
p.ThumbnailUrl,
|
|
||||||
p.IsFeatured,
|
|
||||||
p.DisplayOrder,
|
|
||||||
p.ProjectSkills.Select(ps => ps.Skill.Name).ToList()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Portfolio.Application.Features.Projects.DTOs;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Projects.Queries;
|
|
||||||
|
|
||||||
public sealed record GetProjectsQuery(bool FeaturedOnly = false) : IRequest<IReadOnlyList<ProjectResponseDto>>;
|
|
||||||
|
|
||||||
public sealed class GetProjectsQueryHandler(IProjectRepository projectRepository)
|
|
||||||
: IRequestHandler<GetProjectsQuery, IReadOnlyList<ProjectResponseDto>>
|
|
||||||
{
|
|
||||||
public async Task<IReadOnlyList<ProjectResponseDto>> Handle(GetProjectsQuery request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var projects = await projectRepository.GetAllAsync(request.FeaturedOnly, cancellationToken);
|
|
||||||
|
|
||||||
return projects.Select(p => new ProjectResponseDto(
|
|
||||||
p.Id,
|
|
||||||
p.Slug,
|
|
||||||
p.Title,
|
|
||||||
p.ShortDescription,
|
|
||||||
p.FullDescription,
|
|
||||||
p.RepositoryUrl,
|
|
||||||
p.LiveDemoUrl,
|
|
||||||
p.ThumbnailUrl,
|
|
||||||
p.IsFeatured,
|
|
||||||
p.DisplayOrder,
|
|
||||||
p.ProjectSkills.Select(ps => ps.Skill.Name).ToList()
|
|
||||||
)).ToList();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Skills.DTOs;
|
|
||||||
|
|
||||||
public sealed record SkillResponseDto(
|
|
||||||
Guid Id,
|
|
||||||
string Name,
|
|
||||||
SkillCategory Category,
|
|
||||||
string? IconSlug,
|
|
||||||
byte ProficiencyPercentage,
|
|
||||||
ushort DisplayOrder,
|
|
||||||
bool IsFeatured
|
|
||||||
);
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Portfolio.Application.Features.Skills.DTOs;
|
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Skills.Queries;
|
|
||||||
|
|
||||||
public sealed record GetSkillsQuery(SkillCategory? Category = null) : IRequest<IReadOnlyList<SkillResponseDto>>;
|
|
||||||
|
|
||||||
public sealed class GetSkillsQueryHandler(ISkillRepository skillRepository)
|
|
||||||
: IRequestHandler<GetSkillsQuery, IReadOnlyList<SkillResponseDto>>
|
|
||||||
{
|
|
||||||
public async Task<IReadOnlyList<SkillResponseDto>> Handle(GetSkillsQuery request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var skills = await skillRepository.GetAllAsync(request.Category, cancellationToken);
|
|
||||||
|
|
||||||
return skills.Select(s => new SkillResponseDto(
|
|
||||||
s.Id,
|
|
||||||
s.Name,
|
|
||||||
s.Category,
|
|
||||||
s.IconSlug,
|
|
||||||
s.ProficiencyPercentage,
|
|
||||||
s.DisplayOrder,
|
|
||||||
s.IsFeatured
|
|
||||||
)).ToList();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
namespace Portfolio.Application.Features.Telemetry.DTOs;
|
|
||||||
|
|
||||||
public sealed record ServerTelemetryDto(
|
|
||||||
string Status,
|
|
||||||
string Region,
|
|
||||||
string Provider,
|
|
||||||
string Architecture,
|
|
||||||
string RuntimeVersion,
|
|
||||||
TimeSpan Uptime,
|
|
||||||
double ProcessMemoryMb,
|
|
||||||
int ActiveThreads,
|
|
||||||
DateTime ServerTimeUtc
|
|
||||||
);
|
|
||||||
|
|
||||||
public sealed record PingResponseDto(
|
|
||||||
string Message,
|
|
||||||
long LatencyMs,
|
|
||||||
DateTime TimestampUtc
|
|
||||||
);
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
using System.Diagnostics;
|
|
||||||
using System.Runtime.InteropServices;
|
|
||||||
using MediatR;
|
|
||||||
using Portfolio.Application.Features.Telemetry.DTOs;
|
|
||||||
|
|
||||||
namespace Portfolio.Application.Features.Telemetry.Queries;
|
|
||||||
|
|
||||||
public sealed record GetServerTelemetryQuery : IRequest<ServerTelemetryDto>;
|
|
||||||
|
|
||||||
public sealed class GetServerTelemetryQueryHandler : IRequestHandler<GetServerTelemetryQuery, ServerTelemetryDto>
|
|
||||||
{
|
|
||||||
private static readonly DateTime StartTime = DateTime.UtcNow;
|
|
||||||
|
|
||||||
public Task<ServerTelemetryDto> Handle(GetServerTelemetryQuery request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var process = Process.GetCurrentProcess();
|
|
||||||
var memoryMb = Math.Round((double)process.WorkingSet64 / (1024 * 1024), 2);
|
|
||||||
var uptime = DateTime.UtcNow - StartTime;
|
|
||||||
|
|
||||||
var dto = new ServerTelemetryDto(
|
|
||||||
Status: "OPERATIONAL",
|
|
||||||
Region: "us-ashburn-1",
|
|
||||||
Provider: "Oracle Cloud Infrastructure (OCI)",
|
|
||||||
Architecture: $"{RuntimeInformation.OSDescription} ({RuntimeInformation.ProcessArchitecture})",
|
|
||||||
RuntimeVersion: RuntimeInformation.FrameworkDescription,
|
|
||||||
Uptime: uptime,
|
|
||||||
ProcessMemoryMb: memoryMb,
|
|
||||||
ActiveThreads: process.Threads.Count,
|
|
||||||
ServerTimeUtc: DateTime.UtcNow
|
|
||||||
);
|
|
||||||
|
|
||||||
return Task.FromResult(dto);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,18 +0,0 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\Portfolio.Domain\Portfolio.Domain.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
|
|
||||||
<PackageReference Include="MediatR" Version="14.2.0" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
namespace Portfolio.Domain.Common;
|
|
||||||
|
|
||||||
public abstract class BaseEntity
|
|
||||||
{
|
|
||||||
public Guid Id { get; protected set; } = Guid.NewGuid();
|
|
||||||
public DateTime CreatedAtUtc { get; protected set; } = DateTime.UtcNow;
|
|
||||||
}
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
||||||
using Portfolio.Domain.Common;
|
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
public sealed class ContactInquiry : BaseEntity
|
|
||||||
{
|
|
||||||
public string FullNameOrCompany { get; private set; } = string.Empty;
|
|
||||||
public string Email { get; private set; } = string.Empty;
|
|
||||||
public string? Phone { get; private set; }
|
|
||||||
public string ServiceType { get; private set; } = "General";
|
|
||||||
public string ProjectDetails { get; private set; } = string.Empty;
|
|
||||||
public InquiryStatus Status { get; private set; } = InquiryStatus.New;
|
|
||||||
public string? IpAddress { get; private set; }
|
|
||||||
public DateTime? RepliedAtUtc { get; private set; }
|
|
||||||
|
|
||||||
private ContactInquiry() { }
|
|
||||||
|
|
||||||
public static ContactInquiry Create(
|
|
||||||
string fullNameOrCompany,
|
|
||||||
string email,
|
|
||||||
string projectDetails,
|
|
||||||
string serviceType = "General",
|
|
||||||
string? phone = null,
|
|
||||||
string? ipAddress = null)
|
|
||||||
{
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(fullNameOrCompany);
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(email);
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(projectDetails);
|
|
||||||
|
|
||||||
return new ContactInquiry
|
|
||||||
{
|
|
||||||
FullNameOrCompany = fullNameOrCompany.Trim(),
|
|
||||||
Email = email.Trim().ToLowerInvariant(),
|
|
||||||
ProjectDetails = projectDetails.Trim(),
|
|
||||||
ServiceType = serviceType.Trim(),
|
|
||||||
Phone = phone?.Trim(),
|
|
||||||
IpAddress = ipAddress,
|
|
||||||
Status = InquiryStatus.New
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
using Portfolio.Domain.Common;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
public sealed class GameScore : BaseEntity
|
|
||||||
{
|
|
||||||
public string PlayerName { get; private set; } = string.Empty;
|
|
||||||
public string GameName { get; private set; } = "Minesweeper";
|
|
||||||
public int Score { get; private set; }
|
|
||||||
public int DurationSeconds { get; private set; }
|
|
||||||
public string? CountryCode { get; private set; }
|
|
||||||
|
|
||||||
private GameScore() { }
|
|
||||||
|
|
||||||
public static GameScore Create(
|
|
||||||
string playerName,
|
|
||||||
string gameName,
|
|
||||||
int score,
|
|
||||||
int durationSeconds,
|
|
||||||
string? countryCode = null)
|
|
||||||
{
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(playerName);
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(gameName);
|
|
||||||
|
|
||||||
return new GameScore
|
|
||||||
{
|
|
||||||
PlayerName = playerName.Trim(),
|
|
||||||
GameName = gameName.Trim().ToLowerInvariant(),
|
|
||||||
Score = score,
|
|
||||||
DurationSeconds = durationSeconds,
|
|
||||||
CountryCode = countryCode?.Trim().ToUpperInvariant()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
using Portfolio.Domain.Common;
|
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
public sealed class InteractiveMessage : BaseEntity
|
|
||||||
{
|
|
||||||
public string SenderName { get; private set; } = string.Empty;
|
|
||||||
public string? SenderContact { get; private set; }
|
|
||||||
public string Message { get; private set; } = string.Empty;
|
|
||||||
public MessageOrigin Origin { get; private set; }
|
|
||||||
public bool IsApproved { get; private set; } = true;
|
|
||||||
|
|
||||||
private InteractiveMessage() { }
|
|
||||||
|
|
||||||
public static InteractiveMessage Create(
|
|
||||||
string senderName,
|
|
||||||
string message,
|
|
||||||
MessageOrigin origin = MessageOrigin.Terminal,
|
|
||||||
string? senderContact = null)
|
|
||||||
{
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(senderName);
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(message);
|
|
||||||
|
|
||||||
return new InteractiveMessage
|
|
||||||
{
|
|
||||||
SenderName = senderName.Trim(),
|
|
||||||
Message = message.Trim(),
|
|
||||||
Origin = origin,
|
|
||||||
SenderContact = senderContact?.Trim(),
|
|
||||||
IsApproved = true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,49 +0,0 @@
|
||||||
using Portfolio.Domain.Common;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
public sealed class Project : BaseEntity
|
|
||||||
{
|
|
||||||
public string Slug { get; private set; } = string.Empty;
|
|
||||||
public string Title { get; private set; } = string.Empty;
|
|
||||||
public string ShortDescription { get; private set; } = string.Empty;
|
|
||||||
public string FullDescription { get; private set; } = string.Empty;
|
|
||||||
public string RepositoryUrl { get; private set; } = string.Empty;
|
|
||||||
public string? LiveDemoUrl { get; private set; }
|
|
||||||
public string? ThumbnailUrl { get; private set; }
|
|
||||||
public bool IsFeatured { get; private set; }
|
|
||||||
public ushort DisplayOrder { get; private set; }
|
|
||||||
public DateTime? UpdatedAtUtc { get; private set; }
|
|
||||||
|
|
||||||
public ICollection<ProjectSkill> ProjectSkills { get; private set; } = [];
|
|
||||||
|
|
||||||
private Project() { }
|
|
||||||
|
|
||||||
public static Project Create(
|
|
||||||
string slug,
|
|
||||||
string title,
|
|
||||||
string shortDescription,
|
|
||||||
string fullDescription,
|
|
||||||
string repositoryUrl,
|
|
||||||
string? liveDemoUrl = null,
|
|
||||||
string? thumbnailUrl = null,
|
|
||||||
bool isFeatured = false,
|
|
||||||
ushort displayOrder = 0)
|
|
||||||
{
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(slug);
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(title);
|
|
||||||
|
|
||||||
return new Project
|
|
||||||
{
|
|
||||||
Slug = slug.Trim().ToLowerInvariant(),
|
|
||||||
Title = title.Trim(),
|
|
||||||
ShortDescription = shortDescription.Trim(),
|
|
||||||
FullDescription = fullDescription.Trim(),
|
|
||||||
RepositoryUrl = repositoryUrl.Trim(),
|
|
||||||
LiveDemoUrl = liveDemoUrl?.Trim(),
|
|
||||||
ThumbnailUrl = thumbnailUrl?.Trim(),
|
|
||||||
IsFeatured = isFeatured,
|
|
||||||
DisplayOrder = displayOrder
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
namespace Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
public sealed class ProjectSkill
|
|
||||||
{
|
|
||||||
public Guid ProjectId { get; set; }
|
|
||||||
public Project Project { get; set; } = null!;
|
|
||||||
|
|
||||||
public Guid SkillId { get; set; }
|
|
||||||
public Skill Skill { get; set; } = null!;
|
|
||||||
}
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
using Portfolio.Domain.Common;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
public sealed class RefreshToken : BaseEntity
|
|
||||||
{
|
|
||||||
public Guid UserId { get; private set; }
|
|
||||||
public User User { get; private set; } = null!;
|
|
||||||
|
|
||||||
public string TokenHash { get; private set; } = string.Empty;
|
|
||||||
public DateTime ExpiresAtUtc { get; private set; }
|
|
||||||
public bool IsRevoked { get; private set; }
|
|
||||||
public string? ReplacedByToken { get; private set; }
|
|
||||||
|
|
||||||
public bool IsActive => !IsRevoked && DateTime.UtcNow < ExpiresAtUtc;
|
|
||||||
|
|
||||||
private RefreshToken() { }
|
|
||||||
|
|
||||||
public static RefreshToken Create(Guid userId, string tokenHash, DateTime expiresAtUtc)
|
|
||||||
{
|
|
||||||
return new RefreshToken
|
|
||||||
{
|
|
||||||
UserId = userId,
|
|
||||||
TokenHash = tokenHash,
|
|
||||||
ExpiresAtUtc = expiresAtUtc,
|
|
||||||
IsRevoked = false
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Revoke(string? replacedBy = null)
|
|
||||||
{
|
|
||||||
IsRevoked = true;
|
|
||||||
ReplacedByToken = replacedBy;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
using Portfolio.Domain.Common;
|
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
public sealed class Skill : BaseEntity
|
|
||||||
{
|
|
||||||
public string Name { get; private set; } = string.Empty;
|
|
||||||
public SkillCategory Category { get; private set; }
|
|
||||||
public string? IconSlug { get; private set; }
|
|
||||||
public byte ProficiencyPercentage { get; private set; }
|
|
||||||
public ushort DisplayOrder { get; private set; }
|
|
||||||
public bool IsFeatured { get; private set; }
|
|
||||||
|
|
||||||
public ICollection<ProjectSkill> ProjectSkills { get; private set; } = [];
|
|
||||||
|
|
||||||
private Skill() { }
|
|
||||||
|
|
||||||
public static Skill Create(
|
|
||||||
string name,
|
|
||||||
SkillCategory category,
|
|
||||||
string? iconSlug = null,
|
|
||||||
byte proficiency = 85,
|
|
||||||
ushort displayOrder = 0,
|
|
||||||
bool isFeatured = true)
|
|
||||||
{
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(name);
|
|
||||||
|
|
||||||
return new Skill
|
|
||||||
{
|
|
||||||
Name = name.Trim(),
|
|
||||||
Category = category,
|
|
||||||
IconSlug = iconSlug?.Trim(),
|
|
||||||
ProficiencyPercentage = Math.Min((byte)100, proficiency),
|
|
||||||
DisplayOrder = displayOrder,
|
|
||||||
IsFeatured = isFeatured
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
using Portfolio.Domain.Common;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
public sealed class User : BaseEntity
|
|
||||||
{
|
|
||||||
public string Username { get; private set; } = string.Empty;
|
|
||||||
public string Email { get; private set; } = string.Empty;
|
|
||||||
public string PasswordHash { get; private set; } = string.Empty;
|
|
||||||
public string Role { get; private set; } = "Admin";
|
|
||||||
public DateTime? UpdatedAtUtc { get; private set; }
|
|
||||||
|
|
||||||
public ICollection<RefreshToken> RefreshTokens { get; private set; } = [];
|
|
||||||
|
|
||||||
private User() { }
|
|
||||||
|
|
||||||
public static User Create(string username, string email, string passwordHash, string role = "Admin")
|
|
||||||
{
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(username);
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(email);
|
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(passwordHash);
|
|
||||||
|
|
||||||
return new User
|
|
||||||
{
|
|
||||||
Username = username.Trim(),
|
|
||||||
Email = email.Trim().ToLowerInvariant(),
|
|
||||||
PasswordHash = passwordHash,
|
|
||||||
Role = role
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
namespace Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
public enum InquiryStatus
|
|
||||||
{
|
|
||||||
New = 1,
|
|
||||||
Read = 2,
|
|
||||||
Replied = 3,
|
|
||||||
Archived = 4
|
|
||||||
}
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
namespace Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
public enum MessageOrigin
|
|
||||||
{
|
|
||||||
Terminal = 1,
|
|
||||||
WebForm = 2,
|
|
||||||
ApiTester = 3
|
|
||||||
}
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
namespace Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
public enum SkillCategory
|
|
||||||
{
|
|
||||||
Backend = 1,
|
|
||||||
Frontend = 2,
|
|
||||||
Database = 3,
|
|
||||||
DevOps = 4,
|
|
||||||
Architecture = 5
|
|
||||||
}
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
namespace Portfolio.Domain.Exceptions;
|
|
||||||
|
|
||||||
public class DomainException(string message) : Exception(message);
|
|
||||||
|
|
||||||
public class NotFoundException(string entityName, object key)
|
|
||||||
: DomainException($"Entity '{entityName}' with key ({key}) was not found.");
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
public interface IGameScoreRepository
|
|
||||||
{
|
|
||||||
Task<IReadOnlyList<GameScore>> GetTopScoresAsync(string gameName, int limit = 10, CancellationToken ct = default);
|
|
||||||
Task AddAsync(GameScore score, CancellationToken ct = default);
|
|
||||||
Task<int> SaveChangesAsync(CancellationToken ct = default);
|
|
||||||
}
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
public interface IInteractiveMessageRepository
|
|
||||||
{
|
|
||||||
Task<IReadOnlyList<InteractiveMessage>> GetRecentApprovedAsync(int limit = 50, CancellationToken ct = default);
|
|
||||||
Task AddAsync(InteractiveMessage message, CancellationToken ct = default);
|
|
||||||
Task<int> SaveChangesAsync(CancellationToken ct = default);
|
|
||||||
}
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
public interface IProjectRepository
|
|
||||||
{
|
|
||||||
Task<IReadOnlyList<Project>> GetAllAsync(bool featuredOnly = false, CancellationToken ct = default);
|
|
||||||
Task<Project?> GetBySlugAsync(string slug, CancellationToken ct = default);
|
|
||||||
Task<Project?> GetByIdAsync(Guid id, CancellationToken ct = default);
|
|
||||||
Task AddAsync(Project project, CancellationToken ct = default);
|
|
||||||
void Update(Project project);
|
|
||||||
void Delete(Project project);
|
|
||||||
Task<int> SaveChangesAsync(CancellationToken ct = default);
|
|
||||||
}
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
public interface ISkillRepository
|
|
||||||
{
|
|
||||||
Task<IReadOnlyList<Skill>> GetAllAsync(SkillCategory? category = null, CancellationToken ct = default);
|
|
||||||
Task<Skill?> GetByIdAsync(Guid id, CancellationToken ct = default);
|
|
||||||
Task AddAsync(Skill skill, CancellationToken ct = default);
|
|
||||||
Task<int> SaveChangesAsync(CancellationToken ct = default);
|
|
||||||
}
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Domain.Interfaces;
|
|
||||||
|
|
||||||
public interface IUserRepository
|
|
||||||
{
|
|
||||||
Task<User?> GetByUsernameOrEmailAsync(string identifier, CancellationToken ct = default);
|
|
||||||
Task<User?> GetByIdAsync(Guid id, CancellationToken ct = default);
|
|
||||||
Task AddRefreshTokenAsync(RefreshToken refreshToken, CancellationToken ct = default);
|
|
||||||
Task<RefreshToken?> GetRefreshTokenAsync(string tokenHash, CancellationToken ct = default);
|
|
||||||
Task<int> SaveChangesAsync(CancellationToken ct = default);
|
|
||||||
}
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Portfolio.Application.Common.Interfaces;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
using Portfolio.Infrastructure.Persistence.Context;
|
|
||||||
using Portfolio.Infrastructure.Persistence.Repositories;
|
|
||||||
using Portfolio.Infrastructure.Security;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure;
|
|
||||||
|
|
||||||
public static class DependencyInjection
|
|
||||||
{
|
|
||||||
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
|
|
||||||
{
|
|
||||||
var connectionString = configuration.GetConnectionString("DefaultConnection")
|
|
||||||
?? "Server=localhost;Port=3306;Database=portfolio_db;User=root;Password=;CharSet=utf8mb4;";
|
|
||||||
|
|
||||||
services.AddDbContext<PortfolioDbContext>(options =>
|
|
||||||
{
|
|
||||||
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), mysqlOptions =>
|
|
||||||
{
|
|
||||||
mysqlOptions.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(5), errorNumbersToAdd: null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
services.AddScoped<IProjectRepository, ProjectRepository>();
|
|
||||||
services.AddScoped<ISkillRepository, SkillRepository>();
|
|
||||||
services.AddScoped<IInteractiveMessageRepository, InteractiveMessageRepository>();
|
|
||||||
services.AddScoped<IGameScoreRepository, GameScoreRepository>();
|
|
||||||
services.AddScoped<IUserRepository, UserRepository>();
|
|
||||||
|
|
||||||
services.AddSingleton<IPasswordHasher, PasswordHasher>();
|
|
||||||
services.AddScoped<IJwtTokenGenerator, JwtTokenGenerator>();
|
|
||||||
|
|
||||||
return services;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Configurations;
|
|
||||||
|
|
||||||
public sealed class ContactInquiryConfiguration : IEntityTypeConfiguration<ContactInquiry>
|
|
||||||
{
|
|
||||||
public void Configure(EntityTypeBuilder<ContactInquiry> builder)
|
|
||||||
{
|
|
||||||
builder.ToTable("contact_inquiries");
|
|
||||||
|
|
||||||
builder.HasKey(c => c.Id);
|
|
||||||
builder.Property(c => c.Id).HasColumnName("id").HasMaxLength(36);
|
|
||||||
|
|
||||||
builder.Property(c => c.FullNameOrCompany).HasColumnName("full_name_or_company").HasMaxLength(100).IsRequired();
|
|
||||||
builder.Property(c => c.Email).HasColumnName("email").HasMaxLength(100).IsRequired();
|
|
||||||
builder.Property(c => c.Phone).HasColumnName("phone").HasMaxLength(30);
|
|
||||||
builder.Property(c => c.ServiceType).HasColumnName("service_type").HasMaxLength(50).IsRequired();
|
|
||||||
builder.Property(c => c.ProjectDetails).HasColumnName("project_details").HasColumnType("TEXT").IsRequired();
|
|
||||||
builder.Property(c => c.Status).HasColumnName("status").HasConversion<string>().HasMaxLength(20).IsRequired();
|
|
||||||
builder.Property(c => c.IpAddress).HasColumnName("ip_address").HasMaxLength(45);
|
|
||||||
builder.Property(c => c.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
|
|
||||||
builder.Property(c => c.RepliedAtUtc).HasColumnName("replied_at_utc");
|
|
||||||
|
|
||||||
builder.HasIndex(c => new { c.Status, c.CreatedAtUtc });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Configurations;
|
|
||||||
|
|
||||||
public sealed class GameScoreConfiguration : IEntityTypeConfiguration<GameScore>
|
|
||||||
{
|
|
||||||
public void Configure(EntityTypeBuilder<GameScore> builder)
|
|
||||||
{
|
|
||||||
builder.ToTable("game_scores");
|
|
||||||
|
|
||||||
builder.HasKey(g => g.Id);
|
|
||||||
builder.Property(g => g.Id).HasColumnName("id").HasMaxLength(36);
|
|
||||||
|
|
||||||
builder.Property(g => g.PlayerName).HasColumnName("player_name").HasMaxLength(30).IsRequired();
|
|
||||||
builder.Property(g => g.GameName).HasColumnName("game_name").HasMaxLength(30).IsRequired();
|
|
||||||
builder.Property(g => g.Score).HasColumnName("score").IsRequired();
|
|
||||||
builder.Property(g => g.DurationSeconds).HasColumnName("duration_seconds").IsRequired();
|
|
||||||
builder.Property(g => g.CountryCode).HasColumnName("country_code").HasMaxLength(5);
|
|
||||||
builder.Property(g => g.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
|
|
||||||
|
|
||||||
builder.HasIndex(g => new { g.GameName, g.Score });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Configurations;
|
|
||||||
|
|
||||||
public sealed class InteractiveMessageConfiguration : IEntityTypeConfiguration<InteractiveMessage>
|
|
||||||
{
|
|
||||||
public void Configure(EntityTypeBuilder<InteractiveMessage> builder)
|
|
||||||
{
|
|
||||||
builder.ToTable("interactive_messages");
|
|
||||||
|
|
||||||
builder.HasKey(m => m.Id);
|
|
||||||
builder.Property(m => m.Id).HasColumnName("id").HasMaxLength(36);
|
|
||||||
|
|
||||||
builder.Property(m => m.SenderName).HasColumnName("sender_name").HasMaxLength(60).IsRequired();
|
|
||||||
builder.Property(m => m.SenderContact).HasColumnName("sender_contact").HasMaxLength(100);
|
|
||||||
builder.Property(m => m.Message).HasColumnName("message").HasMaxLength(500).IsRequired();
|
|
||||||
builder.Property(m => m.Origin).HasColumnName("origin").HasConversion<string>().HasMaxLength(20).IsRequired();
|
|
||||||
builder.Property(m => m.IsApproved).HasColumnName("is_approved").IsRequired();
|
|
||||||
builder.Property(m => m.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
|
|
||||||
|
|
||||||
builder.HasIndex(m => new { m.IsApproved, m.CreatedAtUtc });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Configurations;
|
|
||||||
|
|
||||||
public sealed class ProjectConfiguration : IEntityTypeConfiguration<Project>
|
|
||||||
{
|
|
||||||
public void Configure(EntityTypeBuilder<Project> builder)
|
|
||||||
{
|
|
||||||
builder.ToTable("projects");
|
|
||||||
|
|
||||||
builder.HasKey(p => p.Id);
|
|
||||||
builder.Property(p => p.Id).HasColumnName("id").HasMaxLength(36);
|
|
||||||
|
|
||||||
builder.Property(p => p.Slug).HasColumnName("slug").HasMaxLength(100).IsRequired();
|
|
||||||
builder.HasIndex(p => p.Slug).IsUnique();
|
|
||||||
|
|
||||||
builder.Property(p => p.Title).HasColumnName("title").HasMaxLength(150).IsRequired();
|
|
||||||
builder.Property(p => p.ShortDescription).HasColumnName("short_description").HasMaxLength(255).IsRequired();
|
|
||||||
builder.Property(p => p.FullDescription).HasColumnName("full_description").HasColumnType("TEXT").IsRequired();
|
|
||||||
builder.Property(p => p.RepositoryUrl).HasColumnName("repository_url").HasMaxLength(255).IsRequired();
|
|
||||||
builder.Property(p => p.LiveDemoUrl).HasColumnName("live_demo_url").HasMaxLength(255);
|
|
||||||
builder.Property(p => p.ThumbnailUrl).HasColumnName("thumbnail_url").HasMaxLength(255);
|
|
||||||
builder.Property(p => p.IsFeatured).HasColumnName("is_featured").IsRequired();
|
|
||||||
builder.Property(p => p.DisplayOrder).HasColumnName("display_order").IsRequired();
|
|
||||||
builder.Property(p => p.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
|
|
||||||
builder.Property(p => p.UpdatedAtUtc).HasColumnName("updated_at_utc");
|
|
||||||
|
|
||||||
builder.HasIndex(p => new { p.IsFeatured, p.DisplayOrder });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Configurations;
|
|
||||||
|
|
||||||
public sealed class ProjectSkillConfiguration : IEntityTypeConfiguration<ProjectSkill>
|
|
||||||
{
|
|
||||||
public void Configure(EntityTypeBuilder<ProjectSkill> builder)
|
|
||||||
{
|
|
||||||
builder.ToTable("project_skills");
|
|
||||||
|
|
||||||
builder.HasKey(ps => new { ps.ProjectId, ps.SkillId });
|
|
||||||
builder.Property(ps => ps.ProjectId).HasColumnName("project_id").HasMaxLength(36);
|
|
||||||
builder.Property(ps => ps.SkillId).HasColumnName("skill_id").HasMaxLength(36);
|
|
||||||
|
|
||||||
builder.HasOne(ps => ps.Project)
|
|
||||||
.WithMany(p => p.ProjectSkills)
|
|
||||||
.HasForeignKey(ps => ps.ProjectId)
|
|
||||||
.OnDelete(DeleteBehavior.Cascade);
|
|
||||||
|
|
||||||
builder.HasOne(ps => ps.Skill)
|
|
||||||
.WithMany(s => s.ProjectSkills)
|
|
||||||
.HasForeignKey(ps => ps.SkillId)
|
|
||||||
.OnDelete(DeleteBehavior.Restrict);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Configurations;
|
|
||||||
|
|
||||||
public sealed class RefreshTokenConfiguration : IEntityTypeConfiguration<RefreshToken>
|
|
||||||
{
|
|
||||||
public void Configure(EntityTypeBuilder<RefreshToken> builder)
|
|
||||||
{
|
|
||||||
builder.ToTable("refresh_tokens");
|
|
||||||
|
|
||||||
builder.HasKey(rt => rt.Id);
|
|
||||||
builder.Property(rt => rt.Id).HasColumnName("id").HasMaxLength(36);
|
|
||||||
|
|
||||||
builder.Property(rt => rt.UserId).HasColumnName("user_id").HasMaxLength(36).IsRequired();
|
|
||||||
builder.Property(rt => rt.TokenHash).HasColumnName("token_hash").HasMaxLength(255).IsRequired();
|
|
||||||
builder.Property(rt => rt.ExpiresAtUtc).HasColumnName("expires_at_utc").IsRequired();
|
|
||||||
builder.Property(rt => rt.IsRevoked).HasColumnName("is_revoked").IsRequired();
|
|
||||||
builder.Property(rt => rt.ReplacedByToken).HasColumnName("replaced_by_token").HasMaxLength(255);
|
|
||||||
builder.Property(rt => rt.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
|
|
||||||
|
|
||||||
builder.HasOne(rt => rt.User)
|
|
||||||
.WithMany(u => u.RefreshTokens)
|
|
||||||
.HasForeignKey(rt => rt.UserId)
|
|
||||||
.OnDelete(DeleteBehavior.Cascade);
|
|
||||||
|
|
||||||
builder.HasIndex(rt => new { rt.UserId, rt.IsRevoked, rt.ExpiresAtUtc });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Configurations;
|
|
||||||
|
|
||||||
public sealed class SkillConfiguration : IEntityTypeConfiguration<Skill>
|
|
||||||
{
|
|
||||||
public void Configure(EntityTypeBuilder<Skill> builder)
|
|
||||||
{
|
|
||||||
builder.ToTable("skills");
|
|
||||||
|
|
||||||
builder.HasKey(s => s.Id);
|
|
||||||
builder.Property(s => s.Id).HasColumnName("id").HasMaxLength(36);
|
|
||||||
|
|
||||||
builder.Property(s => s.Name).HasColumnName("name").HasMaxLength(50).IsRequired();
|
|
||||||
builder.HasIndex(s => s.Name).IsUnique();
|
|
||||||
|
|
||||||
builder.Property(s => s.Category).HasColumnName("category").HasConversion<string>().HasMaxLength(30).IsRequired();
|
|
||||||
builder.Property(s => s.IconSlug).HasColumnName("icon_slug").HasMaxLength(50);
|
|
||||||
builder.Property(s => s.ProficiencyPercentage).HasColumnName("proficiency_percentage").IsRequired();
|
|
||||||
builder.Property(s => s.DisplayOrder).HasColumnName("display_order").IsRequired();
|
|
||||||
builder.Property(s => s.IsFeatured).HasColumnName("is_featured").IsRequired();
|
|
||||||
builder.Property(s => s.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
|
|
||||||
|
|
||||||
builder.HasIndex(s => new { s.Category, s.DisplayOrder });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Configurations;
|
|
||||||
|
|
||||||
public sealed class UserConfiguration : IEntityTypeConfiguration<User>
|
|
||||||
{
|
|
||||||
public void Configure(EntityTypeBuilder<User> builder)
|
|
||||||
{
|
|
||||||
builder.ToTable("users");
|
|
||||||
|
|
||||||
builder.HasKey(u => u.Id);
|
|
||||||
builder.Property(u => u.Id).HasColumnName("id").HasMaxLength(36);
|
|
||||||
|
|
||||||
builder.Property(u => u.Username).HasColumnName("username").HasMaxLength(50).IsRequired();
|
|
||||||
builder.HasIndex(u => u.Username).IsUnique();
|
|
||||||
|
|
||||||
builder.Property(u => u.Email).HasColumnName("email").HasMaxLength(100).IsRequired();
|
|
||||||
builder.HasIndex(u => u.Email).IsUnique();
|
|
||||||
|
|
||||||
builder.Property(u => u.PasswordHash).HasColumnName("password_hash").HasMaxLength(255).IsRequired();
|
|
||||||
builder.Property(u => u.Role).HasColumnName("role").HasMaxLength(20).IsRequired();
|
|
||||||
builder.Property(u => u.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
|
|
||||||
builder.Property(u => u.UpdatedAtUtc).HasColumnName("updated_at_utc");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
using System.Reflection;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Context;
|
|
||||||
|
|
||||||
public sealed class PortfolioDbContext(DbContextOptions<PortfolioDbContext> options) : DbContext(options)
|
|
||||||
{
|
|
||||||
public DbSet<Project> Projects => Set<Project>();
|
|
||||||
public DbSet<Skill> Skills => Set<Skill>();
|
|
||||||
public DbSet<ProjectSkill> ProjectSkills => Set<ProjectSkill>();
|
|
||||||
public DbSet<InteractiveMessage> InteractiveMessages => Set<InteractiveMessage>();
|
|
||||||
public DbSet<GameScore> GameScores => Set<GameScore>();
|
|
||||||
public DbSet<ContactInquiry> ContactInquiries => Set<ContactInquiry>();
|
|
||||||
public DbSet<User> Users => Set<User>();
|
|
||||||
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
|
|
||||||
|
|
||||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
|
||||||
{
|
|
||||||
base.OnModelCreating(modelBuilder);
|
|
||||||
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
using Portfolio.Infrastructure.Persistence.Context;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Repositories;
|
|
||||||
|
|
||||||
public sealed class GameScoreRepository(PortfolioDbContext context) : IGameScoreRepository
|
|
||||||
{
|
|
||||||
public async Task<IReadOnlyList<GameScore>> GetTopScoresAsync(string gameName, int limit = 10, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return await context.GameScores
|
|
||||||
.AsNoTracking()
|
|
||||||
.Where(g => g.GameName == gameName.ToLower())
|
|
||||||
.OrderByDescending(g => g.Score)
|
|
||||||
.ThenBy(g => g.DurationSeconds)
|
|
||||||
.Take(limit)
|
|
||||||
.ToListAsync(ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task AddAsync(GameScore score, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
await context.GameScores.AddAsync(score, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<int> SaveChangesAsync(CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return context.SaveChangesAsync(ct);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
using Portfolio.Infrastructure.Persistence.Context;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Repositories;
|
|
||||||
|
|
||||||
public sealed class InteractiveMessageRepository(PortfolioDbContext context) : IInteractiveMessageRepository
|
|
||||||
{
|
|
||||||
public async Task<IReadOnlyList<InteractiveMessage>> GetRecentApprovedAsync(int limit = 50, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return await context.InteractiveMessages
|
|
||||||
.AsNoTracking()
|
|
||||||
.Where(m => m.IsApproved)
|
|
||||||
.OrderByDescending(m => m.CreatedAtUtc)
|
|
||||||
.Take(limit)
|
|
||||||
.ToListAsync(ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task AddAsync(InteractiveMessage message, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
await context.InteractiveMessages.AddAsync(message, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<int> SaveChangesAsync(CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return context.SaveChangesAsync(ct);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,64 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
using Portfolio.Infrastructure.Persistence.Context;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Repositories;
|
|
||||||
|
|
||||||
public sealed class ProjectRepository(PortfolioDbContext context) : IProjectRepository
|
|
||||||
{
|
|
||||||
public async Task<IReadOnlyList<Project>> GetAllAsync(bool featuredOnly = false, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var query = context.Projects
|
|
||||||
.AsNoTracking()
|
|
||||||
.Include(p => p.ProjectSkills)
|
|
||||||
.ThenInclude(ps => ps.Skill)
|
|
||||||
.AsQueryable();
|
|
||||||
|
|
||||||
if (featuredOnly)
|
|
||||||
{
|
|
||||||
query = query.Where(p => p.IsFeatured);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await query
|
|
||||||
.OrderBy(p => p.DisplayOrder)
|
|
||||||
.ThenByDescending(p => p.CreatedAtUtc)
|
|
||||||
.ToListAsync(ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<Project?> GetBySlugAsync(string slug, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return await context.Projects
|
|
||||||
.AsNoTracking()
|
|
||||||
.Include(p => p.ProjectSkills)
|
|
||||||
.ThenInclude(ps => ps.Skill)
|
|
||||||
.FirstOrDefaultAsync(p => p.Slug == slug.ToLower(), ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<Project?> GetByIdAsync(Guid id, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return await context.Projects
|
|
||||||
.Include(p => p.ProjectSkills)
|
|
||||||
.FirstOrDefaultAsync(p => p.Id == id, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task AddAsync(Project project, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
await context.Projects.AddAsync(project, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Update(Project project)
|
|
||||||
{
|
|
||||||
context.Projects.Update(project);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Delete(Project project)
|
|
||||||
{
|
|
||||||
context.Projects.Remove(project);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<int> SaveChangesAsync(CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return context.SaveChangesAsync(ct);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
using Portfolio.Infrastructure.Persistence.Context;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Repositories;
|
|
||||||
|
|
||||||
public sealed class SkillRepository(PortfolioDbContext context) : ISkillRepository
|
|
||||||
{
|
|
||||||
public async Task<IReadOnlyList<Skill>> GetAllAsync(SkillCategory? category = null, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var query = context.Skills.AsNoTracking().AsQueryable();
|
|
||||||
|
|
||||||
if (category.HasValue)
|
|
||||||
{
|
|
||||||
query = query.Where(s => s.Category == category.Value);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await query
|
|
||||||
.OrderBy(s => s.Category)
|
|
||||||
.ThenBy(s => s.DisplayOrder)
|
|
||||||
.ToListAsync(ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<Skill?> GetByIdAsync(Guid id, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return await context.Skills.FindAsync([id], ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task AddAsync(Skill skill, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
await context.Skills.AddAsync(skill, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<int> SaveChangesAsync(CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return context.SaveChangesAsync(ct);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
using Portfolio.Domain.Interfaces;
|
|
||||||
using Portfolio.Infrastructure.Persistence.Context;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Persistence.Repositories;
|
|
||||||
|
|
||||||
public sealed class UserRepository(PortfolioDbContext context) : IUserRepository
|
|
||||||
{
|
|
||||||
public async Task<User?> GetByUsernameOrEmailAsync(string identifier, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var lower = identifier.ToLower().Trim();
|
|
||||||
return await context.Users
|
|
||||||
.Include(u => u.RefreshTokens)
|
|
||||||
.FirstOrDefaultAsync(u => u.Username.ToLower() == lower || u.Email.ToLower() == lower, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<User?> GetByIdAsync(Guid id, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return await context.Users
|
|
||||||
.Include(u => u.RefreshTokens)
|
|
||||||
.FirstOrDefaultAsync(u => u.Id == id, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task AddRefreshTokenAsync(RefreshToken refreshToken, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
await context.RefreshTokens.AddAsync(refreshToken, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<RefreshToken?> GetRefreshTokenAsync(string tokenHash, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return await context.RefreshTokens
|
|
||||||
.Include(rt => rt.User)
|
|
||||||
.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<int> SaveChangesAsync(CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
return context.SaveChangesAsync(ct);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\Portfolio.Application\Portfolio.Application.csproj" />
|
|
||||||
<ProjectReference Include="..\Portfolio.Domain\Portfolio.Domain.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="BCrypt.Net-Next" Version="4.2.0" />
|
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" />
|
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.10" />
|
|
||||||
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
|
|
||||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.23.0" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
|
|
@ -1,52 +0,0 @@
|
||||||
using System.IdentityModel.Tokens.Jwt;
|
|
||||||
using System.Security.Claims;
|
|
||||||
using System.Security.Cryptography;
|
|
||||||
using System.Text;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.IdentityModel.Tokens;
|
|
||||||
using Portfolio.Application.Common.Interfaces;
|
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Security;
|
|
||||||
|
|
||||||
public sealed class JwtTokenGenerator(IConfiguration configuration) : IJwtTokenGenerator
|
|
||||||
{
|
|
||||||
public string GenerateAccessToken(User user)
|
|
||||||
{
|
|
||||||
var secret = configuration["JwtSettings:Secret"]
|
|
||||||
?? "DefaultDevelopmentSecretKeyMustBeOverriddenInProduction123456789";
|
|
||||||
var issuer = configuration["JwtSettings:Issuer"] ?? "PortfolioBackend";
|
|
||||||
var audience = configuration["JwtSettings:Audience"] ?? "PortfolioFrontend";
|
|
||||||
var expiryMinutes = int.TryParse(configuration["JwtSettings:ExpiryMinutes"], out var exp) ? exp : 60;
|
|
||||||
|
|
||||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
|
|
||||||
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
||||||
|
|
||||||
var claims = new[]
|
|
||||||
{
|
|
||||||
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
|
|
||||||
new Claim(JwtRegisteredClaimNames.UniqueName, user.Username),
|
|
||||||
new Claim(JwtRegisteredClaimNames.Email, user.Email),
|
|
||||||
new Claim(ClaimTypes.Role, user.Role),
|
|
||||||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
|
||||||
};
|
|
||||||
|
|
||||||
var token = new JwtSecurityToken(
|
|
||||||
issuer: issuer,
|
|
||||||
audience: audience,
|
|
||||||
claims: claims,
|
|
||||||
expires: DateTime.UtcNow.AddMinutes(expiryMinutes),
|
|
||||||
signingCredentials: credentials
|
|
||||||
);
|
|
||||||
|
|
||||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
||||||
}
|
|
||||||
|
|
||||||
public string GenerateRefreshToken()
|
|
||||||
{
|
|
||||||
var randomBytes = new byte[64];
|
|
||||||
using var rng = RandomNumberGenerator.Create();
|
|
||||||
rng.GetBytes(randomBytes);
|
|
||||||
return Convert.ToBase64String(randomBytes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
using Portfolio.Application.Common.Interfaces;
|
|
||||||
|
|
||||||
namespace Portfolio.Infrastructure.Security;
|
|
||||||
|
|
||||||
public sealed class PasswordHasher : IPasswordHasher
|
|
||||||
{
|
|
||||||
public string Hash(string password)
|
|
||||||
{
|
|
||||||
return BCrypt.Net.BCrypt.HashPassword(password, workFactor: 11);
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool Verify(string password, string passwordHash)
|
|
||||||
{
|
|
||||||
return BCrypt.Net.BCrypt.Verify(password, passwordHash);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Portfolio.Application.Features.Guestbook.Commands;
|
|
||||||
using Portfolio.Application.Features.Guestbook.DTOs;
|
|
||||||
using Portfolio.Application.Features.Guestbook.Queries;
|
|
||||||
|
|
||||||
namespace Portfolio.WebApi.Controllers;
|
|
||||||
|
|
||||||
[ApiController]
|
|
||||||
[Route("api/v1/[controller]")]
|
|
||||||
[Produces("application/json")]
|
|
||||||
public sealed class GuestbookController(ISender sender) : ControllerBase
|
|
||||||
{
|
|
||||||
[HttpGet]
|
|
||||||
[ProducesResponseType(typeof(IReadOnlyList<GuestbookMessageResponseDto>), StatusCodes.Status200OK)]
|
|
||||||
public async Task<ActionResult<IReadOnlyList<GuestbookMessageResponseDto>>> GetRecent(
|
|
||||||
[FromQuery] int limit = 50,
|
|
||||||
CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var result = await sender.Send(new GetGuestbookMessagesQuery(limit), ct);
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpPost]
|
|
||||||
[ProducesResponseType(typeof(GuestbookMessageResponseDto), StatusCodes.Status201Created)]
|
|
||||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
|
||||||
public async Task<ActionResult<GuestbookMessageResponseDto>> Create(
|
|
||||||
[FromBody] CreateGuestbookMessageRequestDto request,
|
|
||||||
CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var command = new CreateGuestbookMessageCommand(
|
|
||||||
request.SenderName,
|
|
||||||
request.Message,
|
|
||||||
request.Origin,
|
|
||||||
request.SenderContact
|
|
||||||
);
|
|
||||||
|
|
||||||
var result = await sender.Send(command, ct);
|
|
||||||
return StatusCode(StatusCodes.Status201Created, result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Portfolio.Application.Features.Leaderboard.Commands;
|
|
||||||
using Portfolio.Application.Features.Leaderboard.DTOs;
|
|
||||||
using Portfolio.Application.Features.Leaderboard.Queries;
|
|
||||||
|
|
||||||
namespace Portfolio.WebApi.Controllers;
|
|
||||||
|
|
||||||
[ApiController]
|
|
||||||
[Route("api/v1/[controller]")]
|
|
||||||
[Produces("application/json")]
|
|
||||||
public sealed class LeaderboardController(ISender sender) : ControllerBase
|
|
||||||
{
|
|
||||||
[HttpGet]
|
|
||||||
[ProducesResponseType(typeof(IReadOnlyList<GameScoreResponseDto>), StatusCodes.Status200OK)]
|
|
||||||
public async Task<ActionResult<IReadOnlyList<GameScoreResponseDto>>> GetLeaderboard(
|
|
||||||
[FromQuery] string game = "Minesweeper",
|
|
||||||
[FromQuery] int limit = 10,
|
|
||||||
CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var result = await sender.Send(new GetLeaderboardQuery(game, limit), ct);
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpPost]
|
|
||||||
[ProducesResponseType(typeof(GameScoreResponseDto), StatusCodes.Status201Created)]
|
|
||||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
|
||||||
public async Task<ActionResult<GameScoreResponseDto>> SubmitScore(
|
|
||||||
[FromBody] SubmitGameScoreRequestDto request,
|
|
||||||
CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var command = new SubmitGameScoreCommand(
|
|
||||||
request.PlayerName,
|
|
||||||
request.GameName,
|
|
||||||
request.Score,
|
|
||||||
request.DurationSeconds,
|
|
||||||
request.CountryCode
|
|
||||||
);
|
|
||||||
|
|
||||||
var result = await sender.Send(command, ct);
|
|
||||||
return StatusCode(StatusCodes.Status201Created, result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Portfolio.Application.Features.Projects.DTOs;
|
|
||||||
using Portfolio.Application.Features.Projects.Queries;
|
|
||||||
|
|
||||||
namespace Portfolio.WebApi.Controllers;
|
|
||||||
|
|
||||||
[ApiController]
|
|
||||||
[Route("api/v1/[controller]")]
|
|
||||||
[Produces("application/json")]
|
|
||||||
public sealed class ProjectsController(ISender sender) : ControllerBase
|
|
||||||
{
|
|
||||||
[HttpGet]
|
|
||||||
[ProducesResponseType(typeof(IReadOnlyList<ProjectResponseDto>), StatusCodes.Status200OK)]
|
|
||||||
public async Task<ActionResult<IReadOnlyList<ProjectResponseDto>>> GetAll(
|
|
||||||
[FromQuery] bool featuredOnly = false,
|
|
||||||
CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var result = await sender.Send(new GetProjectsQuery(featuredOnly), ct);
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpGet("{slug}")]
|
|
||||||
[ProducesResponseType(typeof(ProjectResponseDto), StatusCodes.Status200OK)]
|
|
||||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
|
||||||
public async Task<ActionResult<ProjectResponseDto>> GetBySlug(string slug, CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var result = await sender.Send(new GetProjectBySlugQuery(slug), ct);
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
using MediatR;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Portfolio.Application.Features.Skills.DTOs;
|
|
||||||
using Portfolio.Application.Features.Skills.Queries;
|
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
namespace Portfolio.WebApi.Controllers;
|
|
||||||
|
|
||||||
[ApiController]
|
|
||||||
[Route("api/v1/[controller]")]
|
|
||||||
[Produces("application/json")]
|
|
||||||
public sealed class SkillsController(ISender sender) : ControllerBase
|
|
||||||
{
|
|
||||||
[HttpGet]
|
|
||||||
[ProducesResponseType(typeof(IReadOnlyList<SkillResponseDto>), StatusCodes.Status200OK)]
|
|
||||||
public async Task<ActionResult<IReadOnlyList<SkillResponseDto>>> GetAll(
|
|
||||||
[FromQuery] SkillCategory? category = null,
|
|
||||||
CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
var result = await sender.Send(new GetSkillsQuery(category), ct);
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
using System.Diagnostics;
|
|
||||||
using MediatR;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Portfolio.Application.Features.Telemetry.DTOs;
|
|
||||||
using Portfolio.Application.Features.Telemetry.Queries;
|
|
||||||
|
|
||||||
namespace Portfolio.WebApi.Controllers;
|
|
||||||
|
|
||||||
[ApiController]
|
|
||||||
[Route("api/v1/[controller]")]
|
|
||||||
[Produces("application/json")]
|
|
||||||
public sealed class TelemetryController(ISender sender) : ControllerBase
|
|
||||||
{
|
|
||||||
[HttpGet]
|
|
||||||
[ProducesResponseType(typeof(ServerTelemetryDto), StatusCodes.Status200OK)]
|
|
||||||
public async Task<ActionResult<ServerTelemetryDto>> GetServerTelemetry(CancellationToken ct)
|
|
||||||
{
|
|
||||||
var result = await sender.Send(new GetServerTelemetryQuery(), ct);
|
|
||||||
return Ok(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpGet("ping")]
|
|
||||||
[ProducesResponseType(typeof(PingResponseDto), StatusCodes.Status200OK)]
|
|
||||||
public ActionResult<PingResponseDto> Ping()
|
|
||||||
{
|
|
||||||
var sw = Stopwatch.StartNew();
|
|
||||||
sw.Stop();
|
|
||||||
|
|
||||||
return Ok(new PingResponseDto(
|
|
||||||
Message: "PONG // ZEN SERVER HEALTHY",
|
|
||||||
LatencyMs: sw.ElapsedMilliseconds,
|
|
||||||
TimestampUtc: DateTime.UtcNow
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,54 +0,0 @@
|
||||||
using FluentValidation;
|
|
||||||
using Microsoft.AspNetCore.Diagnostics;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Portfolio.Domain.Exceptions;
|
|
||||||
|
|
||||||
namespace Portfolio.WebApi.Middleware;
|
|
||||||
|
|
||||||
public sealed class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
|
|
||||||
{
|
|
||||||
public async ValueTask<bool> TryHandleAsync(
|
|
||||||
HttpContext httpContext,
|
|
||||||
Exception exception,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
logger.LogError(exception, "Unhandled exception occurred: {Message}", exception.Message);
|
|
||||||
|
|
||||||
var problemDetails = exception switch
|
|
||||||
{
|
|
||||||
ValidationException valEx => new ProblemDetails
|
|
||||||
{
|
|
||||||
Status = StatusCodes.Status400BadRequest,
|
|
||||||
Title = "Validation Error",
|
|
||||||
Detail = "One or more validation errors occurred.",
|
|
||||||
Extensions =
|
|
||||||
{
|
|
||||||
["errors"] = valEx.Errors.Select(e => new { e.PropertyName, e.ErrorMessage })
|
|
||||||
}
|
|
||||||
},
|
|
||||||
NotFoundException notFoundEx => new ProblemDetails
|
|
||||||
{
|
|
||||||
Status = StatusCodes.Status404NotFound,
|
|
||||||
Title = "Not Found",
|
|
||||||
Detail = notFoundEx.Message
|
|
||||||
},
|
|
||||||
DomainException domainEx => new ProblemDetails
|
|
||||||
{
|
|
||||||
Status = StatusCodes.Status400BadRequest,
|
|
||||||
Title = "Domain Rule Violation",
|
|
||||||
Detail = domainEx.Message
|
|
||||||
},
|
|
||||||
_ => new ProblemDetails
|
|
||||||
{
|
|
||||||
Status = StatusCodes.Status500InternalServerError,
|
|
||||||
Title = "Internal Server Error",
|
|
||||||
Detail = "An unexpected error occurred. Please contact the administrator."
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
httpContext.Response.StatusCode = problemDetails.Status ?? StatusCodes.Status500InternalServerError;
|
|
||||||
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
|
||||||
<RollForward>LatestMajor</RollForward>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
|
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.10">
|
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
|
||||||
<PrivateAssets>all</PrivateAssets>
|
|
||||||
</PackageReference>
|
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\Portfolio.Application\Portfolio.Application.csproj" />
|
|
||||||
<ProjectReference Include="..\Portfolio.Infrastructure\Portfolio.Infrastructure.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
@Portfolio.WebApi_HostAddress = http://localhost:5117
|
|
||||||
|
|
||||||
GET {{Portfolio.WebApi_HostAddress}}/weatherforecast/
|
|
||||||
Accept: application/json
|
|
||||||
|
|
||||||
###
|
|
||||||
|
|
@ -1,135 +0,0 @@
|
||||||
using Microsoft.OpenApi.Models;
|
|
||||||
using Portfolio.Application;
|
|
||||||
using Portfolio.Infrastructure;
|
|
||||||
using Portfolio.Infrastructure.Persistence.Context;
|
|
||||||
using Portfolio.WebApi.Middleware;
|
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
|
||||||
|
|
||||||
// 1. Configuracion en cascada: appsettingsdevelop.json (base segura en Git) + appsettings.json (secretos locales)
|
|
||||||
builder.Configuration
|
|
||||||
.SetBasePath(builder.Environment.ContentRootPath)
|
|
||||||
.AddJsonFile("appsettingsdevelop.json", optional: true, reloadOnChange: true)
|
|
||||||
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
|
|
||||||
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
|
|
||||||
.AddEnvironmentVariables();
|
|
||||||
|
|
||||||
// 2. Inyeccion de dependencias de Capas (Clean Architecture)
|
|
||||||
builder.Services.AddApplication();
|
|
||||||
builder.Services.AddInfrastructure(builder.Configuration);
|
|
||||||
|
|
||||||
// 3. Manejo Global de Excepciones (RFC 7807 ProblemDetails)
|
|
||||||
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
|
|
||||||
builder.Services.AddProblemDetails();
|
|
||||||
|
|
||||||
// 4. Controladores y Serializacion JSON
|
|
||||||
builder.Services.AddControllers()
|
|
||||||
.AddJsonOptions(options =>
|
|
||||||
{
|
|
||||||
options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
|
|
||||||
});
|
|
||||||
|
|
||||||
// 5. Configuracion de CORS para Angular Frontend
|
|
||||||
var allowedOrigins = builder.Configuration.GetSection("CorsSettings:AllowedOrigins").Get<string[]>()
|
|
||||||
?? ["http://localhost:4200", "https://bryan-bano.com", "https://portfolio.bryan-bano.com"];
|
|
||||||
|
|
||||||
builder.Services.AddCors(options =>
|
|
||||||
{
|
|
||||||
options.AddPolicy("PortfolioCorsPolicy", policy =>
|
|
||||||
{
|
|
||||||
policy.WithOrigins(allowedOrigins)
|
|
||||||
.AllowAnyHeader()
|
|
||||||
.AllowAnyMethod()
|
|
||||||
.AllowCredentials();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// 6. OpenAPI / Swagger con documentacion Cyber-Zen
|
|
||||||
builder.Services.AddEndpointsApiExplorer();
|
|
||||||
builder.Services.AddSwaggerGen(c =>
|
|
||||||
{
|
|
||||||
c.SwaggerDoc("v1", new OpenApiInfo
|
|
||||||
{
|
|
||||||
Title = "Bryan Baño // Portfolio API",
|
|
||||||
Version = "v1",
|
|
||||||
Description = "API REST de alto rendimiento para el portafolio profesional interactivo. Clean Architecture, CQRS y persistencia MySQL.",
|
|
||||||
Contact = new OpenApiContact
|
|
||||||
{
|
|
||||||
Name = "Bryan Baño",
|
|
||||||
Email = "contacto@bryan-bano.com",
|
|
||||||
Url = new Uri("https://bryan-bano.com")
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
|
|
||||||
Name = "Authorization",
|
|
||||||
In = ParameterLocation.Header,
|
|
||||||
Type = SecuritySchemeType.Http,
|
|
||||||
Scheme = "bearer"
|
|
||||||
});
|
|
||||||
|
|
||||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
|
||||||
{
|
|
||||||
{
|
|
||||||
new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Reference = new OpenApiReference
|
|
||||||
{
|
|
||||||
Type = ReferenceType.SecurityScheme,
|
|
||||||
Id = "Bearer"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Array.Empty<string>()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var app = builder.Build();
|
|
||||||
|
|
||||||
// 7. Pipeline de Solicitudes HTTP
|
|
||||||
app.UseExceptionHandler();
|
|
||||||
|
|
||||||
if (app.Environment.IsDevelopment() || builder.Configuration.GetValue<bool>("EnableSwaggerInProd", true))
|
|
||||||
{
|
|
||||||
app.UseSwagger();
|
|
||||||
app.UseSwaggerUI(c =>
|
|
||||||
{
|
|
||||||
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Portfolio API v1");
|
|
||||||
c.DocumentTitle = "Bryan Baño // API Documentation";
|
|
||||||
c.RoutePrefix = "swagger";
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
app.UseCors("PortfolioCorsPolicy");
|
|
||||||
app.UseAuthentication();
|
|
||||||
app.UseAuthorization();
|
|
||||||
|
|
||||||
app.MapControllers();
|
|
||||||
|
|
||||||
// Healthcheck basico en raiz
|
|
||||||
app.MapGet("/", () => Results.Ok(new
|
|
||||||
{
|
|
||||||
service = "Portfolio Backend API",
|
|
||||||
status = "Online",
|
|
||||||
version = "1.0.0",
|
|
||||||
docs = "/swagger"
|
|
||||||
}));
|
|
||||||
|
|
||||||
// 8. Auto-provisionamiento de esquema de base de datos en arranque
|
|
||||||
using (var scope = app.Services.CreateScope())
|
|
||||||
{
|
|
||||||
var db = scope.ServiceProvider.GetRequiredService<PortfolioDbContext>();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
db.Database.EnsureCreated();
|
|
||||||
app.Logger.LogInformation("Esquema de base de datos asegurado correctamente.");
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
app.Logger.LogWarning(ex, "No se pudo sincronizar la base de datos al inicio. Verifica la conexión a MySQL.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
app.Run();
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
{
|
|
||||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
|
||||||
"iisSettings": {
|
|
||||||
"windowsAuthentication": false,
|
|
||||||
"anonymousAuthentication": true,
|
|
||||||
"iisExpress": {
|
|
||||||
"applicationUrl": "http://localhost:25368",
|
|
||||||
"sslPort": 44302
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"profiles": {
|
|
||||||
"http": {
|
|
||||||
"commandName": "Project",
|
|
||||||
"dotnetRunMessages": true,
|
|
||||||
"launchBrowser": true,
|
|
||||||
"launchUrl": "swagger",
|
|
||||||
"applicationUrl": "http://localhost:5117",
|
|
||||||
"environmentVariables": {
|
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"https": {
|
|
||||||
"commandName": "Project",
|
|
||||||
"dotnetRunMessages": true,
|
|
||||||
"launchBrowser": true,
|
|
||||||
"launchUrl": "swagger",
|
|
||||||
"applicationUrl": "https://localhost:7020;http://localhost:5117",
|
|
||||||
"environmentVariables": {
|
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"IIS Express": {
|
|
||||||
"commandName": "IISExpress",
|
|
||||||
"launchBrowser": true,
|
|
||||||
"launchUrl": "swagger",
|
|
||||||
"environmentVariables": {
|
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
{
|
|
||||||
"Logging": {
|
|
||||||
"LogLevel": {
|
|
||||||
"Default": "Information",
|
|
||||||
"Microsoft.AspNetCore": "Warning",
|
|
||||||
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"AllowedHosts": "*",
|
|
||||||
"ConnectionStrings": {
|
|
||||||
"DefaultConnection": "Server=localhost;Port=3306;Database=portfolio_db;User=root;Password=;CharSet=utf8mb4;"
|
|
||||||
},
|
|
||||||
"JwtSettings": {
|
|
||||||
"Secret": "YOUR_SUPER_SECRET_KEY_MINIMUM_32_CHARACTERS_LONG_PLACEHOLDER",
|
|
||||||
"Issuer": "PortfolioBackend",
|
|
||||||
"Audience": "PortfolioFrontend",
|
|
||||||
"ExpiryMinutes": 60,
|
|
||||||
"RefreshTokenExpiryDays": 7
|
|
||||||
},
|
|
||||||
"CorsSettings": {
|
|
||||||
"AllowedOrigins": [
|
|
||||||
"http://localhost:4200",
|
|
||||||
"https://bryan-bano.com",
|
|
||||||
"https://portfolio.bryan-bano.com"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"ServerTelemetry": {
|
|
||||||
"Region": "us-ashburn-1",
|
|
||||||
"Provider": "Oracle Cloud Infrastructure (OCI)",
|
|
||||||
"ServerName": "srv-personal-core",
|
|
||||||
"Architecture": "ARM64 Ampere Altra"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
using Portfolio.Domain.Entities;
|
|
||||||
using Portfolio.Domain.Enums;
|
|
||||||
|
|
||||||
namespace Portfolio.UnitTests;
|
|
||||||
|
|
||||||
public class DomainTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public void Project_Create_WithValidArgs_ShouldInstantiateCorrectly()
|
|
||||||
{
|
|
||||||
// Act
|
|
||||||
var project = Project.Create(
|
|
||||||
slug: "test-project",
|
|
||||||
title: "Test Project Title",
|
|
||||||
shortDescription: "Short description of project",
|
|
||||||
fullDescription: "Detailed description of architecture and features",
|
|
||||||
repositoryUrl: "https://github.com/bryan/test-project",
|
|
||||||
isFeatured: true
|
|
||||||
);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.NotNull(project);
|
|
||||||
Assert.Equal("test-project", project.Slug);
|
|
||||||
Assert.Equal("Test Project Title", project.Title);
|
|
||||||
Assert.True(project.IsFeatured);
|
|
||||||
Assert.NotEqual(Guid.Empty, project.Id);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("", "Title")]
|
|
||||||
[InlineData(" ", "Title")]
|
|
||||||
[InlineData("slug", "")]
|
|
||||||
[InlineData("slug", " ")]
|
|
||||||
public void Project_Create_WithInvalidArgs_ShouldThrowArgumentException(string slug, string title)
|
|
||||||
{
|
|
||||||
// Assert
|
|
||||||
Assert.Throws<ArgumentException>(() =>
|
|
||||||
Project.Create(
|
|
||||||
slug: slug,
|
|
||||||
title: title,
|
|
||||||
shortDescription: "Short",
|
|
||||||
fullDescription: "Full",
|
|
||||||
repositoryUrl: "https://repo"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Skill_Create_WithValidArgs_ShouldInstantiateCorrectly()
|
|
||||||
{
|
|
||||||
// Act
|
|
||||||
var skill = Skill.Create(".NET 8/9", SkillCategory.Backend, "dotnet", proficiency: 95);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.NotNull(skill);
|
|
||||||
Assert.Equal(".NET 8/9", skill.Name);
|
|
||||||
Assert.Equal(SkillCategory.Backend, skill.Category);
|
|
||||||
Assert.Equal(95, skill.ProficiencyPercentage);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
using Portfolio.Application.Features.Guestbook.Commands;
|
|
||||||
using Portfolio.Application.Features.Guestbook.Validators;
|
|
||||||
|
|
||||||
namespace Portfolio.UnitTests;
|
|
||||||
|
|
||||||
public class GuestbookValidationTests
|
|
||||||
{
|
|
||||||
private readonly CreateGuestbookMessageCommandValidator _validator = new();
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Validator_WithValidData_ShouldNotHaveErrors()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var command = new CreateGuestbookMessageCommand("Bryan Baño", "Excelente arquitectura.");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _validator.Validate(command);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.True(result.IsValid);
|
|
||||||
Assert.Empty(result.Errors);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("", "Mensaje de prueba")]
|
|
||||||
[InlineData("Bryan", "")]
|
|
||||||
[InlineData("Bryan", "ab")] // Menos de 3 caracteres
|
|
||||||
public void Validator_WithInvalidData_ShouldHaveValidationErrors(string senderName, string message)
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var command = new CreateGuestbookMessageCommand(senderName, message);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _validator.Validate(command);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.False(result.IsValid);
|
|
||||||
Assert.NotEmpty(result.Errors);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
|
||||||
<RollForward>LatestMajor</RollForward>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
|
|
||||||
<IsPackable>false</IsPackable>
|
|
||||||
<IsTestProject>true</IsTestProject>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="coverlet.collector" Version="6.0.0" />
|
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
|
|
||||||
<PackageReference Include="xunit" Version="2.5.3" />
|
|
||||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Using Include="Xunit" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\..\src\Portfolio.Application\Portfolio.Application.csproj" />
|
|
||||||
<ProjectReference Include="..\..\src\Portfolio.Domain\Portfolio.Domain.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
using Portfolio.Application.Features.Telemetry.Queries;
|
|
||||||
|
|
||||||
namespace Portfolio.UnitTests;
|
|
||||||
|
|
||||||
public class TelemetryTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task GetServerTelemetryQueryHandler_ShouldReturnOperationalStatus()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var handler = new GetServerTelemetryQueryHandler();
|
|
||||||
var query = new GetServerTelemetryQuery();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = await handler.Handle(query, CancellationToken.None);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.NotNull(result);
|
|
||||||
Assert.Equal("OPERATIONAL", result.Status);
|
|
||||||
Assert.Equal("us-ashburn-1", result.Region);
|
|
||||||
Assert.True(result.ProcessMemoryMb > 0);
|
|
||||||
Assert.True(result.ActiveThreads > 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -27,8 +27,7 @@
|
||||||
"glob": "**/*",
|
"glob": "**/*",
|
||||||
"input": "src/assets",
|
"input": "src/assets",
|
||||||
"output": "assets"
|
"output": "assets"
|
||||||
},
|
}
|
||||||
"src/_redirects"
|
|
||||||
],
|
],
|
||||||
"styles": [
|
"styles": [
|
||||||
"src/styles.css"
|
"src/styles.css"
|
||||||
|
|
@ -44,8 +43,8 @@
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": "anyComponentStyle",
|
"type": "anyComponentStyle",
|
||||||
"maximumWarning": "20kB",
|
"maximumWarning": "8kB",
|
||||||
"maximumError": "30kB"
|
"maximumError": "16kB"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"outputHashing": "all"
|
"outputHashing": "all"
|
||||||
|
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
/* /index.html 200
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue