1
+ const Post = require ( '../models/Post' )
2
+ const Comment = require ( '../models/Comment' )
3
+
4
+ exports . isLoggedIn = ( req , res , next ) => {
5
+ if ( req . isAuthenticated ( ) ) {
6
+ next ( )
7
+ } else {
8
+ req . flash ( 'error' , 'You must be logged' )
9
+ res . redirect ( '/login' )
10
+ }
11
+ }
12
+
13
+ // check ownership
14
+ exports . isOwnerPost = async ( req , res , next ) => {
15
+ if ( req . isAuthenticated ( ) ) {
16
+ try {
17
+ // find post by id
18
+ const post = await Post . findById ( req . params . id )
19
+
20
+ if ( ! post ) {
21
+ // if not found the post
22
+ req . flash ( 'error' , 'Post not found' )
23
+ return res . redirect ( 'back' )
24
+ } else {
25
+ // check ownership
26
+ if ( post . userId . equals ( req . user . _id ) ) {
27
+ // same ids
28
+ next ( )
29
+ } else {
30
+ // not same ids
31
+ req . flash ( 'error' , "You don't have permission" )
32
+ return res . redirect ( 'back' )
33
+ }
34
+ }
35
+ } catch ( err ) {
36
+ req . flash ( 'error' , 'Something went wrong' )
37
+ return res . redirect ( 'back' )
38
+ }
39
+ } else {
40
+ req . flash ( 'error' , 'You must be logged in' )
41
+ res . redirect ( 'back' )
42
+ }
43
+ }
44
+
45
+ exports . checkOwnershipComment = async ( req , res , next ) => {
46
+ if ( req . isAuthenticated ( ) ) {
47
+ try {
48
+ // find post and comment
49
+ const post = await Post . findById ( req . params . id )
50
+ const comment = await Comment . findById ( req . params . commentId )
51
+ // not found comment or post
52
+ if ( ! comment || ! post ) {
53
+ req . flash ( 'error' , 'Something went wrong' )
54
+ return res . redirect ( 'back' )
55
+ }
56
+ // check ownership of comment
57
+ if ( comment . author . id . equals ( req . user . _id ) ) {
58
+ next ( )
59
+ } else {
60
+ // dont have permisson
61
+ req . flash ( 'error' , "You don't have permission" )
62
+ return res . redirect ( 'back' )
63
+ }
64
+ } catch ( err ) {
65
+ console . log ( err )
66
+ return res . redirect ( 'back' )
67
+ }
68
+ } else {
69
+ req . flash ( 'error' , 'You must be logged in' )
70
+ return res . redirect ( 'back' )
71
+ }
72
+ }
0 commit comments