All files / controllers me.js

11.11% Statements 21/189
0% Branches 0/81
3.45% Functions 1/29
11.11% Lines 21/189

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 35615x     15x 15x 15x 15x 15x 15x   15x   15x                                                                                                                                           15x                                                                                       15x                                                                                   15x                                       15x           15x       15x               15x                     15x                                                               15x                                                                           15x                                                     15x                                                                             15x    
module.exports = function(crowi, app) {
  'use strict'
 
  const debug = require('debug')('crowi:routes:me')
  const fs = require('fs')
  const config = crowi.getConfig()
  const User = crowi.model('User')
  const actions = {}
  const api = {}
 
  actions.api = api
 
  api.uploadPicture = function(req, res) {
    var fileUploader = require('../util/fileUploader')(crowi, app)
    // var storagePlugin = new pluginService('storage');
    // var storage = require('../service/storage').StorageService(config);
 
    var tmpFile = req.file || null
    if (!tmpFile) {
      return res.json({
        status: false,
        message: 'File type error.',
      })
    }
 
    var tmpPath = tmpFile.path
    var name = tmpFile.filename + tmpFile.originalname
    var ext = name.match(/(.*)(?:\.([^.]+$))/)[2]
    var filePath = User.createUserPictureFilePath(req.user, ext)
    var acceptableFileType = /image\/.+/
 
    if (!tmpFile.mimetype.match(acceptableFileType)) {
      return res.json({
        status: false,
        message: 'File type error. Only image files is allowed to set as user picture.',
      })
    }
 
    // debug('tmpFile Is', tmpFile, tmpFile.constructor, tmpFile.prototype);
    // var imageUrl = storage.writeSync(storage.tofs(tmpFile), filePath, {mime: tmpFile.mimetype});
    // return return res.json({
    //  'status': true,
    //  'url': imageUrl,
    //  'message': '',
    // });
    var tmpFileStream = fs.createReadStream(tmpPath, {
      flags: 'r',
      encoding: null,
      fd: null,
      mode: '0666',
      autoClose: true,
    })
 
    fileUploader
      .uploadFile(filePath, tmpFile.mimetype, tmpFileStream, {})
      .then(function(data) {
        var imageUrl = fileUploader.generateUrl(filePath)
        req.user.updateImage(imageUrl, function(err, data) {
          fs.unlink(tmpPath, function(err) {
            // エラー自体は無視
            if (err) {
              debug('Error while deleting tmp file.', err)
            }
 
            return res.json({
              status: true,
              url: imageUrl,
              message: '',
            })
          })
        })
      })
      .catch(function(err) {
        debug('Uploading error', err)
 
        return res.json({
          status: false,
          message: 'Error while uploading to ',
        })
      })
  }
 
  actions.index = function(req, res) {
    const { user: userData } = req
    const { userForm } = req.body
 
    if (req.method == 'POST' && req.form.isValid) {
      const { name, email, lang } = userForm
 
      if (!User.isEmailValid(email)) {
        req.form.errors.push("You can't update to that email address")
        return res.render('me/index', {})
      }
 
      User.findOne({ email }, (err, existingUserData) => {
        // If another user uses the same email, an error will occur.
        if (existingUserData && !existingUserData._id.equals(userData._id)) {
          debug('Email address was duplicated')
          req.form.errors.push('It can not be changed to that mail address')
          return res.render('me/index', {})
        }
 
        userData.update(name, email, lang, (err, userData) => {
          if (err) {
            Object.keys(err.errors).forEach(e => {
              req.form.errors.push(err.errors[e].message)
            })
            return res.render('me/index', {})
          }
 
          req.i18n.changeLanguage(lang)
          req.flash('successMessage', req.t('Updated'))
          return res.redirect('/me')
        })
      })
    } else {
      // method GET
      /// そのうちこのコードはいらなくなるはず
      if (!userData.isEmailSet()) {
        req.flash('warningMessage', 'メールアドレスが設定されている必要があります')
      }
 
      return res.render('me/index', {})
    }
  }
 
  actions.password = function(req, res) {
    const { user: userData } = req
    const { mePassword: passwordForm } = req.body
 
    // パスワードを設定する前に、emailが設定されている必要がある (schemaを途中で変更したため、最初の方の人は登録されていないかもしれないため)
    // そのうちこのコードはいらなくなるはず
    if (!userData.isEmailSet()) {
      return res.redirect('/me')
    }
 
    if (req.method == 'POST' && req.form.isValid) {
      var newPassword = passwordForm.newPassword
      var newPasswordConfirm = passwordForm.newPasswordConfirm
      var oldPassword = passwordForm.oldPassword
 
      if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
        req.form.errors.push('Wrong current password')
        return res.render('me/password', {})
      }
 
      // check password confirm
      if (newPassword != newPasswordConfirm) {
        req.form.errors.push('Failed to verify passwords')
      } else {
        userData.updatePassword(newPassword, function(err, userData) {
          if (err) {
            for (const [key, e] of err.errors) {
              req.form.errors.push(e.message)
            }
            return res.render('me/password', {})
          }
 
          req.flash('successMessage', 'Password updated')
          return res.redirect('/me/password')
        })
      }
    } else {
      // method GET
      return res.render('me/password', {})
    }
  }
 
  actions.apiToken = function(req, res) {
    const { user: userData } = req
 
    if (req.method == 'POST' && req.form.isValid) {
      userData
        .updateApiToken()
        .then(function(userData) {
          req.flash('successMessage', 'API Token updated')
          return res.redirect('/me/apiToken')
        })
        .catch(function(err) {
          // req.flash('successMessage',);
          req.form.errors.push('Failed to update API Token')
          return res.render('me/api_token', {})
        })
    } else {
      return res.render('me/api_token', {})
    }
  }
 
  actions.notifications = function(req, res) {
    var renderVars = {}
 
    return res.render('me/notifications', renderVars)
  }
 
  actions.updates = function(req, res) {
    res.render('me/update', {})
  }
 
  actions.deletePicture = function(req, res) {
    // TODO: S3 からの削除
    req.user.deleteImage(function(err, data) {
      req.flash('successMessage', 'Deleted profile picture')
      res.redirect('/me')
    })
  }
 
  actions.authThirdParty = function(req, res) {
    const { continue: continueUrl = '/' } = req.query
 
    if (!config.crowi['auth:requireThirdPartyAuth'] || req.user.hasValidThirdPartyId()) {
      req.session.callback = null
      return res.redirect(continueUrl)
    }
    req.session.callback = '/me/auth/third-party'
    return res.render('me/auth/third-party')
  }
 
  actions.authGoogle = async function(req, res) {
    const googleAuth = require('../util/googleAuth')(config)
    const { user: userData, t } = req
    const toDisconnect = !!req.body.disconnectGoogle
    const toConnect = !!req.body.connectGoogle
    const callback = req.session.callback || '/me'
 
    if (toDisconnect) {
      if (userData.canDisconnectThirdPartyId()) {
        await userData.deleteGoogleId()
        try {
          req.flash('successMessage', 'Disconnected from Google account')
        } catch (err) {
          req.flash('warningMessage.auth.google', 'Failed to disconnect Google Account')
        }
        return res.redirect(callback)
      }
      req.flash('warningMessage.auth.google', t('page_me.can_not_disconnect'))
      return res.redirect(callback)
    } else if (toConnect) {
      googleAuth.createAuthUrl(req, function(err, redirectUrl) {
        if (err) {
          // TODO
        }
        req.session.google = { callbackAction: '/me/auth/google/callback' }
        return res.redirect(redirectUrl)
      })
    } else {
      return res.redirect(callback)
    }
  }
 
  actions.authGoogleCallback = function(req, res) {
    const googleAuth = require('../util/googleAuth')(config)
    const { user: userData } = req
    const callback = req.session.callback || '/me'
 
    googleAuth.handleCallback(req, async function(err, tokenInfo) {
      if (err) {
        req.flash('warningMessage.auth.google', err.message) // FIXME: show library error message directly
        return res.redirect(callback) // TODO Handling
      }
 
      const { user_id: googleId, email: googleEmail } = tokenInfo
 
      if (!User.isEmailValid(googleEmail)) {
        req.flash('warningMessage.auth.google', "You can't connect with this  Google's account")
        return res.redirect(callback)
      }
 
      const googleUser = await User.findUserByGoogleId(googleId).catch(err => {
        debug('Failed to findUserByGoogleId', err)
      })
      if (googleUser) {
        req.flash('warningMessage.auth.google', "This Google's account is connected by another user")
        return res.redirect(callback)
      }
 
      try {
        await userData.updateGoogleId(googleId)
        req.flash('successMessage', 'Connected with Google')
      } catch (err) {
        debug('Failed to updateGoogleId', err)
        req.flash('warningMessage.auth.google', 'Failed to connect Google Account')
      }
 
      return res.redirect(callback)
    })
  }
 
  actions.authGitHub = async function(req, res, next) {
    const githubAuth = require('../util/githubAuth')(config)
    const { user: userData, t } = req
    const toDisconnect = !!req.body.disconnectGitHub
    const toConnect = !!req.body.connectGitHub
    const callback = req.session.callback || '/me'
 
    if (toDisconnect) {
      if (userData.canDisconnectThirdPartyId()) {
        await userData.deleteGitHubId()
        try {
          req.flash('successMessage', 'Disconnected from GitHub account')
        } catch (err) {
          req.flash('warningMessage.auth.github', 'Failed to disconnect GitHub Account')
        }
        return res.redirect(callback)
      }
      req.flash('warningMessage.auth.github', t('page_me.can_not_disconnect'))
      return res.redirect(callback)
    } else if (toConnect) {
      req.session.github = { callbackAction: '/me/auth/github/callback' }
      githubAuth.authenticate(req, res, next)
    } else {
      return res.redirect(callback)
    }
  }
 
  actions.authGitHubCallback = function(req, res, next) {
    const githubAuth = require('../util/githubAuth')(config)
    const { user: userData } = req
    const callback = req.session.callback || '/me'
 
    githubAuth.handleCallback(req, res, next)(async function(err, tokenInfo) {
      debug('err', err)
      if (err) {
        req.flash('warningMessage.auth.github', err.message)
        return res.redirect(callback) // TODO Handling
      }
 
      const { organizations: githubOrganizations, user_id: githubId, email: githubEmail } = tokenInfo
 
      if (!User.isEmailValid(githubEmail) || !User.isGitHubAccountValid(githubOrganizations)) {
        req.flash('warningMessage.auth.github', "You can't connect with this  GitHub's account")
        return res.redirect(callback)
      }
 
      const githubUser = await User.findUserByGitHubId(githubId).catch(err => {
        debug('Failed to findUserByGitHubId', err)
      })
      if (githubUser) {
        req.flash('warningMessage.auth.github', "This GitHub's account is connected by another user")
        return res.redirect(callback)
      }
 
      try {
        await userData.updateGitHubId(githubId)
        req.flash('successMessage', 'Connected with GitHub')
      } catch (err) {
        debug('Failed to updateGitHubId', err)
        req.flash('warningMessage.auth.github', 'Failed to connect GitHub Account')
      }
 
      return res.redirect(callback)
    })
  }
 
  return actions
}