Beispiel #1
0
        public async Task <IActionResult> Login(
            [FromBody] UserViewModel usuario,
            [FromServices] TokenConfigurations tokenConfiguration,
            [FromServices] SignConfigurationToken signinConfiguration,
            [FromServices] IUserAppService usuarioAppService)
        {
            #region .::Method logs request
            logsAppService.SaveLog(this.HttpContext.Request.Headers);
            #endregion

            if (usuario is null || !ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var objRetorno = new BaseViewModel <TokenViewModel>();

            var viewModel = _mapper.Map <UserDomain>(usuario);

            var userBase = await usuarioAppService.ValidingUserAsync(viewModel);

            if (userBase != null)
            {
                var identity = new ClaimsIdentity(
                    new GenericIdentity(userBase.Login, "Login"),
                    new[]
                {
                    new Claim(JwtRegisteredClaimNames.Jti, userBase.UserId.ToString()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, userBase.Email)
                }
                    );

                var dateCreate  = DateTime.Now;
                var dateExpired = dateCreate + TimeSpan.FromDays(tokenConfiguration.ExpireIn);

                var handler = new JwtSecurityTokenHandler();

                var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                {
                    Issuer    = tokenConfiguration.Issuer,
                    Audience  = tokenConfiguration.Audience,
                    Subject   = identity,
                    NotBefore = dateCreate,
                    Expires   = dateExpired,

                    SigningCredentials = new SigningCredentials(
                        new SymmetricSecurityKey(
                            Encoding.UTF8.GetBytes(tokenConfiguration.SigningKey)),
                        SecurityAlgorithms.HmacSha256
                        )
                });

                var token = handler.WriteToken(securityToken);
                objRetorno.Message = objRetorno.Success == true?message.AUTH_SUCCESS() : message.AUTH_ERROR();

                objRetorno.ObjectReturn = new TokenViewModel()
                {
                    UserId       = userBase.UserId,
                    Name         = userBase.Name,
                    Mail         = userBase.Email,
                    Authenticate = true,
                    CreateAt     = dateCreate,
                    Expires      = dateExpired,
                    Token        = token
                };

                #region .::Methods Logs
                logsAppService.SaveLog(objRetorno);
                #endregion

                return(Ok(objRetorno));
            }

            return(Unauthorized());
        }