All files / lib/controllers login.ts

8.46% Statements 22/260
0% Branches 0/147
2.63% Functions 1/38
8.46% Lines 22/260

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                          16x 16x 16x 16x 16x 16x 16x   16x                         16x           16x                       16x                   16x                           16x                           16x                           16x                               16x                                                                                                                               16x                                                                           16x                                                                           16x                                                                                                                                                                                                                                                                                                                                                                         16x                                                                 16x       16x    
import { Express } from 'express'
import Crowi from 'server/crowi'
import Debug from 'debug'
import async from 'async'
import url from 'url'
import { getContinueUrl } from '../util/url'
import auth from '../util/auth'
import GoogleAuth from '../util/googleAuth'
import GitHubAuth from '../util/githubAuth'
import axios from 'axios'
import FileUploader from '../util/fileUploader'
 
export default (crowi: Crowi, app: Express) => {
  const debug = Debug('crowi:routes:login')
  const config = crowi.getConfig()
  const mailer = crowi.getMailer()
  const User = crowi.model('User')
  const Config = crowi.model('Config')
  const actions = {} as any
  const isLoggedIn = auth.isLoggedIn
 
  const getSocialSession = function(session) {
    const { google = {}, github = {} } = session
    const { id: googleId } = google
    const { id: githubId } = github
    const socialId = googleId || githubId
    const socialEmail = google.email || github.email
    const socialName = google.name || github.name
    const socialImage = google.image || github.image
    const issuerName = googleId ? 'Google' : githubId ? 'GitHub' : ''
 
    return { googleId, githubId, socialId, socialEmail, socialName, socialImage, issuerName }
  }
 
  const clearSession = function(req) {
    req.session.google = {}
    req.session.github = {}
    req.session.social = {}
  }
 
  const loginSuccess = async function(req, res, userData) {
    userData = await userData.populateSecrets()
    req.user = req.session.user = userData
    if (!userData.password) {
      return res.redirect('/me/password')
    }
 
    clearSession(req)
 
    return res.redirect(getContinueUrl(req))
  }
 
  const loginFailure = function(req, res) {
    req.session.auth = {}
    req.flash('warningMessage', 'Sign in failure.')
 
    const continueUrl = getContinueUrl(req)
    const query = continueUrl === '/' ? '' : `?continue=${continueUrl}`
    const redirectUrl = `/login${query}`
    return res.redirect(redirectUrl)
  }
 
  const connect = async function(req, userData) {
    const { googleId, githubId } = getSocialSession(req.session)
 
    try {
      if (googleId) {
        await userData.updateGoogleId(googleId)
      } else if (githubId) {
        await userData.updateGitHubId(githubId)
      }
    } catch (err) {
      debug('Failed to connect', err)
    }
  }
 
  actions.googleCallback = function(req, res) {
    debug('Header', req.url, req.headers.referer)
    const { query } = req
    const { code = '', state } = query
    const { google = {} } = req.session
    const { callbackAction: action } = google
    const nextAction = action ? url.format({ pathname: action, query: { continue: state } }) : '/login'
    debug('googleCallback.nextAction', nextAction)
    req.session.google = { authCode: code }
    debug('google auth code', code)
 
    return res.redirect(nextAction)
  }
 
  actions.githubCallback = function(req, res) {
    debug('Header', req.url, req.headers.referer)
    const { query } = req
    const { code = '' } = query
    const { github = {} } = req.session
    const { callbackAction: action } = github
    const nextAction = action ? url.format({ pathname: action, query }) : '/login'
    debug('githubCallback.nextAction', nextAction)
    req.session.github = { authCode: code }
    debug('github auth code', code)
 
    return res.redirect(nextAction)
  }
 
  actions.error = function(req, res) {
    var reason = req.params.reason
    var reasonMessage = ''
 
    if (reason === 'suspended') {
      reasonMessage = 'This account is suspended.'
    } else if (reason === 'registered') {
      reasonMessage = 'Wait for approved by administrators.'
    }
 
    return res.render('login/error', {
      reason: reason,
      reasonMessage: reasonMessage,
    })
  }
 
  actions.login = async function(req, res) {
    debug('Header', req.url, req.headers.referer)
    const { loginForm } = req.body
 
    if (req.method == 'POST' && req.form.isValid) {
      let { email } = loginForm
      const { password } = loginForm
      const { toConnect } = req.body
      const { socialEmail } = getSocialSession(req.session)
 
      if (!toConnect && config.crowi['auth:disablePasswordAuth']) {
        return loginFailure(req, res)
      }
 
      email = toConnect ? socialEmail : email
      const userData = await User.findUserByEmailAndPassword(email, password).catch(err => {
        debug('on login findUserByEmailAndPassword', err)
      })
      if (userData) {
        if (toConnect) {
          await connect(
            req,
            userData,
          )
        }
        return loginSuccess(req, res, userData)
      }
 
      return loginFailure(req, res)
    } else {
      const continueUrl = getContinueUrl(req)
 
      if (isLoggedIn(crowi, req)) {
        return res.redirect('/')
      }
 
      // method GET
      if (req.form) {
        debug(req.form.errors)
      }
 
      const socialSession = getSocialSession(req.session)
      const { socialId, socialEmail } = socialSession
      const targetUser = socialEmail
        ? await User.findUserByEmail(socialEmail).catch(err => {
            debug('Failed to findUserByEmail', err)
          })
        : null
      const toConnect = !!targetUser
 
      if (socialId) {
        if (toConnect) {
          const locals = { toConnect, targetUser, ...socialSession }
 
          return res.render('login', locals)
        }
 
        return res.redirect('/register')
      }
 
      return res.render('login', { continueUrl })
    }
  }
 
  actions.loginGoogle = function(req, res) {
    debug('Header', req.url, req.headers.referer)
    const googleAuth = GoogleAuth(config)
    const { google = {} } = req.session
    const { authCode: code } = google
 
    debug('code', code)
    if (!code) {
      googleAuth.createAuthUrl(req, function(err, redirectUrl) {
        if (err) {
          // TODO
        }
 
        req.session.google = { callbackAction: '/login/google' }
        return res.redirect(redirectUrl)
      })
    } else {
      googleAuth.handleCallback(req, async (err, tokenInfo) => {
        debug('handleCallback', err, tokenInfo)
        if (err) {
          return loginFailure(req, res)
        }
 
        const { user_id: id, email, name, picture: image } = tokenInfo
 
        const userData = await User.findUserByGoogleId(id).catch(err => {
          debug('findUserByGoogleId', err)
        })
        if (userData) {
          return loginSuccess(req, res, userData)
        }
        clearSession(req)
        req.session.google = { id, email, name, image }
        return res.redirect('/login')
      })
    }
  }
 
  actions.loginGitHub = function(req, res, next) {
    debug('Header', req.url, req.headers.referer)
    const githubAuth = GitHubAuth(config)
    const { github = {} } = req.session
    const { authCode: code } = github
 
    debug('code', code)
    if (!code) {
      req.session.github = { callbackAction: '/login/github' }
      githubAuth.authenticate(req, res, next)
    } else {
      githubAuth.handleCallback(req, res, next)(async (err, tokenInfo) => {
        debug('handleCallback', err, tokenInfo)
        if (err) {
          return loginFailure(req, res)
        }
 
        const { organizations, user_id: id, email, name, picture: image } = tokenInfo
 
        if (organizations && !User.isGitHubAccountValid(organizations)) {
          clearSession(req)
          return loginFailure(req, res)
        }
 
        const userData = await User.findUserByGitHubId(id).catch(err => {
          debug('findUserByGitHubId', err)
        })
        if (userData) {
          return loginSuccess(req, res, userData)
        }
 
        clearSession(req)
        req.session.github = { organizations, id, email, name, image }
        return res.redirect('/login')
      })
    }
  }
 
  actions.register = async function(req, res, next) {
    debug('Header', req.url, req.headers.referer)
    const { lang = User.LANG_EN_US } = req
 
    // ログイン済みならさようなら
    if (req.user) {
      return res.redirect('/')
    }
 
    // config で closed ならさよなら
    if (config.crowi['security:registrationMode'] == Config.SECURITY_REGISTRATION_MODE_CLOSED) {
      return res.redirect('/')
    }
 
    if (req.method == 'POST' && req.form.isValid) {
      const { t } = req
      const { registerForm = {} } = req.form
      const { name = null, username = null, email = null, password = null, googleId = null, githubId = null, socialImage = null } = registerForm
 
      debug('registerForm', registerForm)
 
      // email と username の unique チェックする
      User.isRegisterable(email, username, function(isRegisterable, errOn) {
        const registerFailure = message => {
          req.flash('registerWarningMessage', message)
          debug('isError user register error', errOn)
          return res.redirect('/register')
        }
 
        if (!User.isEmailValid(email)) {
          return registerFailure('This email address could not be used. (Make sure the allowed email address)')
        }
        if (!isRegisterable) {
          if (!errOn.username) {
            return registerFailure(t('page_register.error.unavailable_user_id'))
          }
          if (!errOn.email) {
            return registerFailure(t('page_register.error.already_registered_email'))
          }
        }
        if (config.crowi['auth:disablePasswordAuth'] && (!googleId && !githubId)) {
          return registerFailure(t('page_register.error.unavailable_password_auth'))
        }
 
        User.createUserByEmailAndPassword(name, username, email, password, lang, async function(err, userData) {
          if (err) {
            req.flash('registerWarningMessage', 'Failed to register.')
            return res.redirect('/register')
          } else {
            // 作成後、承認が必要なモードなら、管理者に通知する
            if (config.crowi['security:registrationMode'] === Config.SECURITY_REGISTRATION_MODE_RESTRICTED) {
              // TODO send mail
              User.findAdmins(function(err, admins) {
                async.each(
                  admins,
                  function(adminUser, next) {
                    mailer.send(
                      {
                        to: adminUser.email,
                        subject: '[' + config.crowi['app:title'] + ':admin] A New User Created and Waiting for Activation',
                        template: 'admin/userWaitingActivation.txt',
                        vars: {
                          createdUser: userData,
                          adminUser: adminUser,
                          url: config.crowi['app:url'],
                          appTitle: config.crowi['app:title'],
                        },
                      },
                      function(err, s) {
                        debug('completed to send email: ', err, s)
                        next()
                      },
                    )
                  },
                  function(err) {
                    debug('Sending invitation email completed.', err)
                  },
                )
              })
            }
 
            // there are no googleId nor githubId, exit
            if (!googleId && !githubId) {
              return loginSuccess(req, res, userData)
            }
 
            // else, updating googleId/githubId and upload socialImage
 
            if (googleId) {
              try {
                userData = await userData.updateGoogleId(googleId)
              } catch (err) {
                // TODO
              }
            }
            if (githubId) {
              try {
                userData = await userData.updateGitHubId(githubId)
              } catch (err) {
                // TODO
              }
            }
 
            debug('socialImage?:', socialImage)
            if (socialImage) {
              const fileUploader = FileUploader(crowi)
 
              axios
                .get(socialImage, { responseType: 'stream' })
                .then(function(response) {
                  const type = response.headers['content-type']
                  const ext = type.replace('image/', '')
                  const filePath = User.createUserPictureFilePath(userData, ext)
                  const { data: fileStream } = response
                  fileStream.length = parseInt(response.headers['content-length'])
 
                  debug('Uploading user socialImage:', filePath, type)
                  fileUploader
                    .uploadFile(filePath, type, fileStream, {})
                    .then(function(data) {
                      const imageUrl = fileUploader.generateUrl(filePath)
                      debug('user picture uploaded', imageUrl)
                      userData.updateImage(imageUrl, function(err, data) {
                        if (err) {
                          debug('Error on update user image', err)
                        }
                        // DONE
                      })
                    })
                    .catch(function(err) {
                      // ignore
                      debug('Upload error', err)
                    })
                })
                .catch(function() {
                  // ignore
                })
            }
 
            return loginSuccess(req, res, userData)
          }
        })
      })
    } else {
      // method GET of form is not valid
      debug('session is', req.session)
 
      const isDisabledPasswordAuth = !!config.crowi['auth:disablePasswordAuth']
 
      const socialSession = getSocialSession(req.session)
      const { socialEmail } = socialSession
      const { github = {} } = req.session
 
      const registerFailure = message => {
        const isRegistering = isDisabledPasswordAuth
        const type = isRegistering ? 'warningMessage' : 'registerWarningMessage'
        req.flash(type, message)
        return res.render('login', { isRegistering })
      }
 
      if (!User.isEmailValid(socialEmail)) {
        return registerFailure('This email address could not be used. (Make sure the allowed email address)')
      }
 
      if (github.organizations && !User.isGitHubAccountValid(github.organizations)) {
        return registerFailure('This account could not be used. (Make sure whether you belong to allowed GitHub Organization)')
      }
 
      const isRegistering = true
      const targetUser = socialEmail
        ? await User.findUserByEmail(socialEmail).catch(err => {
            debug('Failed to findUserByEmail', err)
          })
        : null
      const toConnect = !!targetUser
      const locals = { isRegistering, toConnect, targetUser, ...socialSession }
 
      return res.render('register', locals)
    }
  }
 
  actions.invited = function(req, res) {
    if (!req.user) {
      return res.redirect('/login')
    }
 
    if (req.method == 'POST' && req.form.isValid) {
      var user = req.user
      var invitedForm = req.form.invitedForm || {}
      var username = invitedForm.username
      var name = invitedForm.name
      var password = invitedForm.password
 
      User.isRegisterableUsername(username, function(creatable) {
        if (creatable) {
          user.activateInvitedUser(username, name, password, function(err, data) {
            if (err) {
              req.flash('warningMessage', 'アクティベートに失敗しました。')
              return res.render('invited')
            } else {
              return res.redirect('/')
            }
          })
        } else {
          req.flash('warningMessage', '利用できないユーザーIDです。')
          debug('username', username)
          return res.render('invited')
        }
      })
    } else {
      return res.render('invited', {})
    }
  }
 
  actions.updateInvitedUser = function(req, res) {
    return res.redirect('/')
  }
 
  return actions
}