Example #1
0
        public async Task <Response <JwtDto.Request> > GetUserInfo(ClaimsPrincipal oUser)
        {
            var oResponse = new Response <JwtDto.Request>();

            oResponse.IsSuccess = false;

            try
            {
                if (!oUser.Identity.IsAuthenticated)
                {
                    oResponse.Message = "El Usuario no esta conectado.";
                    return(oResponse);
                }

                if (oUser.Claims == null)
                {
                    oResponse.Message = "El Usuario no tiene datos.";
                    return(oResponse);
                }

                if (oUser.Claims.Count() == 0)
                {
                    oResponse.Message = "El Usuario no tiene datos.";
                    return(oResponse);
                }

                var oResult = new JwtDto.Request();
                oResult.sUsername    = oUser.Claims.FirstOrDefault(x => x.Type.Equals(ClaimTypes.Name)) ? .Value;
                oResult.sUsernameSSO = oUser.Claims.FirstOrDefault(x => x.Type.Equals(ClaimTypes.Sid)) ? .Value;
                oResult.sProfile     = oUser.Claims.FirstOrDefault(x => x.Type.Equals(ClaimTypes.Role)) ? .Value;
                oResult.sIdSession   = oUser.Claims.FirstOrDefault(x => x.Type.Equals(ClaimTypes.NameIdentifier)) ? .Value;
                oResult.nIdEmpresa   = Convert.ToInt32(oUser.Claims.FirstOrDefault(x => x.Type.Equals("nIdEmpresa"))?.Value);
                oResult.nIdLocal     = Convert.ToInt32(oUser.Claims.FirstOrDefault(x => x.Type.Equals("nIdLocal"))?.Value);

                oResponse.IsSuccess = true;
                oResponse.Data      = oResult;
                return(oResponse);
            }
            catch (Exception ex)
            {
                return(oResponse);
            }
        }
