All files / lib/controllers admin.ts

16.26% Statements 40/246
0% Branches 0/70
2% Functions 1/50
16.46% Lines 40/243

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494            16x 16x 16x 16x 16x 16x 16x   16x                                                                                                                                 16x       16x           16x 16x                 16x 16x 16x                               16x                             16x                                               16x 16x                                                 16x 16x 16x                                                                                         16x                                 16x                         16x                         16x                         16x                           16x           16x                             16x                           16x                             16x 16x                           16x                                                   16x                                         16x                               16x                                                                                                             16x 16x               16x    
import Crowi from 'server/crowi'
import Debug from 'debug'
import ApiResponse from '../util/apiResponse'
import { UserDocument } from 'server/models/user'
 
export default (crowi: Crowi) => {
  const debug = Debug('crowi:routes:admin')
  const models = crowi.models
  const User = models.User
  const Config = models.Config
  const MAX_PAGE_LIST = 5
  const actions = {} as any
  actions.api = {} as any
 
  const searchEvent = crowi.event('Search')
 
  function createPager(total, limit, page, pagesCount, maxPageList) {
    const pager: {
      page: any
      pagesCount: number
      pages: number[]
      total: number
      previous: number | null
      previousDots: boolean | null
      next: number | null
      nextDots: boolean | null
    } = {
      page,
      pagesCount,
      pages: [],
      total,
      previous: null,
      previousDots: false,
      next: null,
      nextDots: false,
    }
 
    if (page > 1) {
      pager.previous = page - 1
    }
 
    if (page < pagesCount) {
      pager.next = page + 1
    }
 
    let pagerMin = Math.max(1, Math.ceil(page - maxPageList / 2))
    let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList / 2))
    if (pagerMin === 1) {
      if (MAX_PAGE_LIST < pagesCount) {
        pagerMax = MAX_PAGE_LIST
      } else {
        pagerMax = pagesCount
      }
    }
    if (pagerMax === pagesCount) {
      if (pagerMax - MAX_PAGE_LIST < 1) {
        pagerMin = 1
      } else {
        pagerMin = pagerMax - MAX_PAGE_LIST
      }
    }
 
    pager.previousDots = null
    if (pagerMin > 1) {
      pager.previousDots = true
    }
 
    pager.nextDots = null
    if (pagerMax < pagesCount) {
      pager.nextDots = true
    }
 
    for (let i = pagerMin; i <= pagerMax; i++) {
      pager.pages.push(i)
    }
 
    return pager
  }
 
  actions.index = function(req, res) {
    return res.render('admin')
  }
 
  actions.api.index = function(req, res) {
    const searcher = crowi.getSearcher()
 
    return res.json(ApiResponse.success({ searchConfigured: !!searcher }))
  }
 
  actions.api.app = {}
  actions.api.app.index = async function(req, res) {
    const config = crowi.getConfig()
    const settingForm = config.crowi
    const registrationMode = Config.getRegistrationModeLabels()
    const isUploadable = Config.isUploadable(config)
 
    return res.json(ApiResponse.success({ settingForm, registrationMode, isUploadable }))
  }
 
  actions.notification = {}
  actions.api.notification = {}
  actions.api.notification.index = async function(req, res) {
    const config = crowi.getConfig()
    const UpdatePost = crowi.model('UpdatePost')
    const hasSlackConfig = Config.hasSlackConfig(config)
    const hasSlackToken = Config.hasSlackToken(config)
    const slack = crowi.slack
    const appUrl = config.crowi['app:url']
 
    const defaultSlackSetting = { 'slack:clientId': '', 'slack:clientSecret': '' }
    const slackSetting = hasSlackConfig ? config.notification : defaultSlackSetting
    const slackAuthUrl = hasSlackConfig ? slack.getAuthorizeURL() : ''
 
    const settings = await UpdatePost.findAll()
    return res.json(ApiResponse.success({ settings, slackSetting, hasSlackConfig, hasSlackToken, slackAuthUrl, appUrl }))
  }
 
  actions.api.notification.slackSetting = async function(req, res) {
    const { slackSetting } = req.form
 
    if (!req.form.isValid) {
      return res.json(ApiResponse.error(req.form.errors.join('\n')))
    }
 
    try {
      await Config.updateConfigByNamespace('notification', slackSetting)
      return res.json(ApiResponse.success({ message: 'Updated Slack setting.' }))
    } catch (err) {
      return res.json(ApiResponse.error(err.message))
    }
  }
 
  actions.notification.slackAuth = async function(req, res) {
    const code = req.query.code
 
    if (!code || !Config.hasSlackConfig(req.config)) {
      return res.redirect('/admin/notification')
    }
 
    const slack = crowi.slack
    try {
      const token = await slack.getOauthAccessToken(code)
      try {
        Config.updateConfigByNamespace('notification', { 'slack:token': token })
        req.flash('successMessage', ['Successfully Connected!'])
      } catch (err) {
        req.flash('errorMessage', ['Failed to save access_token. Please try again.'])
      }
      return res.redirect('/admin/notification')
    } catch (error) {
      debug('oauth response ERROR', error)
      req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.'])
      return res.redirect('/admin/notification')
    }
  }
 
  actions.api.search = {}
  actions.api.search.buildIndex = async function(req, res) {
    const search = crowi.getSearcher()
    if (!search) {
      return res.json(ApiResponse.error('Searcher is not ready.'))
    }
 
    searchEvent.on('addPageProgress', (total, current, skip) => {
      crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip })
    })
    searchEvent.on('finishAddPage', (total, current, skip) => {
      crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip })
    })
 
    search
      .buildIndex()
      .then(() => {
        debug('Data is successfully indexed. ------------------ ✧✧')
      })
      .catch(err => {
        debug('Error caught.', err)
      })
 
    return res.json(ApiResponse.success({ message: 'Now re-building index ... this takes a while.' }))
  }
 
  actions.user = {}
  actions.api.user = {}
  actions.api.user.index = function(req, res) {
    var page = parseInt(req.query.page) || 1
 
    // uq means user query
    // q used by search box on header
    const uq = req.query.uq
    const query: {
      $or?: any
    } = {}
 
    if (uq) {
      const $regex = uq.trim().replace(' ', '|')
      query.$or = ['username', 'name', 'email'].map(v => ({
        [v]: {
          $regex,
          $options: 'i',
        },
      }))
    }
 
    User.findUsersWithPagination({ page: page }, query, (err, result) => {
      if (err) {
        debug(err)
        return res.json(
          ApiResponse.success({
            users: [],
            pager: null,
            uq: uq,
            error: err.message,
          }),
        )
      }
 
      const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST)
 
      return res.json(
        ApiResponse.success({
          users: result.docs,
          pager: pager,
          uq,
        }),
      )
    })
  }
 
  actions.api.user.invite = function(req, res) {
    const { emailList, sendEmail } = req.form.inviteForm
    const toSendEmail = sendEmail || false
 
    if (!req.form.isValid) {
      return res.json(ApiResponse.error(req.form.errors.join('\n')))
    }
 
    User.createUsersByInvitation(emailList.split('\n'), toSendEmail, function(err, userList) {
      if (err === null) {
        return res.json(ApiResponse.success({ userList }))
      }
      debug(err, userList)
      return res.json(ApiResponse.error('招待に失敗しました。'))
    })
  }
 
  actions.api.user.makeAdmin = function(req, res) {
    var id = req.params.id
    User.findById(id, function(err, userData) {
      ;(userData as UserDocument).makeAdmin(function(err, userData) {
        if (err === null) {
          return res.json(ApiResponse.success({ message: `${userData.name}さんのアカウントを管理者に設定しました。` }))
        }
        debug(err, userData)
        return res.json(ApiResponse.error('更新に失敗しました。'))
      })
    })
  }
 
  actions.api.user.removeFromAdmin = function(req, res) {
    var id = req.params.id
    User.findById(id, function(err, userData) {
      ;(userData as UserDocument).removeFromAdmin(function(err, userData) {
        if (err === null) {
          return res.json(ApiResponse.success({ message: `${userData.name}さんのアカウントを管理者から外しました。` }))
        }
        debug(err, userData)
        return res.json(ApiResponse.error('更新に失敗しました。'))
      })
    })
  }
 
  actions.api.user.activate = function(req, res) {
    var id = req.params.id
    User.findById(id, function(err, userData) {
      ;(userData as UserDocument).statusActivate(function(err, userData) {
        if (err === null) {
          return res.json(ApiResponse.success({ message: `${userData.name}さんのアカウントを承認しました。` }))
        }
        debug(err, userData)
        return res.json(ApiResponse.error('更新に失敗しました。'))
      })
    })
  }
 
  actions.api.user.suspend = function(req, res) {
    var id = req.params.id
 
    User.findById(id, function(err, userData) {
      ;(userData as UserDocument).statusSuspend(function(err, userData) {
        if (err === null) {
          return res.json(ApiResponse.success({ message: `${userData.name}さんのアカウントを利用停止にしました。` }))
        }
        debug(err, userData)
        return res.json(ApiResponse.error('更新に失敗しました。'))
      })
    })
  }
 
  actions.user.remove = function(req, res) {
    // 未実装
    return res.redirect('/admin/users')
  }
 
  // これやったときの relation の挙動未確認
  actions.user.removeCompletely = function(req, res) {
    // ユーザーの物理削除
    var id = req.params.id
 
    User.removeCompletelyById(id, function(err, removed) {
      if (err) {
        debug('Error while removing user.', err, id)
        req.flash('errorMessage', '完全な削除に失敗しました。')
      } else {
        req.flash('successMessage', '削除しました')
      }
      return res.redirect('/admin/users')
    })
  }
 
  actions.api.user.resetPassword = function(req, res) {
    const id = req.body.user_id
    const User = crowi.model('User')
 
    User.resetPasswordByRandomString(id)
      .then(function(data) {
        return res.json(ApiResponse.success(data))
      })
      .catch(function(err) {
        debug('Error on reseting password', err)
        return res.json(ApiResponse.error('Error'))
      })
  }
 
  actions.api.user.updateEmail = async function(req, res) {
    const { user_id: id, email } = req.body
    const User = crowi.model('User')
 
    try {
      const user = await User.findById(id)
      if (!user) throw new Error('User not found')
      await user.updateEmail(email)
      return res.json(ApiResponse.success())
    } catch (err) {
      debug('Error on updating email', err)
      return res.json(ApiResponse.error('Error'))
    }
  }
 
  actions.api.top = {}
  actions.api.top.index = function(req, res) {
    const { version: crowiVersion } = crowi
    const searcher = crowi.getSearcher()
    const searchInfo = searcher
      ? {
          host: searcher.host,
          indexName: searcher.indexName,
          esVersion: searcher.esVersion,
        }
      : {}
 
    return res.json(ApiResponse.success({ crowiVersion, searchInfo }))
  }
 
  actions.api.postSettings = function(req, res) {
    const form = req.form.settingForm
 
    if (req.form.isValid) {
      debug('form content', form)
 
      // mail setting ならここで validation
      if (form['mail:from']) {
        validateMailSetting(req, form, function(err, data) {
          debug('Error validate mail setting: ', err, data)
          if (err) {
            req.form.errors.push('SMTPを利用したテストメール送信に失敗しました。設定をみなおしてください。')
            return res.json(ApiResponse.error(req.form.errors.join('\n')))
          }
          return saveSetting(req, res, form)
        })
      }
      if (form['auth:disablePasswordAuth'] && !req.user.hasValidThirdPartyId()) {
        return res.json(ApiResponse.error('パスワードによるログインを禁止するには管理者が有効な外部サービスと連携している必要があります。'))
      }
      return saveSetting(req, res, form)
    } else {
      return res.json(ApiResponse.error(req.form.errors.join('\n')))
    }
  }
 
  actions.api.notificationAdd = function(req, res) {
    var UpdatePost = crowi.model('UpdatePost')
    var pathPattern = req.body.pathPattern
    var channel = req.body.channel
 
    debug('notification.add', pathPattern, channel)
    UpdatePost.createUpdatePost(pathPattern, channel, req.user)
      .then(function(doc) {
        debug('Successfully save updatePost', doc)
 
        // fixme: うーん
        doc.creator = ((doc.creator as any) as UserDocument)._id.toString() as any
        return res.json(ApiResponse.success({ updatePost: doc }))
      })
      .catch(function(err) {
        debug('Failed to save updatePost', err)
        return res.json(ApiResponse.error())
      })
  }
 
  // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  actions.api.notificationRemove = async function(req, res) {
    const UpdatePost = crowi.model('UpdatePost')
    const id = req.body.id
 
    try {
      await UpdatePost.findOneAndRemove({ _id: id })
      debug('Successfully remove updatePost')
 
      return res.json(ApiResponse.success({}))
    } catch (err) {
      debug('Failed to remove updatePost', err)
      return res.json(ApiResponse.error())
    }
  }
 
  // app.get('/_api/admin/users.search' , admin.api.userSearch);
  actions.api.usersSearch = function(req, res) {
    const User = crowi.model('User')
    const email = req.query.email
 
    User.findUsersByPartOfEmail(email, {})
      .then(users => {
        const result = {
          data: users,
        }
        return res.json(ApiResponse.success(result))
      })
      .catch(err => {
        return res.json(ApiResponse.error())
      })
  }
 
  function saveSetting(req, res, form) {
    Config.updateConfigByNamespace('crowi', form)
    return res.json(ApiResponse.success())
  }
 
  function validateMailSetting(req, form, callback) {
    const mailer = crowi.mailer
    const option: {
      host: string
      port: number
      auth?: any
      secure?: boolean
    } = {
      host: form['mail:smtpHost'],
      port: form['mail:smtpPort'],
    }
    if (form['mail:smtpUser'] && form['mail:smtpPassword']) {
      option.auth = {
        user: form['mail:smtpUser'],
        pass: form['mail:smtpPassword'],
      }
    }
    if (option.port === 465) {
      option.secure = true
    }
 
    var smtpClient = mailer.createSMTPClient(option)
    debug('mailer setup for validate SMTP setting', smtpClient)
 
    smtpClient.sendMail(
      {
        to: req.user.email,
        subject: 'Wiki管理設定のアップデートによるメール通知',
        text: 'このメールは、WikiのSMTP設定のアップデートにより送信されています。',
      },
      callback,
    )
  }
 
  actions.api.backlink = {}
  actions.api.backlink.buildBacklinks = function(req, res) {
    const Backlink = crowi.model('Backlink')
    // In background
    Backlink.createByAllPages()
 
    return res.json(ApiResponse.success({ message: 'Now re-building backlinks ... this takes a while.' }))
  }
 
  return actions
}