public async Task <IActionResult> Login([FromBody] User request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var user = await _bus.Send(new GetUserCommand(request));

            if (user == null)
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, request.Username),
                new Claim(ClaimTypes.SerialNumber, request.Password),
                new Claim(ClaimTypes.Role, "User")
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(request.Username, claims, DateTime.Now);

            return(Ok(new LoginResult
            {
                UserName = request.Username,
                Role = "User",
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString
            }));
        }
        public async Task <IActionResult> Register([FromBody] RegisterRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var user = await _userService.RegisterUser(request.Username, request.Password, request.Email);

            if (user == null)
            {
                return(BadRequest("user already exist"));
            }
            var claims = new[] {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            };
            var           jwtResult   = _jwtAuthManager.GenerateTokens(user.UserName, claims, DateTime.Now);
            LoginResponse loginResult = new LoginResponse
            {
                Username     = user.UserName,
                AccessToken  = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString,
            };

            SetTokenCookie(jwtResult.AccessToken);
            return(Ok(loginResult));
        }
Exemplo n.º 3
0
        public async Task <ActionResult> Login([FromBody] LoginRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!await _userService.IsValidUserCredentials(request.Username, request.Password))
            {
                return(Unauthorized());
            }

            var role = await _userService.GetUserRole(request.Username);

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, request.Username),
                new Claim(ClaimTypes.Role, role)
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(request.Username, claims, DateTime.Now);

            _logger.LogInformation($"User [{request.Username}] logged in the system.");
            return(Ok(new LoginResult
            {
                UserName = request.Username,
                Role = role,
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString
            }));
        }
Exemplo n.º 4
0
        public async Task <ActionResult> Login([FromBody] LoginRequest loginRequest)
        {
            Console.WriteLine("customer/login end-point");
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var jsonLoginRequest = JsonConvert.SerializeObject(loginRequest);
            var client           = new RestClient("http://localhost:8080/");
            var request          = new RestRequest("auth/customer/login", Method.POST)
            {
                RequestFormat = DataFormat.Json
            };

            request.AddJsonBody(jsonLoginRequest);

            var response = await client.ExecuteAsync(request);

            if (response.IsSuccessful)
            {
                Console.WriteLine(response.Content);

                Customer foundCustomer = JsonConvert.DeserializeObject <Customer>(response.Content);
                Console.WriteLine(foundCustomer.FirstName + foundCustomer.LastName);

                var jwtResult = _jwtAuthManager.GenerateTokens(foundCustomer, new Claim[0], DateTime.Now);

                return(Ok(new LoginResult
                {
                    Id = foundCustomer.Id,
                    Email = loginRequest.Email,
                    FirstName = foundCustomer.FirstName,
                    LastName = foundCustomer.LastName,
                    Role = "customer",
                    AccessToken = jwtResult.AccessToken,
                    RefreshToken = jwtResult.RefreshToken.TokenString
                }));
            }

            return(Unauthorized());
            // if (!_userService.IsValidUserCredentials(request.UserName, request.Password))
            // {
            //     return Unauthorized();
            // }

            // var role = _userService.GetUserRole(request.UserName);
            // var claims = new[]
            // {
            //     new Claim(ClaimTypes.Name,request.UserName),
            //     new Claim(ClaimTypes.Role, role)
            // };
        }
Exemplo n.º 5
0
        public ActionResult Login([FromBody] LoginRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!_userService.IsValidUserCredentials(request.user_name, request.password))
            {
                return(Unauthorized());
            }

            var idrole = _userService.GetUserIDAndRole(request.user_name);
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, request.user_name),
                new Claim(ClaimTypes.Role, idrole.Item2)
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(request.user_name, claims, DateTime.Now);

            _logger.LogInformation($"User [{request.user_name}] logged in the system.");
            return(Ok(new LoginResult
            {
                user_id = idrole.Item1.ToString(),
                user_name = request.user_name,
                role = idrole.Item2,
                access_token = jwtResult.access_token,
                refresh_token = jwtResult.refresh_token.token_string
            }));
        }
Exemplo n.º 6
0
        public async Task <ActionResult> Login([FromBody] User user)
        {
            if (user == null)
            {
                return(BadRequest());
            }

            var result = await userRepository.ValidateUser(user.UserName, user.Password);

            if (result != null)
            {
                var role   = result.Role;
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, result.UserName),
                    new Claim(ClaimTypes.Role, role)
                };

                var jwtResult = jwtAuthManager.GenerateTokens(result.UserName, claims, DateTime.Now);
                logger.LogInformation($"User [{result.UserName}] logged in the system.");
                return(Ok(new LoginResult
                {
                    UserName = result.UserName,
                    Role = role,
                    AccessToken = jwtResult.AccessToken,
                    RefreshToken = jwtResult.RefreshToken.TokenString
                }));
            }
            else
            {
                return(Unauthorized("Login failed"));
            }
        }
Exemplo n.º 7
0
        public async Task <ActionResult <LoginResult> > login([FromBody] UserCreditials creditials)
        {
            var user = await _userResource.Login(creditials.UserName, creditials.Password);

            if (user.UserId == 0)
            {
                return(BadRequest());
            }
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, creditials.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString())
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(user.UserId, creditials.UserName, claims, DateTime.Now);

            return(Ok(new LoginResult
            {
                Username = user.Username,
                AvatarFilePath = user.AvatarFilePath,
                Color = user.Color,
                Email = user.Email,
                UserId = user.UserId,
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString
            }));
        }
Exemplo n.º 8
0
        public async Task <IActionResult> Login([FromBody] LoginRequest request)
        {
            var user = await _userService.GetUserByLogin(request.Login);

            var userRole = await _roleService.GetRoleIdyById(user.RoleId);

            if (user == null)
            {
                return(BadRequest("Пользователь с таким именем не зарегистрирован!"));
            }
            using (var hmac = new HMACSHA512(user.PasswordSalt))
            {
                var computesHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(request.Password));
                for (int i = 0; i < computesHash.Length; i++)
                {
                    if (computesHash[i] != user.PasswordHash[i])
                    {
                        return(Unauthorized("Пользователь с таким именем не зарегистрирован!"));//ошибка авторизации. не смог авторизоваться
                    }
                }
            }

            JwtAuthResult jwtResult;

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, request.Login),
                new Claim(ClaimTypes.Role, userRole.Name)
            };

            jwtResult = _jwtAuthManager.GenerateTokens(request.Login, claims);
            return(Ok(jwtResult));
        }
Exemplo n.º 9
0
        public async Task <ActionResult <LoginResult> > GetUserLogin([FromBody] Credential credential)
        {
            if (ModelState.IsValid)
            {
                User user = await _userProvider.GetUserLogin(credential.Username, credential.Password);

                if (user != null)
                {
                    var claims = new[]
                    {
                        new Claim(ClaimTypes.Name, user.Credential.Username),
                        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                        new Claim(ClaimTypes.Role, "Member")
                    };
                    var jwtResult = _jwtAuthManager.GenerateTokens(user.Credential.Username, claims, DateTime.Now);

                    LoginResult result = new LoginResult
                    {
                        Username     = user.Credential.Username,
                        UserId       = user.Id,
                        AccessToken  = jwtResult.AccessToken,
                        RefreshToken = jwtResult.RefreshToken.TokenString
                    };
                    return(Ok(result));
                }
                else
                {
                    return(NoContent());
                }
            }
            return(BadRequest());
        }
