import { DatabaseResultSet , query } from "../../db/database-query" ; import { checkTokenValidityFromJWT } from "../AuthMiddleware" ; import { Request } from "express" ; import { getStudiesFromTopic } from "../../utilities/TopicsUtils" ; export interface PostAccessType { canEdit : boolean ; canSave : boolean ; } export const hasAccessToTopicRequest = ( topicHash , req ) : Promise < PostAccessType > => { if ( req . cookies === null ) { return Promise . resolve ( { canEdit : false , canSave : false } ) ; } return hasAccessToTopicJWT ( topicHash , req . cookies [ "token" ] ) ; } ; export const hasAccessToTopicJWT = ( topicHash , jwt ) : Promise < PostAccessType > => { const tokenResult = checkTokenValidityFromJWT ( jwt ) ; if ( ! tokenResult ) { return Promise . resolve ( { canEdit : false , canSave : false } ) ; } if ( tokenResult . user . admin ) { return Promise . resolve ( { canEdit : true , canSave : true } ) ; } return getStudiesFromTopic ( topicHash ) . then ( ( studies ) => { for ( const study of studies ) { const isStudyAdmin = tokenResult . user . studies . map ( ( currStudy ) => currStudy . id ) . includes ( study . id ) ; if ( isStudyAdmin ) { return { canEdit : true , canSave : true } ; } } return { canEdit : true , canSave : false } ; } ) ; } ; export const hasAccessToPostRequest = ( postHash , req ) : Promise < PostAccessType > => { if ( req . cookies === null ) { return Promise . resolve ( { canEdit : false , canSave : false } ) ; } return hasAccessToPostJWT ( postHash , req . cookies [ "token" ] ) ; } ; export const hasAccessToPostJWT = ( postHash , jwt ) : Promise < PostAccessType > => { return query ( `
      SELECT deleted, t.hash
      FROM posts p
        INNER JOIN topics t on p.topic = t.id
      WHERE p.hash = ?
    ` , postHash ) . then ( ( databaseResult ) => { if ( databaseResult . getNumberFromDB ( "deleted" ) === 1 ) { return { canEdit : false , canSave : false } ; } return hasAccessToTopicJWT ( databaseResult . getNumberFromDB ( "hash" ) , jwt ) ; } ) ; } ;