public IHttpActionResult Authenticate(UserRequest user) { Response response = new Response(); UserResponse userResponse = new UserResponse(); if (user == null) { response.Code = "002"; response.Message = "La solictud no puede estar vacia"; return(Ok(response)); } var statusAcitve = db.UserStatus.Where(x => x.ShortName == Constants.UserStatuses.Active).FirstOrDefault(); var statusInactive = db.UserStatus.Where(x => x.ShortName == Constants.UserStatuses.Inactive).FirstOrDefault(); var PendigToActive = db.UserStatus.Where(x => x.ShortName == Constants.UserStatuses.PendingToActive).FirstOrDefault(); var currentUser = db.Users.Where(x => x.IsActive == true && (x.UserName == user.UserName || x.EmailAddress == user.EmailAddress) && x.Password == user.Password).FirstOrDefault(); if (currentUser == null) { response.Code = "003"; response.Message = "Credenciales invalida"; return(Ok(response)); } if (currentUser?.StatusId == statusInactive.Id) { response.Code = "003"; response.Message = "Usuario inactivo"; return(Ok(response)); } if (currentUser?.StatusId == PendigToActive.Id) { response.Code = "005"; response.Message = "Usuario pendiente de activar"; return(Ok(response)); } if (currentUser != null) { string userParam = currentUser.UserName + "," + currentUser.Id.ToString(); var token = TokenGenerator.GenerateTokenJwt(userParam); var userRole = db.UserRoles.Where(x => x.UserId == currentUser.Id && x.IsActive == true).FirstOrDefault(); //Permissions if (userRole != null) { DTO.Response.User.Permission permissionResponse = new DTO.Response.User.Permission(); var permission = db.Entities.Where(x => x.IsActive == true).Select(x => new Entity { Id = x.Id, Description = x.Description, ShortName = x.ShortName, EntityActions = (from perm in db.RolePermissions join entAct in db.EntityActions on perm.EntityActionId equals entAct.Id where perm.RoleId == userRole.RoleId && x.Id == entAct.EntityId select new EntityActions { Id = entAct.Id, ActionName = entAct.Action, HasPermissio = perm.HasPermission }).ToList(), }).ToList(); permissionResponse.Entities = permission; userResponse.Permissions = permissionResponse; } else { response.Code = "006"; response.Message = "Este usuario no tiene un rol asignado"; return(Ok(response)); } //End Permissions //Profile List <Locators> userLocators = db.Locators.Where(x => x.PersonId == currentUser.PersonId && x.IsActive == true).Select(x => new Locators { Description = x.Description, IsMain = x.IsMain, Type = x.LocatorType.Description, }).ToList(); Profile profile = new Profile { User = new DTO.Response.User.User { Id = currentUser.Id, UserName = currentUser.UserName, Name = currentUser.Name, Surname = currentUser.Surname, EmailAddress = currentUser.EmailAddress, Image = currentUser.Image, Token = "Bearer " + token, WelcomeMessage = currentUser.Name + " " + currentUser.Surname + ", " + "sea bienvenido al sistema", MenuTemplate = string.Empty, RoleDescription = userRole.Role.Description, RoleShortName = userRole.Role.ShortName, RoleParent = userRole.Role.Parent, }, Person = currentUser.Person == null ? new Person() : new Person { FirstName = currentUser.Person.FirstName, SecondName = currentUser.Person.SecondName, Surname = currentUser.Person.Surname, secondSurname = currentUser.Person.secondSurname, BirthDate = currentUser.Person.BirthDate, FullName = currentUser.Person.FullName, Gender = currentUser.Person.Gender.Description, Locators = userLocators.Count == 0 ? new List <Locators>() : userLocators, } }; //Get menu template var _userRole = db.UserRoles .Where(x => x.UserId == currentUser.Id) .FirstOrDefault(); string menuTemplate = db.Roles.Where(x => x.ShortName == _userRole.Role.Parent && x.Enabled == true) .Select(x => x.MenuTemplate) .FirstOrDefault(); if (menuTemplate != null) { profile.User.MenuTemplate = JsonConvert.DeserializeObject <Object>(menuTemplate);; } userResponse.Profile = profile; //End Profile //System configuration string configuration = Constants.ConfigurationParameter.SystemConfigurationTemplate; if (configuration != null) { var resulConfiguration = JsonConvert.DeserializeObject <Configuration>(configuration); userResponse.Configuration = resulConfiguration; } else { userResponse.Configuration = null; } //End System configuration response.Message = "Usuario autenticado con éxito"; response.Data = userResponse; //Update user bool UpdateUserLogIn = UserService.UpdateUserLogInOut(true, user.UserName); return(Ok(response)); } else { return(Unauthorized()); } }
public IHttpActionResult Authenticate(UserRequest user) { UserResponse userResponse = new UserResponse(); string secondFactorAuthentication = Constants.ConfigurationParameter.SecondFactorAuthentication; secondFactorAuthentication = secondFactorAuthentication.ToUpper(); string currentSecuryCode = string.Empty; var currentUser = new Models.Authorization.User(); var statusAcitve = db.UserStatus.Where(x => x.ShortName == Constants.UserStatuses.Active).FirstOrDefault(); var statusInactive = db.UserStatus.Where(x => x.ShortName == Constants.UserStatuses.Inactive).FirstOrDefault(); var pendigToActive = db.UserStatus.Where(x => x.ShortName == Constants.UserStatuses.PendingToActive).FirstOrDefault(); var pendingToChangePassword = db.UserStatus.Where(x => x.ShortName == Constants.UserStatuses.PendingToChangePassword).FirstOrDefault(); string encryptPassword = Utilities.Security.Encrypt_OneWay(user.Password); var date_2FA_ExpirationTime = new DateTime(); if (user == null) { response.Code = "002"; response.Message = "La solictud no puede estar vacia"; return(Ok(response)); } //Decrypt Token2FA if (secondFactorAuthentication.Equals("TRUE") & (!string.IsNullOrEmpty(user.SecurityCode) & !string.IsNullOrEmpty(user.Token2AF))) { user.Token2AF = HttpUtility.UrlDecode(user.Token2AF); string decryptToken2FA = Utilities.Security.Decrypt_TwoWay(user.Token2AF); string[] arrayToken2AF = decryptToken2FA.Split(','); user.UserName = arrayToken2AF[0]; user.Password = arrayToken2AF[1]; currentSecuryCode = arrayToken2AF[2]; date_2FA_ExpirationTime = Convert.ToDateTime(arrayToken2AF[3]); } if (!string.IsNullOrEmpty(user.Token2AF) & !string.IsNullOrEmpty(user.SecurityCode)) { currentUser = db.Users.Where(x => x.IsActive == true && (x.UserName == user.UserName || x.EmailAddress == user.UserName) && x.Password == user.Password).FirstOrDefault(); } else { currentUser = db.Users.Where(x => x.IsActive == true && (x.UserName == user.UserName || x.EmailAddress == user.UserName) && x.Password == encryptPassword).FirstOrDefault(); } if (currentUser == null) { response.Code = "003"; response.Message = "Credenciales inválida"; return(Ok(response)); } if (currentUser?.StatusId == statusInactive.Id) { response.Code = "003"; response.Message = "Usuario inactivo"; return(Ok(response)); } if (currentUser?.StatusId == pendigToActive.Id) { response.Code = "005"; response.Message = "Usuario pendiente de activar"; return(Ok(response)); } if (currentUser?.StatusId == pendingToChangePassword.Id) { response.Code = "005"; response.Message = "Usuario pendiente de cambiar contraseña. Favor confirme el correo que ha recibido en su bandeja de entrada"; return(Ok(response)); } //Validate 2FA second factor authentication #region 2FA if (secondFactorAuthentication.Equals("TRUE") & !currentUser.IsVisitorUser) { if (string.IsNullOrEmpty(user.SecurityCode) & string.IsNullOrEmpty(user.Token2AF)) { string url_SecondFactorAuthentication = Constants.ConfigurationParameter.URL_SecondFactorAuthentication; string securityCode = Utilities.Security.GenerateSecurityCode(6); int securityCode_ExpirationTime = Convert.ToInt32(Constants.ConfigurationParameter.SecurityCode_ExpirationTime_SecondFactorAuthentication); string token2FA = string.Concat(user.UserName, ",", Utilities.Security.Encrypt_OneWay(user.Password), ",", securityCode, ",", DateTime.Now.AddMinutes(securityCode_ExpirationTime).ToString()); token2FA = Utilities.Security.Encrypt_TwoWay(token2FA); string url2FA = string.Concat(url_SecondFactorAuthentication, "/", HttpUtility.UrlEncode(token2FA)); string sendEmailAlert2FA = Constants.ConfigurationParameter.SendEmailAlert_SecondFactorAuthentication; sendEmailAlert2FA = sendEmailAlert2FA.ToUpper(); string sendSMSAlert2FA = Constants.ConfigurationParameter.SendSMSAlert_SecondFactorAuthentication; sendSMSAlert2FA = sendSMSAlert2FA.ToUpper(); //Send Email Alert #region Send Email Alert string confirmation_Operation = AlertService.Alert.GetOperation("AccessConfirmation"); confirmation_Operation = confirmation_Operation.Replace("@UserName", currentUser.UserName); confirmation_Operation = confirmation_Operation.Replace("@SecurityCode", securityCode); confirmation_Operation = confirmation_Operation.Replace("@Time", securityCode_ExpirationTime.ToString()); var requestEmail = new Mail(); var responseEmail = new AlertService.Base.ClientResponse <bool>(); if (sendEmailAlert2FA.Equals("TRUE")) { //Validate email if (string.IsNullOrEmpty(currentUser.EmailAddress)) { response.Code = "005"; response.Message = string.Concat("Estimado ", currentUser.UserName, " usted no tiene un correo registrado, para recibir notificaciones"); return(Ok(response)); } requestEmail.MailAddresses = currentUser.EmailAddress; requestEmail.Subject = "Confirmar acceso"; requestEmail.Body = confirmation_Operation; responseEmail = AlertService.Alert.SendMail(requestEmail); } #endregion //Send SMS Alert #region Send SMS Alert var requestSMS = new SMS(); var responseSMS = new AlertService.Base.ClientResponse <bool>(); if (sendSMSAlert2FA.Equals("TRUE")) { //Validate phoneNumber if (string.IsNullOrEmpty(currentUser.PhoneNumber) & !responseEmail.Data) { response.Code = "005"; response.Message = string.Concat("Estimado ", currentUser.UserName, " usted no tiene un número movil registrado, para recibir notificaciones"); return(Ok(response)); } if (!string.IsNullOrEmpty(currentUser.PhoneNumber)) { requestSMS.Body = string.Concat("Saludo estimado ", currentUser.UserName, " su codigo de seguridad es: ", securityCode, " y expira en ", securityCode_ExpirationTime.ToString(), " minutos."); requestSMS.PhoneNumber = currentUser.PhoneNumber; responseSMS = AlertService.Alert.SendSMS(requestSMS); } } ; #endregion if (responseEmail.Data || responseSMS.Data) { return(Content(HttpStatusCode.Redirect, url2FA)); } else { response.Code = "005"; response.Message = "No se encontró un canal disponible, para enviar el código de seguridad"; return(Ok(response)); } } if (!string.IsNullOrEmpty(user.SecurityCode) & !string.IsNullOrEmpty(user.Token2AF)) { if (!user.SecurityCode.Equals(currentSecuryCode)) { response.Code = "005"; response.Message = "Código invalido, favor verifique el mismo ó vuelva a iniciar sesión"; return(Ok(response)); } if (DateTime.Now > date_2FA_ExpirationTime) { response.Code = "005"; response.Message = string.Concat("Estimado ", currentUser.UserName, " su código ha expirado, favor vuelva a iniciar sesión"); return(Ok(response)); } } } #endregion if (currentUser != null) { int expireTime = Convert.ToInt32(Constants.ConfigurationParameter.LoginTime); string lifeDate = DateTime.Now.AddMinutes(expireTime).ToString(); string payLoad = currentUser.UserName + "," + currentUser.Id.ToString() + "," + lifeDate; var token = TokenGenerator.GenerateTokenJwt(payLoad); var userRole = db.UserRoles.Where(x => x.UserId == currentUser.Id && x.IsActive == true).FirstOrDefault(); //Permissions if (userRole != null) { DTO.Response.User.Permission permissionResponse = new DTO.Response.User.Permission(); var permission = db.Entities.Where(x => x.IsActive == true).Select(x => new Entity { Id = x.Id, Description = x.Description, ShortName = x.ShortName, EntityActions = (from perm in db.RolePermissions join entAct in db.EntityActions on perm.EntityActionId equals entAct.Id where perm.RoleId == userRole.RoleId && x.Id == entAct.EntityId select new EntityActions { Id = entAct.Id, ActionName = entAct.Action, HasPermissio = perm.HasPermission }).ToList(), }).ToList(); permissionResponse.Entities = permission; userResponse.Permissions = permissionResponse; } else { response.Code = "006"; response.Message = "Este usuario no tiene un rol asignado"; return(Ok(response)); } //End Permissions //Profile List <Locators> userLocators = db.Locators.Where(x => x.PersonId == currentUser.PersonId && x.IsActive == true).Select(x => new Locators { Description = x.Description, IsMain = x.IsMain, Type = x.LocatorType.Description, }).ToList(); Profile profile = new Profile { User = new DTO.Response.User.User { Id = currentUser.Id, UserName = currentUser.UserName, Name = currentUser.Name, Surname = currentUser.Surname, EmailAddress = currentUser.EmailAddress, Image = currentUser.Image, Token = "Bearer " + token, WelcomeMessage = currentUser.Name + " " + currentUser.Surname + ", " + "sea bienvenido al sistema", MenuTemplate = string.Empty, RoleDescription = userRole.Role.Description, RoleShortName = userRole.Role.ShortName, RoleParent = userRole.Role.Parent, IsVisitorUser = currentUser.IsVisitorUser, //Permissions CanEdit = userRole.Role.CanEdit, CanDelete = userRole.Role.CanDelete, CanCreate = userRole.Role.CanCreate, }, Person = currentUser.Person == null ? new Person() : new Person { FirstName = currentUser.Person.FirstName, SecondName = currentUser.Person.SecondName, Surname = currentUser.Person.Surname, secondSurname = currentUser.Person.secondSurname, BirthDate = currentUser.Person.BirthDate, FullName = currentUser.Person.FullName, Gender = currentUser.Person.Gender.Description, Locators = userLocators.Count == 0 ? new List <Locators>() : userLocators, } }; //Get menu template var _userRole = db.UserRoles .Where(x => x.UserId == currentUser.Id) .FirstOrDefault(); string menuTemplate = db.Roles.Where(x => x.ShortName == _userRole.Role.Parent && x.Enabled == true) .Select(x => x.MenuTemplate) .FirstOrDefault(); if (menuTemplate != null) { profile.User.MenuTemplate = JsonConvert.DeserializeObject <Object>(menuTemplate);; } userResponse.Profile = profile; //End Profile //System configuration string configuration = Constants.ConfigurationParameter.SystemConfigurationTemplate; if (configuration != null) { var resulConfiguration = JsonConvert.DeserializeObject <Configuration>(configuration); userResponse.Configuration = resulConfiguration; } else { userResponse.Configuration = null; } //End System configuration response.Message = "Usuario autenticado con éxito"; response.Data = userResponse; //Update user bool UpdateUserLogIn = UserService.UpdateUserLogInOut(true, user.UserName, 0); return(Ok(response)); } else { return(Unauthorized()); } }