Commit 427dec62 authored by Hoanganhvu123's avatar Hoanganhvu123

update

parent 1f2e4944
# Hướng dẫn tạo GitHub Personal Access Token (PAT)
## Bước 1: Đăng nhập GitHub
1. Truy cập: https://github.com
2. Đăng nhập vào tài khoản của bạn
## Bước 2: Vào phần Settings
1. Click vào **ảnh đại diện** (góc trên bên phải)
2. Chọn **Settings**
## Bước 3: Tạo Personal Access Token
1. Trong menu bên trái, scroll xuống và click **Developer settings**
2. Click **Personal access tokens****Tokens (classic)**
3. Click nút **Generate new token****Generate new token (classic)**
## Bước 4: Cấu hình Token
1. **Note**: Đặt tên cho token (ví dụ: "OpenNotion Project")
2. **Expiration**: Chọn thời hạn (khuyến nghị: 90 days hoặc No expiration)
3. **Select scopes**: Chọn các quyền cần thiết:
-**repo** (Full control of private repositories) - QUAN TRỌNG NHẤT
-**workflow** (nếu bạn dùng GitHub Actions)
4. Click **Generate token** ở cuối trang
## Bước 5: Copy và Lưu Token
⚠️ **QUAN TRỌNG**: Token chỉ hiển thị 1 lần duy nhất!
- Copy token ngay lập tức
- Lưu vào nơi an toàn (password manager, file text an toàn)
Token sẽ có dạng: `ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`
## Bước 6: Sử dụng Token để Push Code
### Cách 1: Dùng khi Git hỏi password
Khi chạy `git push`, Git sẽ hỏi:
- **Username**: `Hoanganhvu123` (tên GitHub của bạn)
- **Password**: Dán token vừa tạo (KHÔNG phải password GitHub)
### Cách 2: Lưu token vào Git Credential Manager
```powershell
# Windows
git config --global credential.helper manager
# Sau đó khi push lần đầu, nhập token
# Git sẽ tự động lưu cho lần sau
```
### Cách 3: Dùng token trực tiếp trong URL (tạm thời)
```powershell
git remote set-url origin https://ghp_YOUR_TOKEN@github.com/Hoanganhvu123/cuccu_note.git
git push -u origin main
```
## Lưu ý bảo mật:
- ❌ KHÔNG commit token vào code
- ❌ KHÔNG chia sẻ token công khai
- ✅ Chỉ dùng token khi cần thiết
- ✅ Xóa token cũ nếu không dùng nữa
## Nếu quên mất token:
- Vào lại GitHub → Settings → Developer settings → Personal access tokens
- Xóa token cũ và tạo token mới
...@@ -88,9 +88,10 @@ async def get_me( ...@@ -88,9 +88,10 @@ async def get_me(
avatar_url = getattr(me, "avatar_url", None) or "" avatar_url = getattr(me, "avatar_url", None) or ""
# Connect/proto expects: { "user": User } # Connect/proto expects: { "user": User }
# CRITICAL: Use me.id (Clerk user ID) for proper user data isolation!
return { return {
"user": { "user": {
"name": "users/1", "name": f"users/{me.id}",
"role": 1, # HOST "role": 1, # HOST
"username": username, "username": username,
"email": getattr(me, "email", ""), "email": getattr(me, "email", ""),
......
...@@ -167,11 +167,13 @@ CLERK_JWKS_URL: str | None = os.getenv("CLERK_JWKS_URL") or "https://communal-su ...@@ -167,11 +167,13 @@ CLERK_JWKS_URL: str | None = os.getenv("CLERK_JWKS_URL") or "https://communal-su
CLERK_ISSUER: str | None = os.getenv("CLERK_ISSUER") or "https://communal-sunbeam-0.clerk.accounts.dev" CLERK_ISSUER: str | None = os.getenv("CLERK_ISSUER") or "https://communal-sunbeam-0.clerk.accounts.dev"
# ====================== DATABASE CONNECTION ====================== # ====================== DATABASE CONNECTION ======================
# Redis Cache Configuration # Redis Cache Configuration (Redis Cloud Free - 30MB)
REDIS_CACHE_URL: str | None = os.getenv("REDIS_CACHE_URL") REDIS_CACHE_URL: str | None = os.getenv("REDIS_CACHE_URL", "redis-14473.c93.us-east-1-3.ec2.cloud.redislabs.com")
REDIS_CACHE_PORT: int = int(os.getenv("REDIS_CACHE_PORT", "6379")) REDIS_CACHE_PORT: int = int(os.getenv("REDIS_CACHE_PORT", "14473"))
REDIS_CACHE_DB: int = int(os.getenv("REDIS_CACHE_DB", "2")) REDIS_CACHE_DB: int = int(os.getenv("REDIS_CACHE_DB", "0"))
REDIS_CACHE_TURN_ON: bool = os.getenv("REDIS_CACHE_TURN_ON", "true").lower() == "true" REDIS_CACHE_TURN_ON: bool = os.getenv("REDIS_CACHE_TURN_ON", "true").lower() == "true"
REDIS_PASSWORD: str | None = os.getenv("REDIS_CACHE_PASSWORD", "4kCCXXaJXXv7k358eG69p1lDBQtHTbQ1")
REDIS_USERNAME: str = os.getenv("REDIS_CACHE_USERNAME", "default")
CONV_DATABASE_URL: str | None = os.getenv("CONV_DATABASE_URL") CONV_DATABASE_URL: str | None = os.getenv("CONV_DATABASE_URL")
......
"""Simple Redis connection test."""
import asyncio
import redis.asyncio as aioredis
async def test_redis():
try:
client = aioredis.Redis(
host='redis-14473.c93.us-east-1-3.ec2.cloud.redislabs.com',
port=14473,
password='4kCCXXaJXXv7k358eG69p1lDBQtHTbQ1',
username='default',
decode_responses=True,
socket_connect_timeout=10,
)
result = await client.ping()
print(f"✅ Redis PING: {result}")
# Test set/get
await client.set("test_key", "hello_opennotion")
value = await client.get("test_key")
print(f"✅ Redis SET/GET: {value}")
await client.close()
print("✅ Redis connection successful!")
except Exception as e:
print(f"❌ Redis error: {e}")
if __name__ == "__main__":
asyncio.run(test_redis())
"""
Redis Cache Tests - No pytest required
=======================================
Test Redis Cloud connection and caching functionality.
Run: python tests/test_redis.py
"""
import asyncio
import sys
import time
# Add parent dir to path
sys.path.insert(0, ".")
import redis.asyncio as aioredis
from config import (
REDIS_CACHE_URL,
REDIS_CACHE_PORT,
REDIS_CACHE_DB,
REDIS_PASSWORD,
REDIS_USERNAME,
)
async def test_redis_ping():
"""Test basic Redis PING command."""
print("1. Testing Redis PING...")
client = aioredis.Redis(
host=REDIS_CACHE_URL,
port=REDIS_CACHE_PORT,
db=REDIS_CACHE_DB,
password=REDIS_PASSWORD,
username=REDIS_USERNAME,
decode_responses=True,
socket_connect_timeout=10,
)
try:
result = await client.ping()
assert result is True, "Redis PING should return True"
print(" ✅ Redis PING successful")
return True
except Exception as e:
print(f" ❌ PING failed: {e}")
return False
finally:
await client.close()
async def test_redis_set_get():
"""Test Redis SET and GET operations."""
print("2. Testing Redis SET/GET...")
client = aioredis.Redis(
host=REDIS_CACHE_URL,
port=REDIS_CACHE_PORT,
db=REDIS_CACHE_DB,
password=REDIS_PASSWORD,
username=REDIS_USERNAME,
decode_responses=True,
socket_connect_timeout=10,
)
try:
test_key = "test:opennotion:connection"
test_value = "hello_from_tests"
await client.set(test_key, test_value, ex=60)
result = await client.get(test_key)
assert result == test_value, f"Expected '{test_value}', got '{result}'"
await client.delete(test_key)
print(" ✅ Redis SET/GET successful")
return True
except Exception as e:
print(f" ❌ SET/GET failed: {e}")
return False
finally:
await client.close()
async def test_redis_ttl():
"""Test Redis TTL (Time To Live)."""
print("3. Testing Redis TTL...")
client = aioredis.Redis(
host=REDIS_CACHE_URL,
port=REDIS_CACHE_PORT,
db=REDIS_CACHE_DB,
password=REDIS_PASSWORD,
username=REDIS_USERNAME,
decode_responses=True,
socket_connect_timeout=10,
)
try:
test_key = "test:opennotion:ttl"
await client.set(test_key, "ttl_test", ex=300)
ttl = await client.ttl(test_key)
assert ttl > 0, "TTL should be positive"
await client.delete(test_key)
print(f" ✅ Redis TTL test passed (TTL={ttl}s)")
return True
except Exception as e:
print(f" ❌ TTL test failed: {e}")
return False
finally:
await client.close()
async def test_bulk_operations():
"""Test bulk SET/GET operations."""
print("4. Testing bulk operations (100 ops)...")
client = aioredis.Redis(
host=REDIS_CACHE_URL,
port=REDIS_CACHE_PORT,
db=REDIS_CACHE_DB,
password=REDIS_PASSWORD,
username=REDIS_USERNAME,
decode_responses=True,
socket_connect_timeout=10,
)
try:
# Bulk SET
start = time.time()
for i in range(100):
await client.set(f"test:bulk:{i}", f"value_{i}", ex=60)
set_time = time.time() - start
# Bulk GET
start = time.time()
for i in range(100):
await client.get(f"test:bulk:{i}")
get_time = time.time() - start
# Cleanup
for i in range(100):
await client.delete(f"test:bulk:{i}")
print(f" ✅ Bulk SET: {set_time:.2f}s ({100/set_time:.0f} ops/s)")
print(f" ✅ Bulk GET: {get_time:.2f}s ({100/get_time:.0f} ops/s)")
return True
except Exception as e:
print(f" ❌ Bulk test failed: {e}")
return False
finally:
await client.close()
async def test_cache_module():
"""Test the RedisClient from common.cache."""
print("5. Testing cache module...")
try:
from common.cache import redis_cache
client = await redis_cache.connect()
if client:
print(" ✅ Cache module connected successfully")
stats = redis_cache.get_stats()
print(f" 📊 Cache stats: {stats}")
return True
else:
print(" ⚠️ Cache module disabled (no connection)")
return True
except Exception as e:
print(f" ❌ Cache module failed: {e}")
return False
async def run_all_tests():
"""Run all Redis tests."""
print("\n" + "="*60)
print("🔴 REDIS CONNECTION TESTS")
print(f" Host: {REDIS_CACHE_URL}")
print(f" Port: {REDIS_CACHE_PORT}")
print("="*60 + "\n")
results = []
results.append(await test_redis_ping())
results.append(await test_redis_set_get())
results.append(await test_redis_ttl())
results.append(await test_bulk_operations())
results.append(await test_cache_module())
print("\n" + "="*60)
passed = sum(results)
total = len(results)
if passed == total:
print(f"✅ ALL TESTS PASSED! ({passed}/{total})")
else:
print(f"⚠️ {passed}/{total} tests passed")
print("="*60 + "\n")
if __name__ == "__main__":
asyncio.run(run_all_tests())
# Kiểm tra và push code nếu có thay đổi
cd E:\opennotion
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Kiểm tra thay đổi và push code" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# 1. Kiểm tra trạng thái
Write-Host "[1/6] Kiểm tra trạng thái git..." -ForegroundColor Yellow
$status = git status --porcelain
if ($status) {
Write-Host "✓ Có file thay đổi:" -ForegroundColor Green
$status | ForEach-Object { Write-Host " $_" -ForegroundColor White }
} else {
Write-Host "✓ Không có file thay đổi" -ForegroundColor Green
}
Write-Host ""
# 2. Fetch từ remote
Write-Host "[2/6] Lấy thông tin từ GitHub..." -ForegroundColor Yellow
git fetch origin 2>&1 | Out-Null
Write-Host "✓ Đã fetch" -ForegroundColor Green
Write-Host ""
# 3. So sánh local vs remote
Write-Host "[3/6] So sánh local với remote..." -ForegroundColor Yellow
$localCommit = git rev-parse HEAD 2>$null
$remoteCommit = git rev-parse origin/main 2>$null
Write-Host "Local commit: $($localCommit.Substring(0,7))" -ForegroundColor Cyan
Write-Host "Remote commit: $($remoteCommit.Substring(0,7))" -ForegroundColor Cyan
Write-Host ""
# 4. Kiểm tra commits chưa push
Write-Host "[4/6] Kiểm tra commits chưa push..." -ForegroundColor Yellow
$unpushed = git log origin/main..HEAD --oneline
if ($unpushed) {
Write-Host "⚠ Có commits chưa push:" -ForegroundColor Yellow
$unpushed | ForEach-Object { Write-Host " $_" -ForegroundColor White }
} else {
Write-Host "✓ Không có commits mới để push" -ForegroundColor Green
}
Write-Host ""
# 5. Kiểm tra commits trên remote chưa có local
Write-Host "[5/6] Kiểm tra commits trên remote..." -ForegroundColor Yellow
$unpulled = git log HEAD..origin/main --oneline
if ($unpulled) {
Write-Host "⚠ Có commits trên remote chưa có local:" -ForegroundColor Yellow
$unpulled | ForEach-Object { Write-Host " $_" -ForegroundColor White }
Write-Host "⚠ Cần pull trước khi push!" -ForegroundColor Red
} else {
Write-Host "✓ Local đã đồng bộ với remote" -ForegroundColor Green
}
Write-Host ""
# 6. Push nếu có thay đổi
Write-Host "[6/6] Xử lý push..." -ForegroundColor Yellow
$hasUnpushed = git log origin/main..HEAD --oneline
$hasChanges = git status --porcelain
if ($hasUnpushed -or $hasChanges) {
if ($hasChanges) {
Write-Host "Đang thêm file thay đổi..." -ForegroundColor Yellow
git add .
Write-Host "Đang commit..." -ForegroundColor Yellow
git commit -m "Update: OpenNotion project - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
}
Write-Host "Đang push lên GitHub..." -ForegroundColor Yellow
$pushResult = git push origin main 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host " ✓ THÀNH CÔNG! Code đã được push!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Xem tại: https://github.com/Hoanganhvu123/cuccu_note" -ForegroundColor Cyan
} else {
Write-Host ""
Write-Host "========================================" -ForegroundColor Red
Write-Host " ✗ Push thất bại!" -ForegroundColor Red
Write-Host "========================================" -ForegroundColor Red
Write-Host $pushResult -ForegroundColor Red
}
} else {
Write-Host "✓ Không có gì để push - mọi thứ đã đồng bộ!" -ForegroundColor Green
}
Write-Host ""
# Kiểm tra trạng thái push
cd E:\opennotion
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Kiểm tra trạng thái Git" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "[1] Remote configuration:" -ForegroundColor Yellow
git remote -v
Write-Host ""
Write-Host "[2] Latest commit:" -ForegroundColor Yellow
git log --oneline -1
Write-Host ""
Write-Host "[3] Current branch:" -ForegroundColor Yellow
git branch --show-current
Write-Host ""
Write-Host "[4] Checking remote connection..." -ForegroundColor Yellow
$remoteCheck = git ls-remote --heads origin main 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host "✓ Kết nối thành công với GitHub!" -ForegroundColor Green
Write-Host "Remote branch info:" -ForegroundColor Cyan
$remoteCheck
} else {
Write-Host "✗ Không thể kết nối với remote" -ForegroundColor Red
Write-Host $remoteCheck
}
Write-Host ""
Write-Host "[5] Local vs Remote:" -ForegroundColor Yellow
$localCommit = git rev-parse HEAD 2>$null
$remoteCommit = git rev-parse origin/main 2>$null
if ($localCommit -eq $remoteCommit) {
Write-Host "✓ Code đã được push thành công!" -ForegroundColor Green
Write-Host "Local và Remote đã đồng bộ" -ForegroundColor Green
} else {
Write-Host "⚠ Local và Remote khác nhau" -ForegroundColor Yellow
Write-Host "Local: $localCommit" -ForegroundColor Cyan
Write-Host "Remote: $remoteCommit" -ForegroundColor Cyan
}
Write-Host ""
Write-Host "Repository URL:" -ForegroundColor Cyan
Write-Host "https://github.com/Hoanganhvu123/cuccu_note" -ForegroundColor White
# Script push code lên GitHub với token
cd E:\opennotion
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Đang push code lên GitHub..." -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# Kiểm tra remote
Write-Host "[1/5] Kiểm tra remote..." -ForegroundColor Yellow
git remote -v
Write-Host ""
# Add files
Write-Host "[2/5] Thêm tất cả file vào staging..." -ForegroundColor Yellow
git add .
$staged = git diff --cached --name-only
if ($staged.Count -gt 0) {
Write-Host "✓ Đã thêm $($staged.Count) file(s)" -ForegroundColor Green
} else {
Write-Host "⚠ Không có file mới để thêm" -ForegroundColor Yellow
}
Write-Host ""
# Commit
Write-Host "[3/5] Tạo commit..." -ForegroundColor Yellow
$hasChanges = git diff --cached --quiet
if ($LASTEXITCODE -ne 0) {
$commitMsg = "Update: OpenNotion project - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
git commit -m $commitMsg
Write-Host "✓ Đã commit: $commitMsg" -ForegroundColor Green
} else {
Write-Host "⚠ Không có thay đổi để commit" -ForegroundColor Yellow
# Tạo empty commit để đảm bảo có gì đó để push
git commit --allow-empty -m "Update: OpenNotion project - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Host "✓ Đã tạo empty commit" -ForegroundColor Green
}
Write-Host ""
# Đảm bảo branch là main
Write-Host "[4/5] Đảm bảo branch là main..." -ForegroundColor Yellow
git branch -M main
Write-Host "✓ Branch: main" -ForegroundColor Green
Write-Host ""
# Push
Write-Host "[5/5] Push lên GitHub..." -ForegroundColor Yellow
Write-Host "Repository: https://github.com/Hoanganhvu123/cuccu_note" -ForegroundColor Cyan
Write-Host ""
$pushOutput = git push -u origin main 2>&1
$pushExitCode = $LASTEXITCODE
Write-Host $pushOutput
if ($pushExitCode -eq 0) {
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host " ✓ THÀNH CÔNG! Code đã được push!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Xem code tại:" -ForegroundColor Cyan
Write-Host "https://github.com/Hoanganhvu123/cuccu_note" -ForegroundColor White
Write-Host ""
# Kiểm tra remote branch
Write-Host "Kiểm tra remote branch..." -ForegroundColor Yellow
$remoteInfo = git ls-remote --heads origin main 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host "✓ Remote branch tồn tại" -ForegroundColor Green
Write-Host $remoteInfo
}
} else {
Write-Host ""
Write-Host "========================================" -ForegroundColor Red
Write-Host " ✗ Push thất bại! Exit code: $pushExitCode" -ForegroundColor Red
Write-Host "========================================" -ForegroundColor Red
Write-Host ""
Write-Host "Lỗi chi tiết:" -ForegroundColor Yellow
Write-Host $pushOutput -ForegroundColor Red
}
...@@ -91,8 +91,15 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({ ...@@ -91,8 +91,15 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
dispatch(actions.setLoading("saving", true)); dispatch(actions.setLoading("saving", true));
try { try {
// When creating new memo with date filter, use CURRENT timestamp (not midnight)
// The displayTime filter is for display purposes only, not for setting create_time to midnight
// Only use createTimeOverride for existing memo updates (when memoName is provided)
const displayTimeFilter = filters.find((f) => f.factor === "displayTime"); const displayTimeFilter = filters.find((f) => f.factor === "displayTime");
const createTimeOverride = displayTimeFilter?.value ? new Date(displayTimeFilter.value) : undefined; // For new memos: don't override createTime (let backend use current timestamp)
// For updates: if displayTime filter changed, preserve the filtered date
const createTimeOverride = memoName && displayTimeFilter?.value
? new Date(displayTimeFilter.value)
: undefined;
const result = await memoService.save( const result = await memoService.save(
state, state,
......
...@@ -23,7 +23,9 @@ const MemoView: React.FC<MemoViewProps> = (props: MemoViewProps) => { ...@@ -23,7 +23,9 @@ const MemoView: React.FC<MemoViewProps> = (props: MemoViewProps) => {
const creator = useUser(memoData.creator, { enabled: !isAnonymousCreator }).data; const creator = useUser(memoData.creator, { enabled: !isAnonymousCreator }).data;
const isArchived = memoData.state === State.ARCHIVED; const isArchived = memoData.state === State.ARCHIVED;
// In production, only the memo owner (or superuser) can edit/pin. // In production, only the memo owner (or superuser) can edit/pin.
const readonly = memoData.creator !== currentUser?.name && !isSuperUser(currentUser); // When currentUser is undefined (still loading), default to false to allow owner actions
// The backend will validate permissions anyway when actions are taken.
const readonly = currentUser ? (memoData.creator !== currentUser.name && !isSuperUser(currentUser)) : false;
const parentPage = parentPageProp || "/"; const parentPage = parentPageProp || "/";
const { nsfw, showNSFWContent, toggleNsfwVisibility } = useNsfwContent(memoData, props.showNsfwContent); const { nsfw, showNSFWContent, toggleNsfwVisibility } = useNsfwContent(memoData, props.showNsfwContent);
......
...@@ -19,10 +19,10 @@ export interface UseFilteredMemoStatsOptions { ...@@ -19,10 +19,10 @@ export interface UseFilteredMemoStatsOptions {
export const useFilteredMemoStats = (options: UseFilteredMemoStatsOptions = {}): FilteredMemoStats => { export const useFilteredMemoStats = (options: UseFilteredMemoStatsOptions = {}): FilteredMemoStats => {
const { userName } = options; const { userName } = options;
// Always fetch user stats - use provided userName or fallback to default 'users/1' // SECURITY FIX: Only fetch user stats when userName is explicitly provided
// This ensures Tags section always shows data from backend API // Do NOT fallback to 'users/1' as this causes data leakage across different users
const effectiveUserName = userName || "users/1"; const { data: userStats, isLoading: isLoadingUserStats } = useUserStats(userName);
const { data: userStats, isLoading: isLoadingUserStats } = useUserStats(effectiveUserName);
// Fetch memos for additional fallback computation (activity calendar etc) // Fetch memos for additional fallback computation (activity calendar etc)
const { data: memosResponse, isLoading: isLoadingMemos } = useMemos({}); const { data: memosResponse, isLoading: isLoadingMemos } = useMemos({});
......
# Script to push code to GitHub
cd E:\opennotion
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Pushing OpenNotion to GitHub" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# Check git status
Write-Host "[1/5] Checking git status..." -ForegroundColor Yellow
git status
Write-Host ""
# Add all files
Write-Host "[2/5] Adding all files..." -ForegroundColor Yellow
git add .
Write-Host "Files added!" -ForegroundColor Green
Write-Host ""
# Commit changes
Write-Host "[3/5] Committing changes..." -ForegroundColor Yellow
$hasChanges = git diff --cached --quiet
if ($LASTEXITCODE -ne 0) {
git commit -m "Update: OpenNotion project - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Host "Changes committed!" -ForegroundColor Green
} else {
Write-Host "No changes to commit" -ForegroundColor Yellow
}
Write-Host ""
# Check remote
Write-Host "[4/5] Checking remote configuration..." -ForegroundColor Yellow
git remote -v
Write-Host ""
# Push to GitHub
Write-Host "[5/5] Pushing to GitHub..." -ForegroundColor Yellow
Write-Host "Repository: https://github.com/Hoanganhvu123/cuccu_note.git" -ForegroundColor Cyan
Write-Host ""
Write-Host "If this fails, you may need to:" -ForegroundColor Yellow
Write-Host " 1. Authenticate with GitHub (use Personal Access Token)" -ForegroundColor Yellow
Write-Host " 2. Or use: git push -u origin main" -ForegroundColor Yellow
Write-Host ""
git push -u origin main
if ($LASTEXITCODE -eq 0) {
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host " SUCCESS! Code pushed to GitHub!" -ForegroundColor Green
Write-Host " https://github.com/Hoanganhvu123/cuccu_note" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Green
} else {
Write-Host ""
Write-Host "========================================" -ForegroundColor Red
Write-Host " Push failed. Error code: $LASTEXITCODE" -ForegroundColor Red
Write-Host "========================================" -ForegroundColor Red
Write-Host ""
Write-Host "Common issues:" -ForegroundColor Yellow
Write-Host " - Authentication required (use GitHub Personal Access Token)" -ForegroundColor Yellow
Write-Host " - Repository doesn't exist or you don't have access" -ForegroundColor Yellow
Write-Host " - Network connection issue" -ForegroundColor Yellow
Write-Host ""
Write-Host "To fix authentication:" -ForegroundColor Cyan
Write-Host " git config --global credential.helper manager" -ForegroundColor White
Write-Host " Then try pushing again" -ForegroundColor White
}
# Script push code với token
cd E:\opennotion
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Push Code lên GitHub" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# Kiểm tra và thêm file
Write-Host "[1/4] Thêm các file vào git..." -ForegroundColor Yellow
git add .
Write-Host "✓ Đã thêm file" -ForegroundColor Green
Write-Host ""
# Commit
Write-Host "[2/4] Commit changes..." -ForegroundColor Yellow
$hasStaged = git diff --cached --quiet
if ($LASTEXITCODE -ne 0) {
git commit -m "Update: OpenNotion project - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Host "✓ Đã commit" -ForegroundColor Green
} else {
Write-Host "⚠ Không có thay đổi để commit" -ForegroundColor Yellow
}
Write-Host ""
# Kiểm tra remote
Write-Host "[3/4] Kiểm tra remote..." -ForegroundColor Yellow
git remote -v
Write-Host ""
# Push
Write-Host "[4/4] Push lên GitHub..." -ForegroundColor Yellow
Write-Host ""
Write-Host "⚠ Khi được hỏi:" -ForegroundColor Yellow
Write-Host " Username: Hoanganhvu123" -ForegroundColor Cyan
Write-Host " Password: Dán Personal Access Token của bạn" -ForegroundColor Cyan
Write-Host " (KHÔNG phải password GitHub!)" -ForegroundColor Red
Write-Host ""
git push -u origin main
if ($LASTEXITCODE -eq 0) {
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host " ✓ THÀNH CÔNG! Code đã được push!" -ForegroundColor Green
Write-Host " https://github.com/Hoanganhvu123/cuccu_note" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Green
} else {
Write-Host ""
Write-Host "========================================" -ForegroundColor Red
Write-Host " ✗ Push thất bại!" -ForegroundColor Red
Write-Host "========================================" -ForegroundColor Red
Write-Host ""
Write-Host "Có thể do:" -ForegroundColor Yellow
Write-Host " - Token không đúng hoặc đã hết hạn" -ForegroundColor Yellow
Write-Host " - Chưa có quyền truy cập repository" -ForegroundColor Yellow
Write-Host " - Vấn đề kết nối mạng" -ForegroundColor Yellow
Write-Host ""
Write-Host "Xem hướng dẫn tạo token trong file: HUONG_DAN_TAO_TOKEN.md" -ForegroundColor Cyan
}
# Script đồng bộ code lên GitHub
cd E:\opennotion
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Đồng bộ code lên GitHub" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# Kiểm tra thay đổi
Write-Host "[1] Kiểm tra file thay đổi..." -ForegroundColor Yellow
$changes = git status --porcelain
if ($changes) {
Write-Host "Có $($changes.Count) file(s) thay đổi:" -ForegroundColor Green
$changes | ForEach-Object { Write-Host " $_" }
} else {
Write-Host "Không có file thay đổi" -ForegroundColor Gray
}
Write-Host ""
# Add tất cả
Write-Host "[2] Thêm tất cả file..." -ForegroundColor Yellow
git add -A
Write-Host "✓ Đã thêm" -ForegroundColor Green
Write-Host ""
# Commit
Write-Host "[3] Tạo commit..." -ForegroundColor Yellow
$commitMsg = "Update: Sync to GitHub - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
$commitResult = git commit -m $commitMsg 2>&1
if ($LASTEXITCODE -eq 0) {
if ($commitResult -match "nothing to commit") {
Write-Host "⚠ Không có gì để commit" -ForegroundColor Yellow
} else {
Write-Host "✓ Đã commit: $commitMsg" -ForegroundColor Green
Write-Host $commitResult
}
} else {
Write-Host "⚠ Commit không thành công hoặc không có thay đổi" -ForegroundColor Yellow
}
Write-Host ""
# Kiểm tra commits chưa push
Write-Host "[4] Kiểm tra commits chưa push..." -ForegroundColor Yellow
git fetch origin 2>&1 | Out-Null
$unpushed = git log origin/main..HEAD --oneline
if ($unpushed) {
Write-Host "Có $($unpushed.Count) commit(s) chưa push:" -ForegroundColor Yellow
$unpushed | ForEach-Object { Write-Host " $_" }
Write-Host ""
# Push
Write-Host "[5] Push lên GitHub..." -ForegroundColor Yellow
$pushResult = git push origin main 2>&1
Write-Host $pushResult
if ($LASTEXITCODE -eq 0) {
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host " ✓ THÀNH CÔNG! Code đã được push!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Xem tại: https://github.com/Hoanganhvu123/cuccu_note" -ForegroundColor Cyan
} else {
Write-Host ""
Write-Host "========================================" -ForegroundColor Red
Write-Host " ✗ Push thất bại!" -ForegroundColor Red
Write-Host "========================================" -ForegroundColor Red
}
} else {
Write-Host "✓ Không có commits mới - đã đồng bộ với GitHub" -ForegroundColor Green
Write-Host ""
Write-Host "Commit mới nhất trên GitHub:" -ForegroundColor Cyan
git log origin/main --oneline -1
}
Write-Host ""
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment