Beispiel #1
0
        public async Task <RegisterResultDto> Register(UserCredentialsDto userCredentials)
        {
            if (await _userManager.FindByNameAsync(userCredentials.UserName) != null)
            {
                throw new UserAlreadyExistsException(userCredentials.UserName);
            }

            var newUser = new IdentityUser()
            {
                UserName = userCredentials.UserName
            };

            var result = await _userManager.CreateAsync(newUser, userCredentials.Password);

            if (!result.Succeeded)
            {
                var errors = result.Errors.Select(x => x.Description);

                return(new RegisterResultDto()
                {
                    Successful = false, Errors = errors
                });
            }

            return(new RegisterResultDto()
            {
                Successful = true
            });
        }
Beispiel #2
0
        public async Task <LoginResultDto> Login(UserCredentialsDto userCredentials, HttpContext context)
        {
            var result =
                await _signInManager.PasswordSignInAsync(
                    userCredentials.UserName, userCredentials.Password, false, false);

            if (!result.Succeeded)
            {
                return(new LoginResultDto {
                    Successful = false, Error = "Username and password are invalid."
                });
            }

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

            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSecurityKey"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expiry      = DateTime.Now.AddDays(Convert.ToInt32(_configuration["JwtExpiryInDays"]));

            var token = new JwtSecurityToken(
                _configuration["JwtIssuer"],
                _configuration["JwtAudience"],
                claims,
                expires: expiry,
                signingCredentials: credentials
                );

            return(new LoginResultDto {
                Successful = true, Token = new JwtSecurityTokenHandler().WriteToken(token)
            });
        }
Beispiel #3
0
        public async Task <IActionResult> LogIn([FromBody] UserCredentialsDto userCredentials)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            const byte hashLength = 128;
            string     trimmedEmail = userCredentials.UserMail?.Trim().ToLower(), trimmedPasswordHash = userCredentials.UserPasswordHash?.Trim().ToUpper();

            if ((trimmedEmail == null) || (trimmedPasswordHash == null) || (trimmedEmail.Length == 0) || (trimmedPasswordHash.Length != hashLength))
            {
                return(BadRequest("Illegal login data"));
            }

            UserCredentials authorizedCreds = await _context.UserCredentials
                                              .Where((creds) => creds.UserMail == trimmedEmail && creds.UserPasswordHash == trimmedPasswordHash)
                                              .SingleOrDefaultAsync();

            if (authorizedCreds != null)
            {
                User loginUser = await _context.Users.Where((user) => user.UserId == authorizedCreds.UserId).SingleAsync();

                loginUser.Role = await _context.Roles.Where((role) => role.RoleId == loginUser.RoleId).SingleAsync();

                loginUser.UserCredentials = authorizedCreds;
                await Authenticate(loginUser);

                return(Ok(new UserDto(loginUser, false)));
            }
            else
            {
                return(BadRequest("Illegal login data"));
            }
        }
Beispiel #4
0
        public IActionResult DeleteBlog(int userId, int blogId,
                                        [FromBody] UserCredentialsDto credentials)
        {
            if (!_weblogDataRepository.UserExists(userId))
            {
                return(NotFound());
            }

            var emailAddress = credentials.EmailAddress;
            var password     = credentials.Password;

            if (!_weblogDataRepository.Authorized(userId, emailAddress, password))
            {
                return(Unauthorized());
            }

            var blogFromRepo = _weblogDataRepository.GetBlog(blogId);

            if (blogFromRepo is null)
            {
                return(NotFound());
            }

            _weblogDataRepository.DeleteBlog(blogFromRepo);
            _weblogDataRepository.Save();

            return(NoContent());
        }
Beispiel #5
0
        public IActionResult Authenticate([FromBody] UserCredentialsDto credentials,
                                          [FromHeader(Name = nameof(HeaderNames.Accept))] string mediaType)
        {
            var user = _weblogDataRepository.Authenticate(
                credentials.EmailAddress, credentials.Password);

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

            var userToReturn = _mapper.Map <UserDto>(user);

            var includeLinks = MediaTypes.IncludeLinks(mediaType);

            if (!includeLinks)
            {
                return(Ok(userToReturn));
            }

            var links         = CreateLinksForUser(user.UserId);
            var userWithLinks = new UserDtoWithLinks(userToReturn, links);

            return(Ok(userWithLinks));
        }
Beispiel #6
0
 private Claim[] GetClaims(UserCredentialsDto credentials)
 {
     return(new Claim[]
     {
         new Claim(ID_CLAIM_TYPE, credentials.UserId.ToString()),
         new Claim(LOGIN_CLAIM_TYPE, credentials.Login)
     });
 }
