<commit_before>var config = require('../../server/config.json')
var path = require('path')
var utility = require('../../public/utility.js')
var app = require('../../server/server')

var PRODUCTION = false

var methodDisabler = require('../../public/methodDisabler.js')
var relationMethodPrefixes = [
  'createChangeStream',
  'upsertWithWhere',
  'patchOrCreate',
  'exists',
  'prototype.patchAttributes'
]

var countryList = require('../../config/country.json')
var statusJson = require('../../config/status.json')
var accountType = require('../../config/accountType.json')

module.exports = function (client) {

  methodDisabler.disableOnlyTheseMethods(client, relationMethodPrefixes)

  client.validatesLengthOf('password', {min: 6})
  client.validatesInclusionOf('registrationCountry', {in: countryList})

  // Decrypt Password for Front/Back Communications
  client.beforeRemote('login', function (ctx, modelInstance, next) {
    if (PRODUCTION) {
      var pass1 = utility.base64Decoding(ctx.args.credentials.password).toString()
      var pass2 = utility.base64Decoding(ctx.req.body.password).toString()
      ctx.args.credentials.password = <PASSWORD>
      ctx.req.body.password = <PASSWORD>
    }
    return next()
  })

  client.beforeRemote('create', function (ctx, modelInstance, next) {
    if (PRODUCTION) {
      var pass1 = utility.base64Decoding(ctx.args.data.password).toString()
      var pass2 = utility.base64Decoding(ctx.req.body.password).toString()
      ctx.args.data.password = <PASSWORD>
      ctx.req.body.password = <PASSWORD>
    }
    var whiteList = ['companyName', 'email', 'username', 'password', 'time', 'registrationCountry', 'registrationIPAddress']
    if (!utility.inputChecker(ctx.args.data, whiteList))
      return next(new Error('White List Error! Allowed Parameters: ' + whiteList.toString()))
    else {
      ctx.args.data.announcerAccountModel = {}
      ctx.args.data.announcerAccountModel.budget = 0
      ctx.args.data.announcerAccountModel.type = accountType.free
      ctx.args.data.publisherAccountModel = {}
      ctx.args.data.publisherAccountModel.credit = 0
      ctx.args.data.publisherAccountModel.type = accountType.free
      return next()
    }
  })

  client.beforeRemote('changePassword', function (ctx, modelInstance, next) {
    if (PRODUCTION) {
      var pass1 = utility.base64Decoding(ctx.args.data.password).toString()
      var pass2 = utility.base64Decoding(ctx.req.body.password).toString()
      var conf1 = utility.base64Decoding(ctx.args.data.confirmation).toString()
      var conf2 = utility.base64Decoding(ctx.req.body.confirmation).toString()
      ctx.args.data.password = <PASSWORD>
      ctx.req.body.password = <PASSWORD>
      ctx.args.data.confirmation = conf1
      ctx.req.body.confirmation = conf2
    }
    next()
  })

  client.beforeRemote('prototype.__update__publisherAccount', function (ctx, modelInstance, next) {
    if (!ctx.args.options.accessToken)
      return next()
    client.findById(ctx.req.params.id, function (err, result) {
      if (err)
        throw err
      // Fix Chain
      return next()
    })
  })

  client.beforeRemote('prototype.__create__applications', function (ctx, modelInstance, next) {
    if (!ctx.args.options.accessToken)
      return next()
    var whiteList = ['name', 'operatingSystem']
    if (!utility.inputChecker(ctx.args.data, whiteList))
      return next(new Error('White List Error! Allowed Parameters: ' + whiteList.toString()))
    else {
      ctx.args.data.credit = 0
      ctx.args.data.clientId = ctx.args.options.accessToken.userId
      ctx.args.data.status = statusJson.enable
      ctx.args.data.message = 'Application is Enabled'
      return next()
    }
  })

  client.beforeRemote('prototype.__updateById__applications', function (ctx, modelInstance, next) {
    if (!ctx.args.options.accessToken)
      return next()
    var whiteList = ['name', 'status']
    if (!utility.inputChecker(ctx.args.data, whiteList))
      return next(new Error('White List Error! Allowed Parameters: ' + whiteList.toString()))
    else {
      if (ctx.args.data.status) {
        if (ctx.args.data.status === statusJson.enable) {
          ctx.args.data.status = statusJson.enable
          ctx.args.data.message = 'Application is Enabled'
          return next()
        }
        else if (ctx.args.data.status === statusJson.disable) {
          ctx.args.data.status = statusJson.disable
          ctx.args.data.message = 'Application is Disabed'
          var application = app.models.application
          application.findById(ctx.req.params.fk, function (err, result) {
            if (err)
              return next(err)
            for (var i = 0; i < result.placementList.length; i++) {
              var counter = 0
              var model = result.placementList[i]  
              model.updateAttribute('status', statusConfig.disable, function (err, response) {
                if (err)
                  throw err
                counter++
                if (counter == result.placementList.length)
                return next()
              })
            }
          })
        }
      }
    }
  })

  client.beforeRemote('replaceById', function (ctx, modelInstance, next) {
    var whilteList = ['companyName']
    if (utility.inputChecker(ctx.args.data, whilteList))
      next()
    else
      next(new Error('White List Error! Allowed Parameters: ' + whilteList.toString()))
  })

  // Change Password Remote Method 
  client.changePassword = function (data, req, res, cb) {
    if (!req.accessToken)
      return res.sendStatus(401)<commit_msg>Add RoleManager and Fix Status Chain from Father to Child<commit_after>var config = require('../../server/config.json')
var path = require('path')
var utility = require('../../public/utility.js')
var app = require('../../server/server')
var roleManager = require('../../public/roleManager')

var PRODUCTION = false

var methodDisabler = require('../../public/methodDisabler.js')
var relationMethodPrefixes = [
  'createChangeStream',
  'upsertWithWhere',
  'patchOrCreate',
  'exists',
  'prototype.patchAttributes'
]

var countryList = require('../../config/country.json')
var statusJson = require('../../config/status.json')
var accountType = require('../../config/accountType.json')

module.exports = function (client) {

  methodDisabler.disableOnlyTheseMethods(client, relationMethodPrefixes)

  client.validatesLengthOf('password', {min: 6})
  client.validatesInclusionOf('registrationCountry', {in: countryList})

  // Decrypt Password for Front/Back Communications
  client.beforeRemote('login', function (ctx, modelInstance, next) {
    if (PRODUCTION) {
      var pass1 = utility.base64Decoding(ctx.args.credentials.password).toString()
      var pass2 = utility.base64Decoding(ctx.req.body.password).toString()
      ctx.args.credentials.password = <PASSWORD>
      ctx.req.body.password = <PASSWORD>
    }
    return next()
  })

  client.afterRemote('login', function (ctx, modelInstance, next) {
    roleManager.getRolesById(app, modelInstance.userId, function (err, result) {
      if (err)
        return next(err)
      if (result.roles.length == 0) {
        client.findById(modelInstance.userId, function (err, result) {
          if (err)
            throw err
          if (result.clientType.indexOf('Publisher') <= -1) {
            var oldSet = []
            oldSet = result.clientType
            oldSet.push('Publisher')
            result.updateAttribute('clientType', oldSet, function (err, response) {
              if (err)
                throw err
              return next()
            })        
          }
          else        
            return next()
        })
      }
      else 
        return next()
    })
  })

  client.beforeRemote('create', function (ctx, modelInstance, next) {
    if (PRODUCTION) {
      var pass1 = utility.base64Decoding(ctx.args.data.password).toString()
      var pass2 = utility.base64Decoding(ctx.req.body.password).toString()
      ctx.args.data.password = <PASSWORD>
      ctx.req.body.password = <PASSWORD>
    }
    var whiteList = ['companyName', 'email', 'username', 'password', 'time', 'registrationCountry', 'registrationIPAddress']
    if (!utility.inputChecker(ctx.args.data, whiteList))
      return next(new Error('White List Error! Allowed Parameters: ' + whiteList.toString()))
    else {
      ctx.args.data.announcerAccountModel = {}
      ctx.args.data.announcerAccountModel.budget = 0
      ctx.args.data.announcerAccountModel.type = accountType.free
      ctx.args.data.publisherAccountModel = {}
      ctx.args.data.publisherAccountModel.credit = 0
      ctx.args.data.publisherAccountModel.type = accountType.free
      ctx.args.data.clientType = []
      return next()
    }
  })

  client.beforeRemote('changePassword', function (ctx, modelInstance, next) {
    if (PRODUCTION) {
      var pass1 = utility.base64Decoding(ctx.args.data.password).toString()
      var pass2 = utility.base64Decoding(ctx.req.body.password).toString()
      var conf1 = utility.base64Decoding(ctx.args.data.confirmation).toString()
      var conf2 = utility.base64Decoding(ctx.req.body.confirmation).toString()
      ctx.args.data.password = <PASSWORD>
      ctx.req.body.password = <PASSWORD>
      ctx.args.data.confirmation = conf1
      ctx.req.body.confirmation = conf2
    }
    next()
  })

  client.beforeRemote('prototype.__update__publisherAccount', function (ctx, modelInstance, next) {
    if (!ctx.args.options.accessToken)
      return next()
    client.findById(ctx.req.params.id, function (err, result) {
      if (err)
        throw err
      // Fix Chain
      return next()
    })
  })

  client.beforeRemote('prototype.__create__applications', function (ctx, modelInstance, next) {
    if (!ctx.args.options.accessToken)
      return next()
    var whiteList = ['name', 'operatingSystem']
    if (!utility.inputChecker(ctx.args.data, whiteList))
      return next(new Error('White List Error! Allowed Parameters: ' + whiteList.toString()))
    else {
      ctx.args.data.credit = 0
      ctx.args.data.clientId = ctx.args.options.accessToken.userId
      ctx.args.data.status = statusJson.enable
      ctx.args.data.message = 'Application is Enabled'
      return next()
    }
  })

  client.beforeRemote('prototype.__updateById__applications', function (ctx, modelInstance, next) {
    if (!ctx.args.options.accessToken)
      return next()
    var whiteList = ['name', 'status']
    if (!utility.inputChecker(ctx.args.data, whiteList))
      return next(new Error('White List Error! Allowed Parameters: ' + whiteList.toString()))
    else {
      if (ctx.args.data.status) {
        if (ctx.args.data.status === statusJson.enable) {
          ctx.args.data.status = statusJson.enable
          ctx.args.data.message = 'Application is Enabled'
          return next()
        }
        else if (ctx.args.data.status === statusJson.disable) {
          ctx.args.data.status = statusJson.disable
          ctx.args.data.message = 'Application is Disabed'
        }
      }
    }
  })
  
  client.afterRemote('prototype.__updateById__applications', function (ctx, modelInstance, next) {
    if (ctx.args.data.status) {
      if (ctx.args.data.status === statusJson.disable) {
        var placement = app.models.placement
        placement.find({ where: { 'applicationId': ctx.req.params.fk } }, function (err, placementList) {
          if (err)
            throw err
          var fire = 0
          for (var i = 0; i < placementList.length; i++) {
            fire++
            placementList[i].updateAttribute('status', statusJson.disable, function (err, response) {
              if (err)
                throw err  
              if (fire == placementList.length)
                return next()  
            })
          }
        })
      }
    }
  })

  client.beforeRemote('replaceById', function (ctx, modelInstance, next) {
    var whilteList = ['companyName']
    if (utility.inputChecker(ctx.args.data, whilteList))
      next()
    else
      next(new Error('White List Error! Allowed Parameters: ' + whilteList.toString()))
  })

  // Change Password Remote Method 
  client.changePassword = function (data, req, res, cb) {
    if (!req.accessToken)
      return res.sendStatus(401)
{'fraction_non_alphanumeric': 0.13234097933951522, 'fraction_numerical': 0.005856515373352855, 'mean_word_length': 2.79827000308928, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3358564', 'n_tokens_mistral': 3632, 'n_tokens_neox': 3551, 'n_words': 724}