import debug from 'debug'

const log = debug('www:middlewares:authentifier')

export function isAuthentified (req, res, next) {
  return check(req, res, next,
    req.session.account !== undefined)
}

export function isAdmin (req, res, next) {
  return check(req, res, next,
    req.session.account && req.session.account.admin === true)
}

function check (req, res, next, condition) {
  if (!condition) {
    log('Unauthorized access')

    const api = req.originalUrl.startsWith('/api')

    if (api) {
      return res.status(401)
        .json({ message: 'You don\'t have permission to access this endpoint' })
    }

    const authentified = req.session.account !== undefined

    if (authentified) {
      return next({
        status: 403,
        message: `Vous n'avez pas les permissions requises pour effectuer cette action.`
      })
    }

    // backup current URL in order to redirect after sign in
    req.session.redirectUrl = req.originalUrl

    return res.redirect('/accounts/sign-in')
  }

  log('Access granted')

  next()
}