Beispiel #7
0
    public async Task <UserTokenDto> LoginAsync(UserCredentialsDto user)
    {
        var httpRes = await _httpClient.PostAsJsonAsync <UserCredentialsDto>($"api/users/login", user);

        var res = await httpRes.Content.ReadFromJsonAsync <UserTokenDto>();

        return(res);
    }
Beispiel #8
0
        public IActionResult Login(UserCredentialsDto dto)
        {
            try
            {
                var captchaValidated = CaptchaHelper.ValidateCaptcha(dto.CaptchaKey, dto.UserCaptchaInput);
                if (captchaValidated == true)
                {
                    var setting = UnitOfWork.SettingRepository.GetAll().FirstOrDefault();
                    if (setting == null)
                    {
                        return(StatusCode(500, new { Error = "تنظیمات سیستم تعریف نشده است" }));
                    }

                    var user = UnitOfWork.UserRepository.Find(u => u.UserName == dto.UserName).FirstOrDefault();
                    if (user == null)
                    {
                        return(Unauthorized(new { Error = "نام کاربری یا کلمه عبور اشتباه است" }));
                    }
                    if (UserManager.IsUserLocked(user))
                    {
                        return(Unauthorized(new { Error = "حساب کاربری شما به علت وارد کردن رمز عبور اشتباه بیش از حد مجاز برای دقایقی مسدود شده است." }));
                    }
                    var result = UserManager.VerifyPassword(dto.UserName, dto.Password);
                    if (result == "Failed")
                    {
                        UserManager.IncreaseUserFailedPasswordCount(user);
                        if (UserManager.HasUserPassedMaxFailedPasswordCount(user, setting))
                        {
                            UserManager.LockUser(user, setting);
                            UnitOfWork.Complete();
                            return(Unauthorized(new { Error = "حساب کاربری شما به علت وارد کردن رمز عبور اشتباه بیش از حد مجاز برای دقایقی مسدود شده است." }));
                        }
                        UnitOfWork.Complete();
                        return(Unauthorized(new { Error = "نام کاربری یا کلمه عبور اشتباه است" }));
                    }
                    UserManager.UnlockUser(user);

                    var nextStep = UserManager.GetNextAuthenticationStep(user, SecurityLevel, dto.RequestedSecurityLevel, AuthenticationSteps.Login);
                    if (nextStep == AuthenticationSteps.Done.ToString())
                    {
                        return(new ObjectResult(JwtHandler.Create(user.UserName, dto.RequestedSecurityLevel, dto.ApplicationId, dto.PageId)));
                    }
                    else
                    {
                        return(Ok(new { NextRoute = nextStep }));
                    }
                }
                else
                {
                    return(StatusCode(400, new { Error = "کلید تصویر امنیتی معتبر نمی باشد" }));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex));
            }
        }
        public IActionResult AddUserCredentials([FromBody] UserCredentialsDto userCredentials)
        {
            Boolean result = _authService.AddUserCreadentials(userCredentials.Username, userCredentials.Password);

            if (result)
            {
                return(Ok());
            }
            return(BadRequest());
        }
Beispiel #10
0
        public void SignIn([FromBody] UserCredentialsDto userSignInDto)
        {
            if (userSignInDto == null)
            {
                throw new ArgumentNullException(nameof(userSignInDto));
            }

            var token = _userService.SignIn(userSignInDto.Email, userSignInDto.Password);

            SetAccessToken(token);
        }
Beispiel #11
0
        public async Task <IActionResult> Login([FromBody] UserCredentialsDto userCredentials)
        {
            var result = await _userService.Login(userCredentials, HttpContext);

            if (result.Successful)
            {
                return(Ok(result));
            }

            return(BadRequest(result));
        }
Beispiel #12
0
        public async Task <IActionResult> Post(UserCredentialsDto userCredentialsDto)
        {
            var token = await _authenticateService.GenerateToken(userCredentialsDto.Username, userCredentialsDto.Password);

            if (token == null)
            {
                return(Ok(new { token, errorMessage = "Username and/or password are incorrect" }));
            }

            return(Ok(new { token = token }));
        }
 public IActionResult Login([FromBody] UserCredentialsDto credentials)
 {
     try
     {
         string token = _authService.Login(credentials.Username, credentials.Password).Result;
         return(Ok(token));
     } catch (Exception e)
     {
         Console.WriteLine("Exception: " + e.GetBaseException());
         return(Unauthorized());
     }
 }
        public async Task <User> Login(UserCredentialsDto creds)
        {
            var user = await _userManager.FindByNameAsync(creds.Username);

            var result = await _signInManager.CheckPasswordSignInAsync(user, creds.Password, false);

            if (result.Succeeded)
            {
                return(user);
            }
            return(null);
        }
Beispiel #15
0
        public async Task <IActionResult> Login([FromBody] UserCredentialsDto user)
        {
            var loginedUser = await _repo.Login(user.Name, user.Password);

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

            var token = GenerateToken(loginedUser.Id, loginedUser.UserName);

            return(Ok(new { token }));
        }
