Exemple #1
0
        public IActionResult RegistrationComplete([FromBody] RegistrationCompleteRequest registrationCompleteRequest)
        {
            Logger.Debug("Request: {0}", Framework.Common.SerializeJson.ToObject(registrationCompleteRequest));
            DateTime dateRequest   = DateTime.Now;
            var      response      = new IResponse <RegistrationCompleteResponse>();
            string   correlationId = string.Empty;

            try
            {
                #region Authorization Usuario y Contraseña
                if (string.IsNullOrEmpty(Request.Headers["Authorization"]))
                {
                    var validate = Models.Response.Error(null, "NotAuthenticated");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }

                //AuthenticationHeaderValue authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                //var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter)).Split(':');
                correlationId = Request.Headers["Correlation-Id"].ToString();

                Core.Entity.User user = new Core.Entity.User()
                {
                    Public   = registrationCompleteRequest.PublicToken,
                    UserName = registrationCompleteRequest.UserAplication,
                    Password = registrationCompleteRequest.PasswordAplication
                };
                var userAuthenticate = _user.Authenticate(user);
                if (userAuthenticate.Data == null)
                {
                    var validate = Models.Response.Error("NotAuthenticated");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }
                Core.Entity.UserPolicy userPolicy = new Core.Entity.UserPolicy()
                {
                    AppUserId = registrationCompleteRequest.AppUserId,
                    IdUser    = ((Core.Entity.User)userAuthenticate.Data).Id
                };
                Core.Entity.Policy policy = new Core.Entity.Policy()
                {
                    Name = Request.Path.Value
                };
                var userPolicyAuthorize = _userPolicy.Authorize(userPolicy, policy);
                if (userPolicyAuthorize.Data == null)
                {
                    var validate = Models.Response.Error("NotUnauthorized");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }
                #endregion

                AuthenticationHeaderValue authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialToken        = authHeader.Parameter;
                var responsetokenValidated = _tokenManager.GetPrincipalFromExpiredToken(credentialToken);

                if (responsetokenValidated.Data == null)
                {
                    response.Data    = null;
                    response.Message = responsetokenValidated.Message;
                    response.State   = responsetokenValidated.State;
                    return(BadRequest(response));
                }
                var principal   = (ClaimsPrincipal)responsetokenValidated.Data;
                var claimList   = principal.Claims.ToList();
                var verifyEmail = claimList[2].Value;

                if (!verifyEmail.Equals(registrationCompleteRequest.Email.Trim()))
                {
                    var validate = Models.Response.Error("ClientNotSession");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(BadRequest(response));
                }

                /*if (registrationCompleteRequest.Age <= 18 && (DateTime.Now.Year - registrationCompleteRequest.Birthdate.Year) <= 18)
                 * {
                 *  var validate = Models.Response.Error("UserNotAgeApropiate");
                 *  response.Data = null;
                 *  response.Message = validate.Message;
                 *  response.State = validate.State;
                 *  return BadRequest(response);
                 * }*/
                Core.Entity.Client client = new Core.Entity.Client()
                {
                    Email            = registrationCompleteRequest.Email,
                    NameComplete     = registrationCompleteRequest.NameComplete,
                    Gender           = registrationCompleteRequest.Gender,
                    Birthdate        = registrationCompleteRequest.Birthdate,
                    Age              = registrationCompleteRequest.Age,
                    Department       = registrationCompleteRequest.Department,
                    City             = registrationCompleteRequest.City,
                    Address          = registrationCompleteRequest.Address,
                    CellPhone        = registrationCompleteRequest.CellPhone,
                    Phone            = registrationCompleteRequest.Phone,
                    EducationLevel   = registrationCompleteRequest.EducationLevel,
                    Disability       = registrationCompleteRequest.Disability,
                    TypeDisability   = registrationCompleteRequest.TypeDisability,
                    ReferenceName    = registrationCompleteRequest.ReferenceName,
                    ReferencePhone   = registrationCompleteRequest.ReferencePhone,
                    ModificationUser = registrationCompleteRequest.AppUserId
                };

                var clientCreateAcountInsert = _client.UpdateRegistrationComplete(client, registrationCompleteRequest.AppUserId);
                if (!(Convert.ToInt32(clientCreateAcountInsert.Data) > 0))
                {
                    response.Data    = null;
                    response.Message = clientCreateAcountInsert.Message;
                    response.State   = clientCreateAcountInsert.State;
                    return(BadRequest(response));
                }

                response.Data = new RegistrationCompleteResponse
                {
                    Email = registrationCompleteRequest.Email,
                    RegistrationComplete = true,
                    NameComplete         = registrationCompleteRequest.NameComplete
                };
                response.Message = Models.Response.CommentMenssage("RegistrationCompleted");
                response.State   = "000";
                return(Ok(response));
            }
            catch (Exception ex)
            {
                Logger.Error("Message: {0}; Exception: {1}", ex.Message, Framework.Common.SerializeJson.ToObject(ex));
                response.Data    = null;
                response.Message = "Error General";
                response.State   = "099";
                return(BadRequest(response));
            }
            finally
            {
                DateTime dateResponse = DateTime.Now;
                Core.Entity.ConsumptionHistory consumptionHistory = new Core.Entity.ConsumptionHistory
                {
                    ApiName       = Request.Path.Value,
                    Host          = Dns.GetHostName() + ":" + Request.Host.Port,
                    CorrelationId = correlationId,
                    AppUserId     = registrationCompleteRequest.AppUserId,
                    Request       = Framework.Common.SerializeJson.ToObject(registrationCompleteRequest),
                    DateRequest   = dateRequest,
                    Response      = Framework.Common.SerializeJson.ToObject(response),
                    DateResponse  = dateResponse,
                    CodeResponse  = response.State
                };
                _consumptionHistory.Insert(consumptionHistory);
                Logger.Debug("Request: {0} Response: {1}", registrationCompleteRequest, response);
            }
        }
