import moment from "moment"; import { Connection } from "typeorm"; import { BaseRepository, Encryptor } from "@leal.api/api_utils"; import { ResponseModel, ComercioUsuario } from "@leal.api/api_models"; import { LoginViewModel } from "../models"; import { ComercioUsuarioRefreshTokenRepository } from "."; import { IComercioUsuarioRepository } from "../interfaces"; export class ComercioUsuarioRepository extends BaseRepository implements IComercioUsuarioRepository { public encryptor: Encryptor; private refreshTokenRepo: ComercioUsuarioRefreshTokenRepository; constructor(connection: Connection) { super(connection, ComercioUsuario); this.encryptor = new Encryptor(); this.refreshTokenRepo = new ComercioUsuarioRefreshTokenRepository( connection ); } async inicioSesion( usuario: string, contrasena: string ): Promise> { //TODO: check against database and validate email and password match try { let result = await this.repo .createQueryBuilder("user") .where( "user.estado LIKE 'act%' AND user.usuario = :usuario AND (user.contrasena = :md5 OR user.contrasena = :encrypt)", { usuario: usuario, md5: this.encryptor.md5(contrasena), encrypt: this.encryptor.encrypt(contrasena) } ) .select([ "user.id", "user.usuario", "user.email", "user.fullname", "user.idComercio", "user.idRol", "user.idFranquicia", "user.idSucursal" ]) .getOne(); if (result) { let refreshToken = ( moment().unix() + this.encryptor.md5(result.id + "-" + moment().unix()) ).toString(); //TODO: insert or update refresh token in DB let loginViewModel = await this.refreshTokenRepo.update_or_insert_refresh_token( result.id, refreshToken ); return loginViewModel; } else { return new ResponseModel( 102, undefined, "Wrong email or password" ); } } catch (error) { return new ResponseModel(105, undefined, error); } } async premios() { return await this.repo .createQueryBuilder("t1") .innerJoin("com_premios", "t2", "t1.id_comercio=t2.id_comercio") .where("t2.estado='activo'") .andWhere("t1.puntos_activos>=t2.puntos") .select("t2.id_premio, t2.premio") .getMany(); } }