2023-05-22 07:20:48 -05:00
// Copyright (C) 2022-present Daniel31x13 <daniel31x13@gmail.com>
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
import type { NextApiRequest , NextApiResponse } from "next" ;
import { getServerSession } from "next-auth/next" ;
import { authOptions } from "pages/api/auth/[...nextauth]" ;
2023-05-22 23:08:16 -05:00
import { prisma } from "@/lib/api/db" ;
2023-05-22 07:20:48 -05:00
import path from "path" ;
import fs from "fs" ;
export default async function ( req : NextApiRequest , res : NextApiResponse ) {
const session = await getServerSession ( req , res , authOptions ) ;
2023-05-22 23:08:16 -05:00
const userId = session ? . user . id ;
const userEmail = session ? . user . email ;
const queryId = Number ( req . query . id ) ;
if ( ! queryId )
2023-05-23 18:07:26 -05:00
return res
. setHeader ( "Content-Type" , "text/plain" )
. status ( 401 )
. send ( "Invalid parameters." ) ;
2023-05-22 23:08:16 -05:00
if ( ! userId || ! userEmail )
2023-05-23 18:07:26 -05:00
return res
. setHeader ( "Content-Type" , "text/plain" )
. status ( 401 )
. send ( "You must be logged in." ) ;
2023-05-22 07:20:48 -05:00
2023-05-22 23:08:16 -05:00
if ( userId !== queryId ) {
const targetUser = await prisma . user . findUnique ( {
where : {
id : queryId ,
} ,
} ) ;
if (
targetUser ? . isPrivate &&
! targetUser . whitelistedUsers . includes ( userEmail )
) {
2023-05-23 18:07:26 -05:00
return res
. setHeader ( "Content-Type" , "text/plain" )
. status ( 401 )
. send ( "This profile is private." ) ;
2023-05-22 23:08:16 -05:00
}
}
2023-05-22 07:20:48 -05:00
const filePath = path . join (
process . cwd ( ) ,
2023-05-22 23:08:16 -05:00
` data/uploads/avatar/ ${ queryId } .jpg `
2023-05-22 07:20:48 -05:00
) ;
console . log ( filePath ) ;
const file = fs . existsSync ( filePath )
? fs . readFileSync ( filePath )
: "File not found." ;
2023-05-23 18:07:26 -05:00
if ( ! fs . existsSync ( filePath ) ) res . setHeader ( "Content-Type" , "text/plain" ) ;
else res . setHeader ( "Content-Type" , "image/jpeg" ) ;
2023-05-22 07:20:48 -05:00
return res . send ( file ) ;
}