Beispiel #16
0
        public async Task <RegisterResultDto> Register(UserCredentialsDto userCredentials)
        {
            var resp = await _httpClient.PostAsync("api/users/register", GetStringContent(userCredentials));

            if (resp.IsSuccessStatusCode)
            {
                var result = await resp.Content.ReadAsAsync <RegisterResultDto>();

                return(result);
            }

            return(null);
        }
Beispiel #17
0
        public async Task <IActionResult> SignUp([FromBody] UserCredentialsDto userCredentials)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            const byte hashLength = 128;
            string     trimmedEmail = userCredentials.UserMail?.Trim().ToLower(), trimmedPasswordHash = userCredentials.UserPasswordHash?.Trim().ToUpper();

            if ((trimmedEmail == null) || (trimmedPasswordHash == null) || (trimmedEmail.Length == 0) || (trimmedPasswordHash.Length != hashLength))
            {
                return(BadRequest("Illegal register data"));
            }

            using (var transaction = _context.Database.BeginTransaction())
            {
                /*
                 *  Exception is throwed if using just Any(Async):
                 *      System.InvalidOperationException: "No coercion operator is defined between types 'System.Int16' and 'System.Boolean'."
                 *  Seems to be Oracle connector problem
                 */
                if (await _context.UserCredentials.ToAsyncEnumerable().Any((creds) => creds.UserMail == trimmedEmail))
                {
                    return(BadRequest("Email already exists"));
                }

                Role newUserRole = await _context.Roles.Where((role) => role.RoleAlias == "user").FirstOrDefaultAsync();

                if (newUserRole == null)
                {
                    throw new Exception("Error creating user: no needed role");
                }

                User newUser = (await _context.Users.AddAsync(new User {
                    RoleId = newUserRole.RoleId
                })).Entity;
                newUser.Role            = newUserRole;
                newUser.UserCredentials = (await _context.UserCredentials.AddAsync(new UserCredentials {
                    UserId = newUser.UserId, UserMail = trimmedEmail, UserPasswordHash = trimmedPasswordHash
                })).Entity;

                await _context.SaveChangesAsync();

                transaction.Commit();

                await Authenticate(newUser);

                return(Created(nameof(SignUp), new UserDto(newUser, false)));
            }
        }
        public async Task <AuthenticatedUserDto> LoginAsync(UserCredentialsDto credentialsDto)
        {
            var credentials = Credentials.Create(credentialsDto.Mail, credentialsDto.Password);
            var user        = await this.dbAccess.LoginAsync(credentials);

            var token = RetrieveJwtToken(user);

            return(new AuthenticatedUserDto()
            {
                Id = user.Id,
                Role = user.Role.ToString(),
                Token = token
            });
        }
Beispiel #19
0
 public async Task <ActionResult <AuthenticatedUserDto> > LoginUserAsync([FromForm] UserCredentialsDto userCredentials)
 {
     try
     {
         return(await this.userService.LoginAsync(userCredentials));
     }
     catch (UserException exc) when(exc.HasCodeIn((int)UserException.UserExceptionCode.WrongMail, (int)UserException.UserExceptionCode.WrongPassword))
     {
         return(BadRequest(exc));
     }
     catch (UserException exc) when(exc.Code == (int)UserException.UserExceptionCode.UserNotConfirmed)
     {
         return(Conflict(exc));
     }
 }
        public UserDto CredentialsIsValid(UserCredentialsDto credentialsDto)
        {
            User user = _context.Users.SingleOrDefault(x => x.Name.Equals(credentialsDto.UserName, StringComparison.CurrentCultureIgnoreCase));

            if (user != null && PasswordCompare(user, credentialsDto))
            {
                return(new UserDto
                {
                    Id = user.Id,
                    UserName = user.Name
                });
            }

            return(null);
        }
Beispiel #21
0
        public ActionResult Login([FromBody] UserCredentialsDto value)
        {
            try
            {
                if (repo.GetUser(value.Username, value.Password) != default(User))
                {
                    return(Ok());
                }

                return(Unauthorized());
            }catch (Exception ex)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Beispiel #22
0
        public async Task <UserDto> SignInUser(UserCredentialsDto credentials)
        {
            var user = await _userRepository
                       .GetWithThrow(u => u.Email == credentials.Email);

            var encryptedPassword = _mapper.Map <User, Password>(user);

            _authService.VerifyPasswordHash(credentials.Password, encryptedPassword);

            var mappedUser = _mapper.Map <User, UserDto>(user);

            //mappedUser.Token = _authService.GenerateToken(user.Id);

            return(mappedUser);
        }
        public async Task<IActionResult> Post([FromBody]UserCredentialsDto credentials)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var response = await _authorization.GetAuthorizedPlayerAsync(credentials);

            if (response == null)
            {
                return BadRequest("There is no such user or credentials are invalid");
            }

            return Ok(response);
        }