Exemple #2
0
        public IActionResult PreRegistration([FromBody] PreRegistrationRequest preRegistrationRequest)
        {
            Logger.Debug("Request: {0}", Framework.Common.SerializeJson.ToObject(preRegistrationRequest));
            DateTime dateRequest   = DateTime.Now;
            var      response      = new IResponse <PreRegistrationResponse>();
            string   correlationId = string.Empty;

            try
            {
                #region Authorization Usuario y Contraseña
                if (string.IsNullOrEmpty(Request.Headers["Authorization"]))
                {
                    var validate = Models.Response.Error(null, "NotAuthenticated");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }

                AuthenticationHeaderValue authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter)).Split(':');
                correlationId = Request.Headers["Correlation-Id"].ToString();

                Core.Entity.User user = new Core.Entity.User()
                {
                    Public   = preRegistrationRequest.PublicToken,
                    UserName = credentials[0],
                    Password = credentials[1]
                };
                var userAuthenticate = _user.Authenticate(user);
                if (userAuthenticate.Data == null)
                {
                    var validate = Models.Response.Error("NotAuthenticated");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }
                Core.Entity.UserPolicy userPolicy = new Core.Entity.UserPolicy()
                {
                    AppUserId = preRegistrationRequest.AppUserId,
                    IdUser    = ((Core.Entity.User)userAuthenticate.Data).Id
                };
                Core.Entity.Policy policy = new Core.Entity.Policy()
                {
                    Name = Request.Path.Value
                };
                var userPolicyAuthorize = _userPolicy.Authorize(userPolicy, policy);
                if (userPolicyAuthorize.Data == null)
                {
                    var validate = Models.Response.Error("NotUnauthorized");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }
                #endregion

                if (!Framework.Common.Tools.WellWrittenEmail(preRegistrationRequest.Email))
                {
                    var validate = Models.Response.Error("InvalidEmail");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(BadRequest(response));
                }

                if (preRegistrationRequest.Password != preRegistrationRequest.ConfirmPassword)
                {
                    var validate = Models.Response.Error("PasswordNotConfirm");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(BadRequest(response));
                }

                var passwordEncrypted     = BC.HashPassword(preRegistrationRequest.Password);
                Core.Entity.Client client = new Core.Entity.Client()
                {
                    Email                  = preRegistrationRequest.Email,
                    Ci                     = preRegistrationRequest.Ci,
                    CiExpedition           = preRegistrationRequest.CiExpedition,
                    Password               = passwordEncrypted,
                    AcceptTerms            = preRegistrationRequest.AcceptTerms,
                    VerificationTokenEmail = Framework.Common.Tools.RandomTokenString(),
                    CreationUser           = preRegistrationRequest.AppUserId
                };
                var clientCreateAcountInsert = _client.InsertIfNotexist(client);
                if (clientCreateAcountInsert.Data == null)
                {
                    response.Data    = null;
                    response.Message = clientCreateAcountInsert.Message;
                    response.State   = clientCreateAcountInsert.State;
                    return(BadRequest(response));
                }
                var newClient = (Core.Entity.Client)clientCreateAcountInsert.Data;


                var linkToken = _configuration.GetValue <string>("Connectors_Email:link") + string.Format("?token={0}", newClient.VerificationTokenEmail);
                var withOriginMessageVerificationEmail    = _configuration.GetValue <string>("Connectors_Email:WithOriginMessageVerificationEmail");
                var withoutOriginMessageVerificationEmail = _configuration.GetValue <string>("Connectors_Email:WithoutOriginMessageVerificationEmail");
                _emailmanager.SendEmail(newClient.Email, "Verificacion de Correo", withOriginMessageVerificationEmail, withoutOriginMessageVerificationEmail, "VERIFICACIÓN DE CORREO PARA ACTIVAR SU CUENTA", Request.Headers["origin"], linkToken, newClient.VerificationTokenEmail);

                response.Data = new PreRegistrationResponse
                {
                    Email = newClient.Email,
                    Ci    = newClient.Ci,
                };
                response.Message = Models.Response.CommentMenssage("PreRegistredCompleted");
                response.State   = "000";
                return(Ok(response));
            }
            catch (Exception ex)
            {
                Logger.Error("Message: {0}; Exception: {1}", ex.Message, Framework.Common.SerializeJson.ToObject(ex));
                response.Data    = null;
                response.Message = "Error General";
                response.State   = "099";
                return(BadRequest(response));
            }
            finally
            {
                DateTime dateResponse = DateTime.Now;
                Core.Entity.ConsumptionHistory consumptionHistory = new Core.Entity.ConsumptionHistory
                {
                    ApiName       = Request.Path.Value,
                    Host          = Dns.GetHostName() + ":" + Request.Host.Port,
                    CorrelationId = correlationId,
                    AppUserId     = preRegistrationRequest.AppUserId,
                    Request       = Framework.Common.SerializeJson.ToObject(preRegistrationRequest),
                    DateRequest   = dateRequest,
                    Response      = Framework.Common.SerializeJson.ToObject(response),
                    DateResponse  = dateResponse,
                    CodeResponse  = response.State
                };
                _consumptionHistory.Insert(consumptionHistory);
                Logger.Debug("Request: {0} Response: {1}", preRegistrationRequest, response);
            }
        }
