58 lines
1.6 KiB
TypeScript
58 lines
1.6 KiB
TypeScript
import { GetServerSideProps } from 'next'
|
|
import axios from 'axios'
|
|
|
|
export const getServerSideProps: GetServerSideProps = async (context) => {
|
|
const { res, req, query } = context
|
|
const { jid, instance } = query
|
|
|
|
// 1. Extrai o token de acesso do cookie seguro pré-processado pelo Next.js
|
|
const token = req.cookies['accessToken'] || ''
|
|
|
|
if (!jid || !instance) {
|
|
res.statusCode = 204
|
|
res.end()
|
|
return { props: {} }
|
|
}
|
|
|
|
// 2. Faz o fetch da imagem no backend original, passando o token no Header
|
|
try {
|
|
const apiBase = (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8008').replace(/\/$/, '')
|
|
|
|
const response = await axios.get(`${apiBase}/api/inbox/avatar/${encodeURIComponent(jid as string)}`, {
|
|
params: { instance },
|
|
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
|
responseType: 'arraybuffer',
|
|
validateStatus: () => true,
|
|
})
|
|
|
|
// 3. Devolve os headers e os bytes da imagem para o navegador de forma transparente (Proxy)
|
|
res.statusCode = response.status
|
|
|
|
if (response.headers['content-type']) {
|
|
res.setHeader('Content-Type', response.headers['content-type'])
|
|
} else {
|
|
res.setHeader('Content-Type', 'image/jpeg')
|
|
}
|
|
|
|
if (response.headers['cache-control']) {
|
|
res.setHeader('Cache-Control', response.headers['cache-control'])
|
|
}
|
|
|
|
if (response.headers['etag']) {
|
|
res.setHeader('ETag', response.headers['etag'])
|
|
}
|
|
|
|
res.write(Buffer.from(response.data))
|
|
res.end()
|
|
} catch (err) {
|
|
res.statusCode = 204
|
|
res.end()
|
|
}
|
|
|
|
return { props: {} }
|
|
}
|
|
|
|
export default function ProxyAvatarPage() {
|
|
return null
|
|
}
|