Example #2
0
        public async Task <Response <JwtDto.Response> > GenerateJwtToken(JwtDto.Request oItem)
        {
            try
            {
                var      oTokenHandler    = new JwtSecurityTokenHandler();
                var      oSecretKey       = Encoding.ASCII.GetBytes(this._settings.SecretKey);
                DateTime dCurrentDate     = DateTime.Now;
                DateTime dTokenExpiration = dCurrentDate.AddMinutes(Convert.ToInt32(this._settings.MinutesExpiration));

                var oTokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, oItem.sUsername),
                        new Claim(ClaimTypes.Sid, oItem.sUsernameSSO),
                        new Claim(ClaimTypes.Role, oItem.sProfile),
                        new Claim(ClaimTypes.NameIdentifier, oItem.sIdSession),
                        new Claim("nIdEmpresa", oItem.nIdEmpresa.ToString()),
                        new Claim("nIdLocal", oItem.nIdLocal.ToString())
                    }),
                    NotBefore          = dCurrentDate,
                    Expires            = dTokenExpiration,
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(oSecretKey), SecurityAlgorithms.HmacSha256Signature)
                };
                var    oToken = oTokenHandler.CreateToken(oTokenDescriptor);
                string sToken = oTokenHandler.WriteToken(oToken);

                var oResult = new JwtDto.Response();
                oResult.sToken           = sToken;
                oResult.dTokenExpiration = dTokenExpiration;

                var oResponse = new Response <JwtDto.Response>();
                oResponse.IsSuccess = true;
                oResponse.Data      = oResult;
                return(oResponse);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <IActionResult> Login(SSODto.Login.RequestModel oItem)
        {
            try
            {
                var oResponse = new Response <SSODto.Login.Response>();
                oResponse.IsSuccess = false;

                #region VALIDACION DE CAPTCHA

                if (string.IsNullOrEmpty(oItem.sCode))
                {
                    oResponse.Message = Messages.SSO.Login.EX008;
                    return(Ok(oResponse));
                }

                if (!this._captchaApplication.ComputeMd5Hash(oItem.sCode).Equals(CaptchaHash))
                {
                    HttpContext.Session.Remove(this._sCaptchaHashKey);
                    oResponse.Message = Messages.SSO.Login.EX009;
                    return(Ok(oResponse));
                }

                if (CaptchaHash != null)
                {
                    HttpContext.Session.Remove(this._sCaptchaHashKey);
                }

                #endregion

                #region VALIDACION DE USUARIO

                var oUser = await this._sSOApplication.Login(oItem);

                if (!oUser.IsSuccess)
                {
                    oResponse.Message = Messages.SSO.Login.EX001;
                    return(Ok(oResponse));
                }

                if (oUser.Data == null)
                {
                    oResponse.Message = Messages.SSO.Login.EX001;
                    return(Ok(oResponse));
                }

                if (oUser.Data.IdUsuario == 0)
                {
                    oResponse.Message = Messages.SSO.Login.EX001;
                    return(Ok(oResponse));
                }

                #endregion

                #region VALIDACION DE EMPRESAS

                var oEmpresas = await this._sSOApplication.GetEmpresas(oItem.sUsername);

                if (!oEmpresas.IsSuccess)
                {
                    oResponse.Message = Messages.SSO.Login.EX002;
                    return(Ok(oResponse));
                }

                if (oEmpresas.Data == null)
                {
                    oResponse.Message = Messages.SSO.Login.EX002;
                    return(Ok(oResponse));
                }

                if (oEmpresas.Data.Count == 0)
                {
                    oResponse.Message = Messages.SSO.Login.EX002;
                    return(Ok(oResponse));
                }

                #endregion

                var oTmpEmpresa = oEmpresas.Data[0];

                #region VALIDACION DE LOCALES

                if (oTmpEmpresa.Locales == null)
                {
                    oResponse.Message = Messages.SSO.Login.EX003;
                    return(Ok(oResponse));
                }

                if (oTmpEmpresa.Locales.Count == 0)
                {
                    oResponse.Message = Messages.SSO.Login.EX003;
                    return(Ok(oResponse));
                }

                #endregion

                oUser.Data.nIdEmpresa     = oTmpEmpresa.IdEmpresa;
                oUser.Data.sNombreEmpresa = oTmpEmpresa.NombreCentro;
                oUser.Data.nIdLocal       = oTmpEmpresa.Locales[0].IdLocal;
                oUser.Data.sNombreLocal   = oTmpEmpresa.Locales[0].NombreLocal;

                #region VALIDACION DE PERFILES

                var oPerfiles = await this._sSOApplication.GetPerfiles(oItem.sUsername, oUser.Data.nIdLocal.ToString());

                if (!oPerfiles.IsSuccess)
                {
                    oResponse.Message = Messages.SSO.Login.EX004;
                    return(Ok(oResponse));
                }

                if (oPerfiles.Data == null)
                {
                    oResponse.Message = Messages.SSO.Login.EX004;
                    return(Ok(oResponse));
                }

                if (oPerfiles.Data.Count == 0)
                {
                    oResponse.Message = Messages.SSO.Login.EX004;
                    return(Ok(oResponse));
                }


#if DEBUG
                // ================================
                // ===== SECCION PARA PRUEBAS =====
                // ================================
                //oPerfiles.Data[0].NombreRol = "OES";
                oPerfiles.Data[0].NombreRol = "OGTU";
                //oPerfiles.Data[0].NombreRol = "Promovilidad";
#endif

                int nCantPerfilesValidos = 0;
                foreach (var item in oPerfiles.Data)
                {
                    nCantPerfilesValidos = this._perfilesPermitidos.Count(str => str.ToUpper().Equals(item.NombreRol.ToUpper()));
                    if (nCantPerfilesValidos > 0)
                    {
                        oUser.Data.nIdPerfil     = item.IdRol;
                        oUser.Data.sNombrePerfil = item.NombreRol;
                        break;
                    }
                }

                if (nCantPerfilesValidos == 0)
                {
                    oResponse.Message = Messages.SSO.Login.EX005;
                    return(Ok(oResponse));
                }

                #endregion

                #region VALIDACION INFORMACION DE USUARIO

                var oUserInfo = await this._sSOApplication.GetUserInfo(oUser.Data.IdUsuario);

                if (!oUserInfo.IsSuccess)
                {
                    oResponse.Message = Messages.SSO.Login.EX006;
                    return(Ok(oResponse));
                }

                if (oUserInfo.Data == null)
                {
                    oResponse.Message = Messages.SSO.Login.EX006;
                    return(Ok(oResponse));
                }

                if (oUserInfo.Data.PK_eIdUsuario == 0)
                {
                    oResponse.Message = Messages.SSO.Login.EX006;
                    return(Ok(oResponse));
                }

                #endregion

                oUser.Data.sCorreo         = oUserInfo.Data.uCorElectronico;
                oUser.Data.sNombreCompleto = oUserInfo.Data.NombreCompleto;

                #region VALIDACION DE REGISTRO DE SESION EN BD

                var oRequestRegistrarSesion = new AdminDto.RegistrarSesion();
                oRequestRegistrarSesion.sUsuario      = oItem.sUsername.ToUpper();
                oRequestRegistrarSesion.sUsuarioSSO   = null;
                oRequestRegistrarSesion.sIp           = "0.0.0.0";
                oRequestRegistrarSesion.sFlag         = "1";
                oRequestRegistrarSesion.nIdSessionSSO = oUser.Data.IdUsuario;

                var oRegistroSesion = await this._adminApplication.RegistrarSesion(oRequestRegistrarSesion);

                if (!oRegistroSesion.IsSuccess)
                {
                    oResponse.Message = Messages.SSO.Login.EX007;
                    return(Ok(oResponse));
                }

                if (oRegistroSesion.Data == 0)
                {
                    oResponse.Message = Messages.SSO.Login.EX007;
                    return(Ok(oResponse));
                }

                #endregion

                oUser.Data.nIdSession = oRegistroSesion.Data; //Obtiene Id Sesion del SIROS (DB)

                #region GENERAR JWT

                var oJwt = new JwtDto.Request();
                oJwt.sUsername    = oItem.sUsername.ToUpper(); //Forzar mayuscula
                oJwt.sUsernameSSO = oUser.Data.IdUsuario.ToString();
                oJwt.sProfile     = oUser.Data.sNombrePerfil;
                oJwt.sIdSession   = oUser.Data.nIdSession.ToString();
                oJwt.nIdEmpresa   = oUser.Data.nIdEmpresa;
                oJwt.nIdLocal     = oUser.Data.nIdLocal;

#if DEBUG
                // ================================
                // ===== SECCION PARA PRUEBAS =====
                // ================================
                oJwt.nIdEmpresa = 1166;
#endif

                var oToken = await this._jwtApplication.GenerateJwtToken(oJwt);

                oUser.Data.sToken           = oToken.Data.sToken;
                oUser.Data.dTokenExpiration = oToken.Data.dTokenExpiration;

                #endregion

                oResponse.IsSuccess = true;
                oResponse.Data      = oUser.Data;
                return(Ok(oResponse));
            }
            catch (Exception ex)
            {
                _ = this._logApplication.SetLog(EnumLogType.TEXT_N_EMAIL, EnumLogCategory.ERROR, "SSO-Login", ex, oItem);
                return(Ok(new Response <Object> {
                    Message = $"[SSO]: ERR-Fallo en el servidor: {ex.StackTrace}"
                }));
            }
        }