67 lines
1.8 KiB
TypeScript
67 lines
1.8 KiB
TypeScript
import { query, execute } from './db'
|
|
|
|
const config = useRuntimeConfig()
|
|
|
|
/**
|
|
* Google Access Token 갱신
|
|
*/
|
|
export async function refreshGoogleToken(employeeId: number): Promise<string | null> {
|
|
// 현재 토큰 정보 조회
|
|
const rows = await query<any>(`
|
|
SELECT google_access_token, google_refresh_token, google_token_expires_at
|
|
FROM wr_employee_info
|
|
WHERE employee_id = $1
|
|
`, [employeeId])
|
|
|
|
const employee = rows[0]
|
|
if (!employee?.google_refresh_token) {
|
|
return null
|
|
}
|
|
|
|
// 토큰이 아직 유효하면 그대로 반환 (5분 여유)
|
|
const expiresAt = new Date(employee.google_token_expires_at)
|
|
if (expiresAt.getTime() > Date.now() + 5 * 60 * 1000) {
|
|
return employee.google_access_token
|
|
}
|
|
|
|
// 토큰 갱신
|
|
try {
|
|
const res = await fetch('https://oauth2.googleapis.com/token', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
body: new URLSearchParams({
|
|
client_id: config.googleClientId,
|
|
client_secret: config.googleClientSecret,
|
|
refresh_token: employee.google_refresh_token,
|
|
grant_type: 'refresh_token'
|
|
})
|
|
})
|
|
|
|
const data = await res.json()
|
|
if (!data.access_token) {
|
|
console.error('Token refresh failed:', data)
|
|
return null
|
|
}
|
|
|
|
// 새 토큰 저장
|
|
await execute(`
|
|
UPDATE wr_employee_info SET
|
|
google_access_token = $1,
|
|
google_token_expires_at = NOW() + INTERVAL '${data.expires_in} seconds'
|
|
WHERE employee_id = $2
|
|
`, [data.access_token, employeeId])
|
|
|
|
return data.access_token
|
|
} catch (e) {
|
|
console.error('Token refresh error:', e)
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 유효한 Google Access Token 조회 (자동 갱신)
|
|
*/
|
|
export async function getValidGoogleToken(employeeId: number): Promise<string | null> {
|
|
return refreshGoogleToken(employeeId)
|
|
}
|