????

Your IP : 3.145.180.18


Current Path : C:/inetpub/vhost/sdoc.gdtsolutions.vn/package/app/controllers/
Upload File :
Current File : C:/inetpub/vhost/sdoc.gdtsolutions.vn/package/app/controllers/taikhoan.js

const Database = require('../models/Database');
var moment = require('moment');
const bcrypt = require('bcryptjs');
class TaiKhoanController extends Database {
  constructor(params) {
    super(params);
  }
  static create(params) {
    return new TaiKhoanController(params);
  }
  getUsers(role) {
    return this.select('SELECT Account.*,[Role].Name,[Role].RoleArea,[Role].Tasks FROM Account INNER JOIN [Role] ON [Role].Id = Account.[Role] AND Account.[Role] = @role', { role: role });
  }
  getReaders() {
    return this.select('SELECT ROW_NUMBER() OVER(ORDER BY Username) as RowNum,UUID,Username,Password,FullName,Gender,IdNumber,Birthday,Email,Telephone,Address, (SELECT COUNT(UUID) FROM DocReq WHERE AccountId = Account.UUID) reqCount FROM Account WHERE [Role] = 2 AND [State] > 0');
  }
  async getRoleByUsername(username) {
    var acc = await this.getByUsername(username);
    if (acc) return acc.Role;
    else return null;
  }
  async getByUsername(username) {
    var sql = 'SELECT Account.*,[Role].Name,[Role].Code,[Role].Tasks FROM Account INNER JOIN [Role] ON [Role].Id = Account.[Role] WHERE Account.Username = @login OR Account.Telephone = @login';
    var account = (await this.select(sql, { login: username }))[0];
    if (account) return account;
    else return null;
  }
  async isUser(username, password) {
    var account = await this.getByUsername(username);
    if (account && await bcrypt.compare(password, account.Password)) return account;
    else return null;
  }
  async changePassword(account, passInfo) {
    if (!(await bcrypt.compare(passInfo['curpassword'], account['Password']))) throw new Error('Mật khẩu cũ không chính xác')
    var hash = await bcrypt.hash(passInfo['newpassword'], 10);
    return await this.query('UPDATE Account SET Password = @password WHERE UUID = @uuid', { password: hash, uuid: account.UUID })
  }
  async editProfile(user, account) {
    var updates = [];
    account.uuid = user.UUID;
    if (typeof account.fullname !== 'undefined') updates.push('FullName = @fullname');
    if (typeof account.gender !== 'undefined') updates.push('Gender = @gender');
    if (typeof account.birthday !== 'undefined') {
      let birthday = moment.utc(account['birthday'], 'DD/MM/YYYY');
      account['birthday'] = birthday.isValid() ? birthday.toDate() : null;
      updates.push('Birthday = @birthday');
    }
    if (typeof account.idnumber !== 'undefined') updates.push('IdNumber = @idnumber');
    if (typeof account.address !== 'undefined') updates.push('Address = @address');
    if (typeof account.email !== 'undefined') updates.push('Email = @email');
    if (typeof account.phone !== 'undefined') updates.push('Telephone = @phone');
    return await this.query(`UPDATE Account SET ${updates.join(',')} WHERE UUID = @uuid`, account);
  }
  async addReader(account) {
    let phone = '0' + account['phone'].trim();
    let password = account['password'] || this.autoPassword();
    if ((await this.select('SELECT UUID FROM Account WHERE Username = @phone OR Telephone = @phone', { phone: phone })).length)
      throw new Error(`Đã tồn tại tài khoản với tên số điện thoại [${phone}]`);
    if (account['idnumber'] && (await this.select('SELECT UUID FROM Account WHERE IdNumber = @idnumber', { idnumber: account['idnumber'] })).length)
      throw new Error(`Đã tồn tại tài khoản với số CMND hoặc hộ chiếu [${account['idnumber']}]`);
    if (account['email'] && (await this.select('SELECT UUID FROM Account WHERE Email = @email', { email: account['email'] })).length)
      throw new Error(`Đã tồn tại tài khoản với email [${account['email']}]`);
    let input = {
      username: account['username'],
      password: await bcrypt.hash(password, 10),
      fullname: account['fullname'].trim(),
      birthday: moment.utc(account['birthday'], 'DD/MM/YYYY').isValid() ? moment.utc(account['birthday'], 'DD/MM/YYYY').toDate() : null,
      gender: account['gender'],
      idnumber: account['idnumber'].trim() || null,
      address: account['address'].trim() || null,
      email: account['email'].trim() || null,
      telephone: phone
    };
    return await this.select('INSERT INTO Account(Username,Password,FullName,Gender,Birthday,IdNumber,Address,Email,Telephone,[Role],State) OUTPUT inserted.UUID VALUES(@username,@password,@fullname,@gender,@birthday,@idnumber,@address,@email,@telephone,2,1)', input);
  }
  async delete(id) {
    return await this.query('DELETE FROM Account WHERE UUID=@uuid', { uuid: id });
  }
  // kiểm tra tài khoản tồn tại
  async checkAcc(login, user) {
    let query = 'SELECT UUID FROM Account WHERE (Username = @login OR Telephone = @login)';
    let input = { login: login };
    if (user) {
      query += ' AND UUID = @id';
      input['id'] = user.UUID;
    }
    let users = await this.select(query, input);
    if (users.length) return true;
    return false;
  }
  autoPassword(length) {
    let keylist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
    let result = '';
    for (let i = 0; i < length; i++) {
      result += keylist.charAt(Math.floor(Math.random() * keylist.length))
    }
    return result;
  }
}
module.exports = TaiKhoanController