Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let mysql = require('mysql')
  2.   , SHA256 = require('crypto-js/sha256')
  3.   , config = require('./config')
  4.   , connection = mysql.createConnection(config.db)
  5.  
  6.  
  7. class User {
  8.   constructor() {
  9.     this.logged = false
  10.     this.loginAttempts = 0
  11.     this.maxLoginAttempts = 3
  12.     this.login = this.bind (this.login, this.onBeforeLogin, this.onAfterLogin)
  13.   }
  14.  
  15.   bind (func, beforeFunc, afterFunc) {
  16.     return function() {  
  17.     return beforeFuncn.call(this, arguments) ? func.call(this, arguments, afterFunc) : null
  18.   }
  19.  
  20.   static get blackList() { return ['127.0.0.1']; }
  21.  
  22.   login (player, username, password, callback) {
  23.     if (this.logged) return true
  24.    
  25.     connection.query('SELECT * FROM users WHERE username = ?, password = ?',[
  26.       username.toString(),
  27.       SHA256(password.toString()),
  28.     ], function(err, result) {
  29.       if (!err) { // ошибок нет, все окей
  30.         // Запись с такой парой найдена?
  31.         if (result.length) {
  32.           this.logged = true
  33.           return callback(username, this.logged, this.loginAttempts)
  34.         } else {
  35.           return callback(username, this.logged, ++this.loginAttempts)
  36.         }
  37.       } else {
  38.         debug(`User::login, ошибка запроса к БД, причина: ${err}`)
  39.       }
  40.     })     
  41.   }
  42.  
  43.   beforeLogin (player) {
  44.     return this.loginAttempts > this.maxLoginAttempts || User.blackList.indexOf(player.ip) >= 0 ? false : true
  45.   }
  46.  
  47.   afterLogin (username, status, count) {
  48.     if (status) {
  49.       debug(`Пользовател ${username} авторизовался! ${count ? 'Его количество попыток входа = ' + count : ''}`)
  50.       this.loginAttempts = 0
  51.     } else {
  52.       debug(`Ошибка авторизации. Количество попыток входа с логином ${username} = ${count.toString()}`)
  53.     }
  54.     return status
  55.   }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement