Skip to content

Commit 5d91fd9

Browse files
committed
fix: button only appears if authenticated user is the owner of the post
1 parent fc9ff57 commit 5d91fd9

File tree

2 files changed

+88
-28
lines changed

2 files changed

+88
-28
lines changed

components/post.js

Lines changed: 57 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import Content from './content'
77
import Video from './video'
88
import Image from 'next/image'
99
import Reaction from './reaction'
10-
import { useState } from 'react'
10+
import { useState, useEffect } from 'react'
1111
import EmojiPicker from 'emoji-picker-react'
1212

1313
const imageFileTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp']
@@ -34,31 +34,44 @@ const Post = ({
3434
displayStreak: false,
3535
streakCount: 0
3636
},
37+
sessionID = 'abc',
3738
text,
3839
attachments = [],
3940
mux = [],
4041
reactions = [],
4142
postedAt,
4243
slackUrl,
4344
muted = false,
44-
openEmojiPicker = () => {},
45+
openEmojiPicker = () => { },
4546
authStatus,
4647
swrKey,
4748
authSession
4849
}) => {
4950
const [isVisible, setIsVisible] = useState(true);
50-
51+
const [sessionUserId, setSessionUserId] = useState(null);
52+
53+
useEffect(() => {
54+
if (authStatus === 'authenticated') {
55+
const fetchSessionUserID = async () => {
56+
const id = await getSessionUserID(user.id);
57+
setSessionUserId(id);
58+
};
59+
fetchSessionUserID();
60+
}
61+
}, [user.id, authStatus]);
62+
63+
5164
const deletePost = async (id) => {
5265
try {
5366
const response = await fetch('/api/web/post/delete', {
5467
method: 'DELETE',
5568
headers: {
5669
'Content-Type': 'application/json',
5770
},
58-
body: JSON.stringify({ id })
71+
body: JSON.stringify({ id })
5972
});
6073
const responseText = await response.text()
61-
if (responseText.includes("Post Deleted")){
74+
if (responseText.includes("Post Deleted")) {
6275
setIsVisible(false);
6376
}
6477
} catch (error) {
@@ -67,7 +80,7 @@ const Post = ({
6780
};
6881

6982
if (!isVisible) {
70-
return null;
83+
return null;
7184
}
7285

7386
return (
@@ -107,11 +120,10 @@ const Post = ({
107120
<span className="post-header-name">
108121
<strong>@{user.username}</strong>
109122
<span
110-
className={`badge post-header-streak ${
111-
!user.displayStreak || user.streakCount === 0
112-
? 'header-streak-zero'
113-
: ''
114-
}`}
123+
className={`badge post-header-streak ${!user.displayStreak || user.streakCount === 0
124+
? 'header-streak-zero'
125+
: ''
126+
}`}
115127
title={`${user.streakCount}-day streak`}
116128
>
117129
{`${user.streakCount <= 7 ? user.streakCount : '7+'}`}
@@ -182,28 +194,45 @@ const Post = ({
182194
</div>
183195
)}
184196
<footer className="post-reactions" aria-label="Emoji reactions">
185-
<div style={{ display: 'flex', flexWrap: 'wrap', flexGrow: 1 }}>
186-
{reactions.map(reaction => (
187-
<Reaction
188-
key={id + reaction.name}
189-
{...reaction}
190-
postID={id}
191-
authStatus={authStatus}
192-
authSession={authSession}
193-
swrKey={swrKey}
194-
/>
195-
))}
196-
{authStatus == 'authenticated' && (
197-
<div className="post-reaction" onClick={() => openEmojiPicker(id)}>
198-
+
199-
</div>
200-
)}
197+
<div style={{ display: 'flex', flexWrap: 'wrap', flexGrow: 1 }}>
198+
{reactions.map(reaction => (
199+
<Reaction
200+
key={id + reaction.name}
201+
{...reaction}
202+
postID={id}
203+
authStatus={authStatus}
204+
authSession={authSession}
205+
swrKey={swrKey}
206+
/>
207+
))}
208+
{authStatus == 'authenticated' && (
209+
<div className="post-reaction" onClick={() => openEmojiPicker(id)}>
210+
+
211+
</div>
212+
)}
201213
</div>
202-
<Icon glyph="delete" size={32} className="delete-button post-reaction" onClick={() => deletePost(id)} />
214+
{( authStatus == 'authenticated' && sessionUserId === user.id) && <Icon glyph="delete" size={32} className="delete-button post-reaction" onClick={() => deletePost(id)} />}
203215
</footer>
204216
</section>
205217
</>
206218
)
207219
}
208220

209221
export default Post
222+
223+
const getSessionUserID = async (id) => {
224+
try {
225+
const response = await fetch('/api/web/session/get', {
226+
method: 'POST',
227+
headers: {
228+
'Content-Type': 'application/json',
229+
},
230+
body: JSON.stringify({ id })
231+
});
232+
233+
const responseText = JSON.parse(await response.text());
234+
return responseText.message;
235+
} catch (error) {
236+
console.error('Error:', error);
237+
}
238+
}

pages/api/web/session/get.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { getServerSession } from 'next-auth/next';
2+
import { authOptions } from '../../auth/[...nextauth]';
3+
import prisma from '../../../../lib/prisma';
4+
5+
export default async (req, res) => {
6+
const session = await getServerSession(req, res, authOptions);
7+
8+
if (!session?.user) {
9+
console.log('Unauthorized access attempt');
10+
return res.status(401).send({ message: "Unauthorized" });
11+
}
12+
13+
try {
14+
const update = await prisma.session.findFirst({
15+
where: {
16+
userId: req.body.id
17+
},
18+
orderBy: {
19+
expires: 'desc'
20+
}
21+
});
22+
if (update) {
23+
const userId = update.userId;
24+
return res.status(200).send({ message: userId });
25+
}
26+
return res.status(200).send({ message: false });
27+
} catch (e) {
28+
console.error('Error deleting post:', e);
29+
return res.status(500).json({ error: true, message: 'Internal Server Error' });
30+
}
31+
};

0 commit comments

Comments
 (0)