Exemplo n.º 10
0
        public ActionResult Login([FromBody] LoginRequest request)
        {
            if (String.IsNullOrEmpty(request.username) || String.IsNullOrEmpty(request.password))
            {
                return(BadRequest());
            }

            if (!_userService.IsValidUserCredentials(request.username, request.password))
            {
                return(Unauthorized());
            }

            User user   = _userService.findUserByUserName(request.username);
            var  claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, request.username),
                new Claim("Id", request.username)
            };

            if (user.isAdmin)
            {
                claims.Add(new Claim("Role", "admin"));
            }

            var jwtResult = _jwtAuthManager.GenerateTokens(request.username, claims.ToArray(), DateTime.Now);

            _logger.LogInformation($"User [{request.username}] logged in the system.");
            return(Ok(new LoginResult
            {
                username = request.username,
                accessToken = jwtResult.accessToken,
                refreshToken = jwtResult.refreshToken.tokenString
            }));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Post([FromBody] UserDTO userDTO)
        {
            var user = await _userAppService.GetAsync(userDTO.Login, userDTO.Password);

            if (user == null)
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, user.Login),
                new Claim(ClaimTypes.Role, "Admin")
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(user.Login, claims, DateTime.Now);

            return(Ok(new
            {
                UserName = userDTO.Login,
                Role = "Admin",
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString
            }));
        }
Exemplo n.º 12
0
        public async Task <IActionResult> AuthenticateUser([FromBody] AuthenticateUserDto authUser)
        {
            ServiceResponse <GetUserDto> response = await _userService.AuthenticateUser(authUser);

            if (response.Data == null)
            {
                return(Unauthorized(response));
            }
            else
            {
                ServiceResponse <JwtTokens> respjwtTokens = new ServiceResponse <JwtTokens>();

                _jwtAuthManager.RemoveRefreshTokenByUserName(authUser.Email);
                var claims = new[]
                {
                    new Claim("Email", authUser.Email),
                    new Claim("Role", "role"),
                    new Claim("Activated", response.Data.Status == UserStatus.Disabled ? "False": "True")
                };
                var jwtResult = _jwtAuthManager.GenerateTokens(authUser.Email, claims, DateTime.Now);
                _logger.LogInformation($"User [{authUser.Email}] logged in the system.");
                JwtTokens jwtTokens = new JwtTokens();
                jwtTokens.AccessToken  = jwtResult.AccessToken.ToString();
                jwtTokens.RefreshToken = jwtResult.RefreshToken.TokenString;
                respjwtTokens.Data     = jwtTokens;
                respjwtTokens.Message  = "Validated";
                return(Ok(jwtResult));
            }
        }
