Completed
Push — master ( 78d2f9...949122 )
by greg
42s
created

forgot.js ➔ ... ➔ crypto.randomBytes   C

Complexity

Conditions 7
Paths 18

Size

Total Lines 70

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
nc 18
dl 0
loc 70
rs 6.8519
c 0
b 0
f 0
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import fs from 'fs-extra'
2
import crypto from 'crypto'
3
import nodemailer from 'nodemailer'
4
import path from 'path'
5
6
import {
7
  coreUtils,
8
  config,
9
  Handlebars,
10
  User
11
} from '../../../../cli'
12
13
function showHtml(res, req, info) {
14
  var resHtml = ''
15
  var page = path.join(__dirname + '/../../../views/users/forgot.html')
0 ignored issues
show
Compatibility introduced by
Consider using the path module for constructing paths since they are otherwise not cross-OS compatible.
Loading history...
16
  if (coreUtils.file.exist(page)) {
17
    resHtml = fs.readFileSync(page, 'utf8')
18
  }
19
20
  var template = Handlebars.compile(resHtml, {noEscape: true})
21
22
  var tmp = template({
23
    csrfToken: res.locals.csrfToken,
24
    config: JSON.stringify(config),
25
    express: {
26
      req: req,
27
      res: res
28
    },
29
    token: req.query.token,
30
    info: info
31
  })
32
33
  return res.send(tmp)
34
}
35
36
var route = function route(req, res) {
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable route already seems to be declared on line 36. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
37
  var html
38
  if(typeof req.query.email !== 'undefined' && req.query.email !== null) {
39
    User.utils.findByEmail(req.query.email, function (err, user) {
40
      if (err) {
41
        return res.status(200).json({success: 1}) 
42
      }
43
44
      crypto.randomBytes(20, function(err, buf) {
45
        var resetPasswordToken = buf.toString('hex')
46
        var forgotExpire = config.forgotExpire
47
48
        User.operations.update({
49
          id:user.id,
50
          resetPasswordToken: resetPasswordToken,
51
          resetPasswordExpires: Date.now() + (forgotExpire*60*1000)
52
        })
53
54
        var requestedUrl = req.protocol + '://' + req.get('Host') + '/abe/users/reset?token=' + resetPasswordToken
55
56
        var smtp = config.smtp
57
        var emailConf = config.users.email
58
        html = emailConf.html || ''
59
60
        if(typeof emailConf.templateHtml !== 'undefined' && emailConf.templateHtml !== null) {
61
          var fileHtml = path.join(config.root, emailConf.templateHtml)
62
          if (coreUtils.file.exist(fileHtml)) {
63
            html = fs.readFileSync(fileHtml, 'utf8')
64
          }
65
        }
66
67
        var template = Handlebars.compile(html, {noEscape: true})
68
69
        html = template({
70
          express: {
71
            req: req,
72
            res: res
73
          },
74
          forgotUrl: requestedUrl,
75
          siteUrl: req.protocol + '://' + req.get('Host'),
76
          user: user
77
        })
78
79
        if(typeof smtp === 'undefined' || smtp === null) {
80
          var transport = nodemailer.createTransport('direct', {})
81
          transport.sendMail({
82
            from: emailConf.from, // sender address
83
            to: user.email, // list of receivers
84
            subject: emailConf.subject, // Subject line
85
            text: emailConf.text.replace(/\{\{forgotUrl\}\}/g, requestedUrl), // plaintext body
86
            html: html.replace(/\{\{forgotUrl\}\}/g, requestedUrl) // html body
87
          }, console.error)
88
89
          showHtml(res, req, 'Check your inbox')
90
        }else if(typeof smtp !== 'string') {
91
          // create reusable transporter object using the default SMTP transport
92
          var transporter = nodemailer.createTransport('SMTP', smtp)
93
94
          // setup e-mail data with unicode symbols
95
          var mailOptions = {
96
            from: emailConf.from, // sender address
97
            to: user.email, // list of receivers
98
            subject: emailConf.subject, // Subject line
99
            text: emailConf.text.replace(/\{\{forgotUrl\}\}/g, requestedUrl), // plaintext body
100
            html: html.replace(/\{\{forgotUrl\}\}/g, requestedUrl) // html body
101
          }
102
103
          // send mail with defined transport object
104
          transporter.sendMail(mailOptions, function(error, info){
105
            if(error){
106
              return console.log(error)
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
107
            }
108
109
            showHtml(res, req, 'Check your inbox')
110
            console.log('Message sent: ' + info.response)
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
111
          })
112
        }
113
      })
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
114
    })
115
  }else {
116
    showHtml(res, req, req.flash('info'))
117
  }
118
}
119
120
export default route