{"size": 5726, "ext": "js", "max_stars_repo_path": "backend/endpoints/utils/verification.js", "max_stars_repo_name": "MattiHenning/urban-hiking", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "backend/endpoints/utils/verification.js", "max_issues_repo_name": "MattiHenning/urban-hiking", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "backend/endpoints/utils/verification.js", "max_forks_repo_name": "MattiHenning/urban-hiking", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.7927927928, "max_line_length": 77, "alphanum_fraction": 0.6161369193}
const jwt = require('jsonwebtoken')
const { jwtKey } = require('../../config/config')
const logger = require('../../config/winston')
const Group = require('../group/GroupModel')
const GroupService = require('../group/GroupService')
const Message = require('../messages/messageModel')
const User = require('../user/UserModel')
const { getUserbyId } = require('../user/UserService')
const UserService = require('../user/UserService')

const getUserIdFromHeader = (headers) => {
  try {
    let token = headers.authorization.split(' ')[1]

    let encrypt = jwt.verify(token, jwtKey, { salgorithm: 'HS256' })

    return encrypt.user
  } catch (e) {
    throw new Error(e)
  }
}

/* clean */
const verifyIfGroupMember = async (groupId, userId, group) => {
  if (group) {
    return group.members.includes(userId) || userId == 'SuperAdmin@admin.com'
  } else {
    let group = await GroupService.getGroupById(groupId)
    return group.members.includes(userId) || userId == 'SuperAdmin@admin.com'
  }
}

const verifyIfGroupOwner = async (groupId, userId, group) => {
  logger.info('start to check if group owner')

  let isGroupOwner

  if (!group) {
    group = await GroupService.getGroupById(groupId)

    if (!group) {
      res.status(404).send()
    }
  }
  isGroupOwner = group.groupOwner === userId
  return isGroupOwner
}

const verifyIfAdmin = (req, res, next) => {
  logger.info('start to verify admin')
  if (typeof req.headers.authorization !== 'undefined') {
    let token = req.headers.authorization.split(' ')[1]
    jwt.verify(token, jwtKey, { algorithm: 'HS256' }, (err, decoded) => {
      if (err) {
        return res.status(500).json({ error: 'Not Authorized' })
      } else {
        UserService.getUserbyId(decoded.user, (err, user) => {
          if (err) {
            return res.status(500).json({ error: 'Not Authorized' })
          } else if (!user.isAdministrator) {
            return res
              .status(500)
              .json({ error: 'Not Authorized - you need admin-rights' })
          } else {
            logger.info('verifyd as admin')
            next()
          }
        })
      }
    })
  } else {
    return res.status(500).json({ error: 'Not Authorized' })
  }
}

const verifyIfOwner = (req, res, next) => {
  logger.info('start to verify')
  if (typeof req.headers.authorization !== 'undefined') {
    let token = req.headers.authorization.split(' ')[1]
    jwt.verify(token, jwtKey, { algorithm: 'HS256' }, (err, decoded) => {
      if (err) {
        return res.status(500).json({ error: 'Not Authorized' })
      } else {
        UserService.getUserbyId(decoded.user, (err, user) => {
          if (err) {
            return res.status(500).json({ error: 'Not Authorized' })
          } else if (user.isAdministrator) {
            logger.info('verifyd as owner or admin')
            next()
          } else if (!(user.userID === req.params.id)) {
            return res
              .status(500)
              .json({ error: 'Not Authorized - you need admin-rights' })
          } else {
            logger.info('verifyd as owner or admin')
            next()
          }
        })
      }
    })
  } else {
    return res.status(500).json({ error: 'Not Authorized' })
  }
}

/* Alternative Middleware to VerifyIfGroupOwner */
const checkIfGroupOwner = async (req, res, next) => {
  let group = req.group
  let userId = getUserIdFromHeader(req.headers)
  req.userId = userId
  let isOwner

  if (!group) {
    res.status(404)
  } else {
    isOwner = group.groupOwner == userId || userId == 'SuperAdmin@admin.com'
    if (isOwner) {
      next()
    } else {
      res.send(403)
    }
  }
}

/* Alternative Middleware to VerfyIfGroupMember */
const checkIfGroupMember = async (req, res, next) => {
  let group = req.group
  let userId = getUserIdFromHeader(req.headers)
  req.userId = userId

  if (!group) {
    res.send(500)
  } else if (group.members.includes(userId)) {
    next()
  } else {
    res.send(500)
  }
}

const checkIfUserExist = async (userId) => {
  logger.info('check if user exists')
  const user = await User.findOne({
    userID: userId,
  })

  if (!user) {
    return false
  } else {
    return true
  }
}

const checkIfGroupExist = async (groupId) => {
  const group = await Group.findOne({
    title: groupId,
  })

  if (!group) {
    return false
  } else {
    return true
  }
}

const checkIfMessageExist = async (messageId) => {
  const message = await Message.findOne({
    messageId: messageId,
  })
  if (!message) {
    return false
  } else {
    return true
  }
}

const checkIfRecipientExist = async (req, res, next) => {
  logger.info('check if User exists')
  req.userId = getUserIdFromHeader(req.headers)

  let recipient = req.body.recipient
  if (!recipient) {
    res.status(404).send()
  } else {
    if (req.body.privateMessage && (await checkIfUserExist(recipient))) {
      next()
    } else if (
      !req.body.privateMessage &&
      (await checkIfGroupExist(recipient))
    ) {
      next()
    } else {
      logger.error('no access ritghs')
      res.status(404).send('No access-right or user or group does not exist')
    }
  }
}

const checkIfRelatedToMessage = async (userId, message) => {
  let isDirectRelated =
    message.author === userId || message.recipient === userid

  if (message.privateMessage === false) {
    let isGroupMember = await verifyIfGroupMember(message.messageId, userId)
  }

  return isDirectRelated || isGroupMember
}

module.exports = {
  getUserIdFromHeader,
  verifyIfGroupMember,
  verifyIfAdmin,
  verifyIfOwner,
  verifyIfGroupOwner,
  checkIfGroupOwner,
  checkIfGroupMember,
  checkIfRecipientExist,
  checkIfGroupExist,
  checkIfMessageExist,
  checkIfRelatedToMessage,
}