Exemplo n.º 13
0
        public ActionResult Login([FromBody] LoginRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var CurrentUser = _userService.GetUserByEmail(request.Email);

            if (CurrentUser == null || !BC.Verify(request.Password, CurrentUser.Password))
            {
                return(Unauthorized());
            }


            var claims = new[]
            {
                new Claim(ClaimTypes.Name, CurrentUser.UserName),
                new Claim(ClaimTypes.Email, CurrentUser.Email)
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(CurrentUser.UserName, claims, DateTime.Now);

            _logger.LogInformation($"User [{CurrentUser.UserName}] logged in the system.");
            return(Ok(new LoginResult
            {
                UserId = CurrentUser.Id,
                UserName = CurrentUser.UserName,
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString,
                Email = CurrentUser.Email,
                IsEmailConfirmed = CurrentUser.IsEmailConfirmed,
                ShippingAddress = CurrentUser.ShippingAddress,
                Orders = CurrentUser.Orders
            }));
        }
        public ActionResult <LoginResult> Login([FromBody] LoginRequest request)
        {
            if (!_flightCenterSystem.TryLogin(request.UserName, request.Password, out ILoginToken loginToken, out FacadeBase facade))//validate the login credentials
            {
                return(Unauthorized());
            }

            dynamic user = loginToken.GetType().GetProperties()[0].GetValue(loginToken); //Get the user from the login token as dynamic object

            string role = user.User.UserRole.ToString();                                 //get the user role

            var claims = new[]                                                           //generate claims array
            {
                new Claim(ClaimTypes.Name, user.User.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.User.Id.ToString()),
                new Claim(ClaimTypes.Role, role),
                new Claim("LoginToken", loginToken.ToString()),
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(request.UserName, claims, DateTime.Now);//Invoke GenerateTokens and get JWTAuthResult

            _logger.LogInformation($"User [{request.UserName}] logged in the system.");
            return(Ok(new LoginResult
            {
                UserName = request.UserName,
                Role = role,
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString
            }));
        }
Exemplo n.º 15
0
        public async Task <IActionResult> SignUp(LoginRequest request)
        {
            var result = await _usersService.TryInsertIfUniqueAsync(request);

            if (result == null)
            {
                return(Unauthorized("Username exists. Try another one"));
            }

            var claims    = _jwtAuthManager.GenerateClaims(result.UserId, result.UserName);
            var jwtResult = _jwtAuthManager.GenerateTokens(result.UserId, result.UserName, claims, DateTime.Now);

            result.AccessToken  = jwtResult.AccessToken;
            result.RefreshToken = jwtResult.RefreshToken.TokenString;

            return(Ok(result));
        }
Exemplo n.º 16
0
        public async Task <IActionResult> LogIn(string userName, string password)
        {
            try
            {
                if (userName == null || password == null)
                {
                    return(BadRequest());
                }


                var result = await _signInManager.PasswordSignInAsync(userName, password, false, lockoutOnFailure : false);


                if (!result.Succeeded)
                {
                    return(Unauthorized("Wrong Password"));
                }
                //asgakini islet
                //if (!passwordOK)
                //    return StatusCode(StatusCodes.Status401Unauthorized, "Incorrect username or password");

// ###########         Belke lazim olar deye
                //if (existingUser == null)
                //{
                //    response = Request.CreateResponse(HttpStatusCode.NotFound);
                //}
                //else
                //{
                //    var loginSuccess =
                //        string.Equals(EncryptPassword(model.Password, existingUser.Salt),
                //            existingUser.PasswordHash);

                var userId = _unitOfWork.UserApplication.FirstOrDefault(u => u.UserName == userName).Id;

                var claims = new[] {
                    new Claim(ClaimTypes.NameIdentifier, userId),
                    new Claim(ClaimTypes.Name, userName),
                    new Claim(ClaimTypes.Role, "Manager"),
                    new Claim(JwtRegisteredClaimNames.UniqueName, userName),
                    new Claim(JwtRegisteredClaimNames.Sub, userName),
                    new Claim(JwtRegisteredClaimNames.Email, userName)
                };

                var jwtResult = _jwtAuthManager.GenerateTokens(userName, claims, DateTime.Now);
                var UserName  = User.Identity.Name;

                return(Ok(new LoginResult
                {
                    AccessToken = jwtResult.AccessToken,
                    RefreshToken = jwtResult.RefreshToken,
                    UserName = userName
                }));
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, data = ex.Message + "\n" + ex.InnerException.Message }));
            }
        }
        private JwtAuthResult JwtAuthResult(string userId, string email)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, userId)
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(email, claims, DateTime.Now);

            return(jwtResult);
        }
Exemplo n.º 18
0
        public async Task <LoginResult> AuthenticateAsync(LoginRequest request)
        {
            var CurrentUser = await userServices.GetUserByEmailAsync(request.Email);

            if (CurrentUser == null)
            {
                throw new Exception($"User with {request.Email} not found.");
            }

            if (request.Email == configuration["ShopOwner:Email"] && request.Password == configuration["ShopOwner:Password"])
            {
                CurrentUser = new User
                {
                    Id               = "maxshopowner",
                    Email            = request.Email,
                    Password         = BC.HashPassword(request.Password),
                    Role             = UserRoles.MaxShopOwner,
                    UserName         = "******",
                    IsEmailConfirmed = true
                };
            }

            if (!BC.Verify(request.Password, CurrentUser.Password))
            {
                throw new Exception($"Credentials for '{request.Email} aren't valid'.");
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, CurrentUser.UserName),
                new Claim(ClaimTypes.Email, CurrentUser.Email),
                new Claim(ClaimTypes.Role, CurrentUser.Role)
            };

            var jwtResult = jwtAuthManager.GenerateTokens(CurrentUser.UserName, claims, DateTime.Now);

            logger.LogInformation($"User [{request.Email}] logged in the system.");

            return(new LoginResult
            {
                UserId = CurrentUser.Id,
                Role = CurrentUser.Role,
                UserName = CurrentUser.UserName,
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString,
                Email = CurrentUser.Email,
                IsEmailConfirmed = CurrentUser.IsEmailConfirmed,
                Contact = CurrentUser.Contact,
            });
        }
