コード例 #1
0
        public async Task <IActionResult> SignIn([FromBody] SignIn infoSignIn)
        {
            try
            {
                _logger.LogInformation(String.Format("Action: {0} | Status: {1}", "SignIn", "Begin   - " + infoSignIn.Email ?? ""));


                if (!ModelState.IsValid)
                {
                    _logger.LogWarning(String.Format("Action: {0} | Status: {1}", "SignIn", "Failure - Invalid payload"));
                    return(BadRequest(ModelState));
                }

                var existentUser = await _userService.FirstOrDefaultByEmailAsync(infoSignIn.Email);

                if (existentUser == null)
                {
                    _logger.LogWarning(String.Format("Action: {0} | Status: {1}", "SignIn", "Failure - Invalid user"));
                    return(StatusCode((int)HttpStatusCode.Unauthorized, new ErrorMessage()
                    {
                        Message = ErrorMessage.InvalidUser
                    }));
                }

                if (!_hashHelper.CompareStringToSHA256(infoSignIn.Password, existentUser.Password))
                {
                    _logger.LogWarning(String.Format("Action: {0} | Status: {1}", "SignIn", "Failure - Invalid password"));
                    return(StatusCode((int)HttpStatusCode.Unauthorized, new ErrorMessage()
                    {
                        Message = ErrorMessage.InvalidUser
                    }));
                }

                existentUser.LastLoginOn = DateTime.Now;
                List <Claim> exampleClaims = new List <Claim>()
                {
                    new Claim(_claimIdKey, existentUser.Id.ToString()),
                    new Claim(_claimLastLoginOnKey, existentUser.LastLoginOn.ToString())
                };

                String jwtToken = JwtTokenHelper.WriteJwtToken(exampleClaims, _jwtSigningKey);
                existentUser.Token       = jwtToken;
                existentUser.TokenHashed = _hashHelper.ComputeSha256FromString(_bearer + jwtToken);

                await _userService.UpdateAsync(existentUser);

                _logger.LogInformation(String.Format("Action: {0} | Status: {1}", "SignIn", "Success"));
                return(Ok(existentUser));
            }
            catch (Exception ex)
            {
                _logger.LogError(String.Format("Action: {0} | Status: {1}", "SignUp", "Exception"));
                return(StatusCode((int)HttpStatusCode.InternalServerError, new ErrorMessage()
                {
                    Message = ex.Message
                }));
            }
        }