Exemple #3
0
        public IActionResult RefreshToken([FromBody] TokenRefreshRequest tokenRefreshRequest)
        {
            Logger.Debug("Request: {0}", Framework.Common.SerializeJson.ToObject(tokenRefreshRequest));
            DateTime dateRequest   = DateTime.Now;
            var      response      = new IResponse <TokenRefreshResponse>();
            string   correlationId = string.Empty;

            try
            {
                #region Authorization Usuario y Contraseña
                if (string.IsNullOrEmpty(Request.Headers["Authorization"]))
                {
                    var validate = Models.Response.Error(null, "NotAuthenticated");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }

                AuthenticationHeaderValue authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentials = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter)).Split(':');
                correlationId = Request.Headers["Correlation-Id"].ToString();

                Core.Entity.User user = new Core.Entity.User()
                {
                    Public   = tokenRefreshRequest.PublicToken,
                    UserName = credentials[0],
                    Password = credentials[1]
                };
                var userAuthenticate = _user.Authenticate(user);
                if (userAuthenticate.Data == null)
                {
                    var validate = Models.Response.Error("NotAuthenticated");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }
                Core.Entity.UserPolicy userPolicy = new Core.Entity.UserPolicy()
                {
                    AppUserId = tokenRefreshRequest.AppUserId,
                    IdUser    = ((Core.Entity.User)userAuthenticate.Data).Id
                };
                Core.Entity.Policy policy = new Core.Entity.Policy()
                {
                    Name = Request.Path.Value
                };
                var userPolicyAuthorize = _userPolicy.Authorize(userPolicy, policy);
                if (userPolicyAuthorize.Data == null)
                {
                    var validate = Models.Response.Error("NotUnauthorized");
                    response.Data    = null;
                    response.Message = validate.Message;
                    response.State   = validate.State;
                    return(Unauthorized(response));
                }
                #endregion

                var    refreshToken = Request.Cookies["refreshToken"];
                string ipAddress    = "";
                if (Request.Headers.ContainsKey("X-Forwarded-For"))
                {
                    ipAddress = Request.Headers["X-Forwarded-For"];
                }
                else
                {
                    ipAddress = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
                }
                var newRefreshToken = _tokenManager.GenerateRefreshToken(ipAddress, _configuration.GetValue <double>("JwtSettings:TimeExpirationTokenRefresh"));

                var refreshTokenUpdate = _refreshToken.RefreshTokenUpdate(tokenRefreshRequest.Email, ipAddress, refreshToken, newRefreshToken.Token);
                if (refreshTokenUpdate.Data == null)
                {
                    response.Data    = null;
                    response.State   = refreshTokenUpdate.State;
                    response.Message = refreshTokenUpdate.Message;

                    return(BadRequest(response));
                }
                var clientData = (Core.Entity.Client)refreshTokenUpdate.Data;


                newRefreshToken.CreationUser = tokenRefreshRequest.AppUserId;
                newRefreshToken.EmailClient  = tokenRefreshRequest.Email;

                var refreshTokenInsertClient = _refreshToken.Insert(newRefreshToken);

                if (refreshTokenInsertClient.Data == null)
                {
                    response.Data    = null;
                    response.State   = refreshTokenInsertClient.State;
                    response.Message = refreshTokenInsertClient.Message;

                    return(BadRequest(response));
                }
                var refreshTokenRemove = _refreshToken.RemoveOldRefreshTokens(tokenRefreshRequest.Email, _configuration.GetValue <int>("JwtSettings:RefreshTokenTTL"));

                var claims = new List <Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Iat, Guid.NewGuid().ToString()),
                    new Claim(ClaimTypes.Name, clientData.NameComplete),
                    new Claim(ClaimTypes.Email, clientData.Email),
                };
                var accessToken = _tokenManager.GenerateAccessToken(claims);

                var cookieOptions = new CookieOptions
                {
                    //HttpOnly = true,
                    Expires  = DateTime.UtcNow.AddDays(_configuration.GetValue <double>("JwtSettings:TimeExpirationTokenRefresh")),
                    SameSite = SameSiteMode.None,
                    Secure   = true,
                };
                Response.Cookies.Append("refreshToken", newRefreshToken.Token, cookieOptions);

                response.Data = new TokenRefreshResponse
                {
                    Email              = clientData.Email,
                    Role               = clientData.Role == Core.Entity.Role.Admin ? "Admin" : "User",
                    Verify             = clientData.IsVerified,
                    RegistredCompleted = clientData.CompleteRegister,
                    Token              = accessToken,
                    RefreshToken       = newRefreshToken.Token
                };
                response.Message = Models.Response.CommentMenssage("TokenRefreshSuccessful");
                response.State   = "000";
                return(Ok(response));
            }
            catch (Exception ex)
            {
                Logger.Error("Message: {0}; Exception: {1}", ex.Message, Framework.Common.SerializeJson.ToObject(ex));
                response.Data    = null;
                response.Message = "Error General";
                response.State   = "099";
                return(BadRequest(response));
            }
            finally
            {
                DateTime dateResponse = DateTime.Now;
                Core.Entity.ConsumptionHistory consumptionHistory = new Core.Entity.ConsumptionHistory
                {
                    ApiName       = Request.Path.Value,
                    Host          = Dns.GetHostName() + ":" + Request.Host.Port,
                    CorrelationId = correlationId,
                    AppUserId     = tokenRefreshRequest.AppUserId,
                    Request       = Framework.Common.SerializeJson.ToObject(tokenRefreshRequest),
                    DateRequest   = dateRequest,
                    Response      = Framework.Common.SerializeJson.ToObject(response),
                    DateResponse  = dateResponse,
                    CodeResponse  = response.State
                };
                _consumptionHistory.Insert(consumptionHistory);
                Logger.Debug("Request: {0} Response: {1}", tokenRefreshRequest, response);
            }
        }