Exemplo n.º 19
0
        public async Task <CustomerAuthViewModel> AuthenticateAsync(string email, string password)
        {
            var passwordHashed = AuthenticateHelper.HashPassword(password);
            var customer       = await _customerRepository.AuthenticateCustomerAsync(email, passwordHashed);

            if (customer == null)
            {
                return(null);
            }
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, customer.Id.ToString()),
                new Claim(ClaimTypes.Name, email),
                new Claim("Scope", "Customer")
            };
            var jwtResult = _jwtAuthManager.GenerateTokens(email, claims, DateTime.Now);

            return(new CustomerAuthViewModel
            {
                Customer = customer,
                JwtResult = jwtResult
            });
        }
Exemplo n.º 20
0
        public ActionResult Login([FromBody] LoginRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var CurrentUser = _userService.GetUserByEmail(request.Email);

            if (request.Email == _configuration["ShopOwner:Email"] && request.Password == _configuration["ShopOwner:Password"])
            {
                CurrentUser = new User
                {
                    Id               = "maxshopowner",
                    Email            = request.Email,
                    Password         = BC.HashPassword(request.Password),
                    Role             = UserRoles.MaxShopOwner,
                    UserName         = "******",
                    IsEmailConfirmed = true
                };
            }

            if (CurrentUser == null || !BC.Verify(request.Password, CurrentUser.Password))
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, CurrentUser.UserName),
                new Claim(ClaimTypes.Email, CurrentUser.Email),
                new Claim(ClaimTypes.Role, CurrentUser.Role)
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(CurrentUser.UserName, claims, DateTime.Now);

            return(Ok(new LoginResult
            {
                UserId = CurrentUser.Id,
                Role = CurrentUser.Role,
                UserName = CurrentUser.UserName,
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString,
                Email = CurrentUser.Email,
                IsEmailConfirmed = CurrentUser.IsEmailConfirmed,
                Contact = CurrentUser.Contact,
                Notifications = CurrentUser.Notifications
            }));
        }
Exemplo n.º 21
0
        private string CreateToken(User user)
        {
            _jwtAuthManager.RemoveRefreshTokenByUserName(user.Name);
            var claims = new[]
            {
                new Claim("Email", user.Name),
                new Claim("Role", "role"),
                new Claim("Activated", user.Status == UserStatus.Enabled ? "Yes": "No"),
                new Claim("Id", user.Id.ToString()),
                new Claim("Name", user.Name)
            };
            var jwtResult = _jwtAuthManager.GenerateTokens(user.Name, claims, DateTime.Now);

            return(jwtResult.AccessToken);
        }