Beispiel #24
0
        public void Authenticate(CurrentAuth auth, UserCredentialsDto credentials)
        {
            var user = Repository.FindByEmail(credentials.Email.ToLower());

            if (user == null || user.Password != credentials.Password)
            {
                throw new ValidationFieldException(nameof(credentials.Password), "Nome ou senha incorretos!");
            }

            if (!user.Active)
            {
                throw new ValidationFieldException(nameof(credentials.Email), "Sua conta está desativada!");
            }

            _userAuthProvider.Load(user, auth);
        }
Beispiel #25
0
 public async Task <IActionResult> Register([FromBody] UserCredentialsDto userCredentials)
 {
     try
     {
         return(Ok(await _userService.Register(userCredentials)));
     }
     catch (UserAlreadyExistsException e)
     {
         return(Ok(new RegisterResultDto()
         {
             Successful = false, Errors = new List <string>()
             {
                 e.Message
             }
         }));
     }
 }
Beispiel #26
0
        public async Task <LoginResultDto> Login(UserCredentialsDto userCredentials)
        {
            var resp = await _httpClient.PostAsync("api/users/login", GetStringContent(userCredentials));

            var result = await resp.Content.ReadAsAsync <LoginResultDto>();

            if (!result.Successful)
            {
                return(result);
            }

            await _localStorage.SetItemAsync("authToken", result.Token);

            ((CustomAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(userCredentials.UserName);

            return(result);
        }
        public async Task <IActionResult> Register([FromBody] UserCredentialsDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!PasswordHelper.CheckPassword(model.Password))
            {
                return(BadRequest("new password is incorrect"));
            }

            var user = new User
            {
                UserName            = model.Email,
                Email               = model.Email,
                FirstName           = model.FirstName,
                LastName            = model.LastName,
                IsActive            = model.IsActive,
                IsPasswordForChange = true,
            };

            var oldUser = await _userManager.FindByEmailAsync(model.Email);

            if (oldUser != null)
            {
                return(new StatusCodeResult(StatusCodes.Status409Conflict));
            }

            var result = await _userManager.CreateAsync(user, model.Password);

            await _userManager.AddToRoleAsync(user, model.RoleName);



            if (result.Succeeded)
            {
                return(Ok(user));
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("error", error.Description);
            }
            return(BadRequest(result.Errors));
        }
Beispiel #28
0
        public IActionResult Login([FromForm] UserCredentialsDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(View(dto));
            }

            try {
                _service.Authenticate(_auth, dto);

                return(RedirectToAction("Index", "Home"));
            }
            catch (ValidationFieldException e) {
                ModelState.AddModelError(e.Field, e.Error);
            }

            return(View(dto));
        }
Beispiel #29
0
        public async Task <AuthDto> Login(string email, string paswword)
        {
            var user = new UserCredentialsDto
            {
                email    = email,
                password = paswword
            };

            var authDto = await _restClient.PostAsync <AuthDto>(LoginPath, user);

            if (authDto.success)
            {
                ServiceBus.UserService.GetAllUsers();
                ServiceBus.UserService.ReviewerLoginAsync();
            }

            return(authDto);
        }
Beispiel #30
0
        public ActionResult <bool> Login(UserCredentialsDto credDto)
        {
            if (!ModelState.IsValid || credDto == null)
            {
                Log.Information("User login - Invalid model");
                return(new BadRequestObjectResult(new { Message = "Login failed", IsLogin = false }));
            }

            var dbUser = _repository.GetUserByUserId(credDto.UserId);

            if (dbUser == null)
            {
                Log.Information(string.Format("User login - Invalid username: {0}", credDto.UserId));
                return(Unauthorized(new { Message = "Invalid username or password", IsLogin = false }));
            }

            var hashedPasword = _userHelper.GetHashedPassword(credDto.Password);

            if (hashedPasword != dbUser.Password)
            {
                Log.Information(string.Format("User login - Invalid password: {0}", dbUser.UserId));
                return(Unauthorized(new { Message = "Invalid username or password", IsLogin = false }));
            }

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Email, dbUser.Email),
                new Claim(ClaimTypes.Name, dbUser.UserId)
            };

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                    new ClaimsPrincipal(claimsIdentity));

            // TODO: remove/change when we have decided our url
            // Source: https://dotnetstories.com/blog/How-to-enable-CORS-for-POST-requests-on-a-single-endpoint-in-ASPNET-Core-en-7186478980?lang=en
            Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:3001");
            Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

            return(Ok(new { Message = "Successful login", IsLogin = true }));
        }