Exemplo n.º 22
0
        public ActionResult LoginUser([FromBody] string credentials)
        {
            string         responseData = string.Empty;
            UserInputModel requestData  = JsonConvert.DeserializeObject <UserInputModel>(credentials);
            UserInputModel userData     = _userService.ValidateCredentials(requestData);
            UserViewModel  user         = new UserViewModel();

            if (userData != null)
            {
                user.userDetails = userData;

                string  userType = Enum.GetName(typeof(USERTYPE), userData.User_Type_Id);
                string  role     = Enum.GetName(typeof(USERROLE), userData.User_Role_Id);
                Claim[] claims   = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, userData.Id.ToString()),
                    new Claim(ClaimTypes.Role, role)
                };

                var jwtResult = _jwtAuthManager.GenerateTokens(userData.Id.ToString(), claims, DateTime.Now);
                _logger.LogInformation($"User [{userData.Id}] logged in the system.");

                UserTokenModel userToken = new UserTokenModel()
                {
                    UserId                 = userData.Id,
                    Token                  = jwtResult.AccessToken,
                    RefreshToken           = jwtResult.RefreshToken.TokenString,
                    RefreshTokenExpiration = jwtResult.RefreshToken.ExpireAt,
                    Created_On             = DateTime.Now
                };
                user.userToken = userToken;
                if (userToken.Token.Length > 0)
                {
                    responseData = JsonConvert.SerializeObject(user);
                }
            }
            else
            {
                user = null;
            }
            return(Ok(user));
        }
Exemplo n.º 23
0
        public LoginResult Login(string login, string password)
        {
            var zaposlenik = context.Zaposlenici.FirstOrDefault(z => z.Login == login && z.Password == password);

            if (zaposlenik != null)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.GivenName, login)
                };
                var jwtResult   = jwtAuthManager.GenerateTokens(login, claims, DateTime.Now);
                var loginResult = new LoginResult
                {
                    Zaposlenik   = zaposlenik,
                    AccessToken  = jwtResult.AccessToken,
                    RefreshToken = jwtResult.RefreshToken.TokenString
                };
                return(loginResult);
            }
            return(null);
        }
Exemplo n.º 24
0
        public LoginResult Login(string email, string password)
        {
            var user = context.Users.FirstOrDefault(u => u.Email == email && u.Password == password);

            if (user != null)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Email, email)
                };
                var jwtResult   = jwtAuthManager.GenerateTokens(email, claims, DateTime.Now);
                var loginResult = new LoginResult
                {
                    User         = user,
                    AccessToken  = jwtResult.AccessToken,
                    RefreshToken = jwtResult.RefreshToken.TokenString
                };
                return(loginResult);
            }
            return(null);
        }
Exemplo n.º 25
0
        public async Task <ApplicationResponse <LoginResponseDto> > Authenticate(LoginRequestDto authenticateRequest)
        {
            var userByMail = await _userRepository.GetAsync(x => x.EMail == authenticateRequest.EMail);

            if (userByMail is null)
            {
                return(new ApplicationResponse <LoginResponseDto>(ResponseState.Error,
                                                                  ResponseMessage.Error.UserNotFound));
            }

            var hashPassword = SecurityHelper.HashPassword(authenticateRequest.Password, userByMail.PasswordSalt);

            var user = await _userRepository.GetAsync(x =>
                                                      x.EMail == authenticateRequest.EMail && x.Password == hashPassword);

            if (user is null)
            {
                return(new ApplicationResponse <LoginResponseDto>(ResponseState.Error,
                                                                  ResponseMessage.Error.UserNotFound));
            }

            var claims = new List <Claim>
            {
                new("id", user.Id),
                new("email", user.EMail),
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(user.EMail, claims.ToArray());
            await _tokenManager.AssignToken(jwtResult.AccessToken, jwtResult.RefreshToken);

            return(new ApplicationResponse <LoginResponseDto>(new LoginResponseDto
            {
                Id = user.Id,
                Name = user.Name,
                Surname = user.Surname,
                Mail = user.EMail,
                Company = user.Company?.Name,
                AccessToken = jwtResult.AccessToken,
            }));
        }
Exemplo n.º 26
0
        public async Task <IActionResult> Post(UserLoginModel loginUser)
        {
            if (loginUser != null)
            {
                var existingUser = await _userManager.FindByNameAsync(loginUser.UserName);

                var passwordMatch = _userManager.PasswordHasher.VerifyHashedPassword(existingUser, existingUser.PasswordHash, loginUser.Password);

                if (existingUser != null && passwordMatch.Equals(PasswordVerificationResult.Success))
                {
                    var claims = new[] {
                        new Claim(ClaimTypes.Name, loginUser.UserName)
                    };
                    var jwtResult = _jwtManager.GenerateTokens(loginUser.UserName, claims, DateTime.Now);
                    return(new OkObjectResult(new UserLoginResultModel {
                        UserName = loginUser.UserName,
                        AccessToken = jwtResult.AccessToken
                    }));
                }
            }
            return(new UnauthorizedObjectResult("Incorrect login credentials."));
        }
Exemplo n.º 27
0
        public async Task <ActionResult> LoginAsync([FromBody] LoginRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!(await _userService.IsValidUserCredentialsAsync(request.UserName, request.Password)))
            {
                return(Unauthorized());
            }

            JwtAuthResult jwtResult = _jwtAuthManager.GenerateTokens(request.UserName, new Claim[] { }, DateTime.Now);

            _logger.LogInformation($"User [{request.UserName}] logged in the system.");
            return(Ok(new LoginResult
            {
                UserName = request.UserName,
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString
            }));
        }
Exemplo n.º 28
0
        public async Task <ActionResult> Login([FromBody] LoginRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!await _userService.IsValidUserCredentials(request.Email, request.Password))
            {
                return(Unauthorized());
            }

            // var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var User = _userService.GetUser(request.Email, request.Password);

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, request.Email),
                new Claim("UserId", Convert.ToString(User.Result.UserId)),
                new Claim("Username", User.Result.FirstName + ' ' + User.Result.LastName),
                new Claim("TypeUser", User.Result.TypeUser),
                new Claim("CreatedByAdminID", User.Result.CreatedByAdminID.ToString())
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(request.Email, claims, DateTime.Now);

            // _logger.LogInformation($"User [{request.Email}] logged in the system.");
            return(Ok(new LoginResult
            {
                Email = request.Email,
                UserId = User.Result.UserId,
                Username = User.Result.FirstName + ' ' + User.Result.LastName,
                TypeUser = User.Result.TypeUser,
                CreatedByAdminID = User.Result.CreatedByAdminID,
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString
            }));
        }
Exemplo n.º 29
0
        public IActionResult Login([FromBody] User login)
        {
            IActionResult response = Unauthorized();

            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }

                if (!_userService.IsValidUserCredentials(login.UserName, login.Password))
                {
                    return(Unauthorized());
                }

                var claims = new[]
                {
                    new Claim("username", login.UserName),
                    new Claim("userid", Convert.ToString(login.UserId))
                };

                var jwtResult = _jwtAuthManager.GenerateTokens(login.UserName, claims, DateTime.Now);
                _loggerService.Info("User:"******"logged in the system.");
                return(Ok(new
                {
                    UserName = login.UserName,
                    AccessToken = jwtResult.AccessToken,
                    RefreshToken = jwtResult.RefreshToken.TokenString
                }));
            }
            catch (Exception ex)
            {
                _loggerService.Error(ex);
                return(BadRequest());
            }
        }
Exemplo n.º 30
0
        public ActionResult Login([FromBody] LoginRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            // if (!_userService.IsValidUserCredentials(request.UserName, request.Password))
            // {
            //     return Unauthorized();
            // }

            var user = _userManager.FindByNameAsync(request.UserName).Result;

            if (!_userManager.CheckPasswordAsync(user, request.Password).Result)
            {
                return(Unauthorized());
            }

            // var role = _userService.GetUserRole(request.UserName);
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };

            var jwtResult = _jwtAuthManager.GenerateTokens(request.UserName, claims, DateTime.Now);

            _logger.LogInformation($"User [{request.UserName}] logged in the system.");
            return(Ok(new LoginResult
            {
                UserName = request.UserName,
                Role = "admin",
                AccessToken = jwtResult.AccessToken,
                RefreshToken = jwtResult.RefreshToken.TokenString
            }));
        }