Ejemplo n.º 1
0
        public IActionResult UpdateUserPassword(UserPasswordUpdateRequest request)
        {
            //User id corrente
            var userId = PlatformUtils.GetIdentityUserId(User);

            //modifica solo se admin o se sè stesso o è autorizzato
            if (request.UserId != userId)
            {
                return(Unauthorized());
            }

            //Recupero l'elemento dal business layer
            var entity = AuthorizationLayer.GetUserById(request.UserId);

            if (entity == null)
            {
                return(NotFound());
            }

            //Salvataggio
            var validations = AuthorizationLayer.UpdateUserPassword(entity, request.Password);

            if (validations.Count > 0)
            {
                return(BadRequest(validations));
            }

            //Confermo
            return(Ok(new BooleanResponse()
            {
                Value = true
            }));
        }
Ejemplo n.º 2
0
        public void ShouldUpdateUserPasswordBeOkHavingProvidedData()
        {
            //Recupero un user esistente
            var existing = Scenario.Shooters.FirstOrDefault();

            if (existing == null)
            {
                Assert.Inconclusive("User does not exists");
            }

            var oldPassword = existing.Password;

            //Composizione della request
            var request = new UserPasswordUpdateRequest
            {
                UserId   = existing.Id,
                Password = RandomizationUtils.GenerateRandomString(10)
            };

            //Invoke del metodo
            var response = Controller.UpdateUserPassword(request);

            var newPassword = Scenario.Shooters.FirstOrDefault(x => x.Id == existing.Id)?.Password;

            //Parsing della risposta e assert
            var parsed = ParseExpectedOk <BooleanResponse>(response);

            Assert.IsNotNull(newPassword);
            Assert.IsTrue(parsed != null &&
                          oldPassword != newPassword);
        }
Ejemplo n.º 3
0
        //public UserWithRole GetCurrentUser(int id)
        //{
        //    UserWithRole result = new UserWithRole();
        //    dataProvider.ExecuteCmd(
        //        "Users_GetCurrentUser",
        //        inputParamMapper: parameters =>
        //        {
        //            parameters.AddWithValue("@Id", id);
        //        },
        //        singleRecordMapper: (reader, resultsSetNumber) =>
        //        {
        //            result.Id = (int)reader["Id"];
        //            result.FirstName = (string)reader["FirstName"];
        //            result.LastName = (string)reader["LastName"];
        //            result.Email = (string)reader["Email"];
        //            result.UserTypeId = reader.GetSafeInt32Nullable("UserTypeId");
        //            result.UserTypeName = (string)reader["UserTypeName"];
        //            result.Role = reader.GetSafeInt32Nullable("Role");
        //            result.AvatarUrl = reader["AvatarUrl"] as string ?? default(string);
        //            result.DateCreated = (DateTime)reader["DateCreated"];
        //            result.DateModified = (DateTime)reader["DateModified"];
        //            result.DisplayName = reader.GetSafeString("DisplayName");
        //        });
        //    return result;
        //}

        //public string GetProfileById(int id, int viewersUserId)
        //{
        //    var jsonResult = new StringBuilder();
        //    dataProvider.ExecuteCmd(
        //        "UserProfile_GetById",
        //        inputParamMapper: parameters =>
        //        {
        //            parameters.AddWithValue("@Id", id);
        //            parameters.AddWithValue("@ViewersUserId", viewersUserId);
        //        },
        //        singleRecordMapper: (reader, resultSetId) =>
        //        {
        //            jsonResult.Append(reader.GetString(0));
        //        });
        //    return jsonResult.ToString();
        //}
        //public void UpdateProfile(UserProfileUpdateRequest model)
        //{
        //    var json = JsonConvert.SerializeObject(model);
        //    dataProvider.ExecuteNonQuery(
        //        "UserProfile_Update",
        //        inputParamMapper: (parameters) =>
        //        {
        //            parameters.AddWithValue("@Data", json);
        //        },
        //        returnParameters: null);
        //}

        //public bool GoogleLogin(GoogleLogInRequest model)
        //{
        //    bool userAuthenticated = false;
        //    int userId = 0;

        //    //TODO: Update with RecruitHub Client Id
        //    string googleClientId = "58772775873-oma31jtiqhph7os62h7i9a37makcilfr.apps.googleusercontent.com";
        //    string gapiRespObject;
        //    string gapiAuthUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=";
        //    HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(gapiAuthUrl + model.GoogleToken);
        //    webReq.Method = "GET";
        //    HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
        //    using (Stream stream = webResp.GetResponseStream())
        //    {
        //        StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
        //        gapiRespObject = reader.ReadToEnd();
        //    }

        //    var gapiRespString = (JObject)JsonConvert.DeserializeObject(gapiRespObject);
        //    string authEmail = gapiRespString["email"].Value<string>();
        //    string authAud = gapiRespString["aud"].Value<string>();
        //    string authFirstName = gapiRespString["given_name"].Value<string>();
        //    string authLastName = gapiRespString["family_name"].Value<string>();
        //    string authPassword = gapiRespString["sub"].Value<string>();

        //    if (authAud == googleClientId)
        //    {
        //        userAuthenticated = true;

        //        dataProvider.ExecuteCmd(
        //        "Users_GoogleLogin",
        //        inputParamMapper: (parameters) =>
        //        {
        //            parameters.AddWithValue("@Email", authEmail);
        //            parameters.AddWithValue("@FirstName", authFirstName);
        //            parameters.AddWithValue("@LastName", authLastName);
        //            parameters.AddWithValue("@UserTypeId", (object)DBNull.Value);
        //            parameters.AddWithValue("@Password", authPassword);
        //        },
        //        singleRecordMapper: (reader, resultsSetNumber) =>
        //        {
        //            userId = (int)reader["Id"];
        //        });

        //        UserAuthData userAuthData = new UserAuthData()
        //        {
        //            Id = userId
        //        };
        //        authenticationService.LogIn(userAuthData, true);
        //    }
        //    return userAuthenticated;
        //}

        //public Dictionary<int, UserAvatarResponse> GetUserAvatarsByIds(int[] ids)
        //{
        //    Dictionary<int, UserAvatarResponse> result = new Dictionary<int, UserAvatarResponse>();

        //    dataProvider.ExecuteCmd(
        //        "UserAvatar_GetByIds",
        //        inputParamMapper: p =>
        //        {
        //            p.AddWithValue("@Ids", JsonConvert.SerializeObject(ids));
        //        },
        //        singleRecordMapper: (reader, resultSetIndex) =>
        //        {
        //            UserAvatarResponse avatar = new UserAvatarResponse();
        //            avatar.Id = (int)reader["Id"];
        //            avatar.AvatarUrl = reader["AvatarUrl"] as string ?? default(string);
        //            avatar.UserTypeId = (int)reader["UserTypeId"];
        //            avatar.FullName = (string)reader["FullName"];
        //            result.Add(avatar.Id, avatar);
        //        });

        //    return result;
        //}

        //public void UpdateAvatarUrl(int id, UsersUpdateAvatarUrlRequest url)
        //{
        //    dataProvider.ExecuteNonQuery(
        //        "Users_UpdateAvatarUrl",
        //         inputParamMapper: parameters =>
        //         {
        //             parameters.AddWithValue("@Id", id);
        //             parameters.AddWithValue("@Url", url.Url);
        //         },
        //         returnParameters: null
        //         );
        //}

        public bool UpdatePassword(UserPasswordUpdateRequest model)
        {
            bool   passwordUpdateResult = false;
            string passwordHash         = null;

            dataProvider.ExecuteCmd(
                "Users_GetPasswordHash",
                inputParamMapper: parameters =>
            {
                parameters.AddWithValue("@Id", model.Id);
            },
                singleRecordMapper: (reader, resultsSetNumber) =>
            {
                passwordHash = (string)reader["Password"];
            });

            bool validPassword = BCrypt.Net.BCrypt.Verify(model.Password, passwordHash);

            if (validPassword)
            {
                string newPasswordHash = BCrypt.Net.BCrypt.HashPassword(model.NewPassword);

                dataProvider.ExecuteNonQuery(
                    "Users_PasswordUpdate",
                    inputParamMapper: parameters =>
                {
                    parameters.AddWithValue("@Id", model.Id);
                    parameters.AddWithValue("@NewPassword", newPasswordHash);
                },
                    returnParameters: null);

                passwordUpdateResult = true;
            }
            return(passwordUpdateResult);
        }
Ejemplo n.º 4
0
        public ActionResult <SuccessResponse> ResetPassword(UserPasswordUpdateRequest model)
        {
            int          iCode    = 200;
            BaseResponse response = null;

            try
            {
                int userId = _userService.ResetPassword(model.Token);

                if (userId > 0)
                {
                    _userService.UpdateUserPassword(userId, model.Password);
                    _userService.DeleteToken(model.Token);
                    response = new SuccessResponse();
                }
                else
                {
                    iCode    = 500;
                    response = new ErrorResponse("Failed to reset password.");
                }
            }
            catch (Exception ex)
            {
                iCode    = 500;
                response = new ErrorResponse($"Generic Error: {ex.Message}");
                base.Logger.LogError(ex.ToString());
            }

            return(StatusCode(iCode, response));
        }
Ejemplo n.º 5
0
        public async Task <UserResult> UpdatePasswordAsync(UserPasswordUpdateRequest model)
        {
            _validationStrategyContext.SetStrategy(new UserPasswordUpdateValidationStratergy());
            bool canUpdate = _validationStrategyContext.Validate(model);

            if (!canUpdate)
            {
                throw new UnauthorizedAccessException();
            }

            var errors = _validationStrategyContext.Errors;

            if (errors != null || errors.Any())
            {
                throw new ArgumentException(_validationStrategyContext.Errors.FirstOrDefault().Message);
            }

            var user = await _userRepository.FirstOrDefaultAsync(x => x.Id == model.UserId);

            if (user == null)
            {
                return(new UserResult());
            }
            user.PasswordHash = model.NewPassword;
            await _userRepository.UpdateAsync(user);

            return(new UserResult()
            {
                Id = user.Id
            });
        }
Ejemplo n.º 6
0
        public void CreatePassword(UserPasswordUpdateRequest model)
        {
            string newPasswordHash = BCrypt.Net.BCrypt.HashPassword(model.NewPassword);

            dataProvider.ExecuteNonQuery(
                "Users_PasswordUpdate",
                inputParamMapper: parameters =>
            {
                parameters.AddWithValue("@Id", model.Id);
                parameters.AddWithValue("@NewPassword", newPasswordHash);
            },
                returnParameters: null);
        }
Ejemplo n.º 7
0
        public void ShouldUpdateUserPasswordBeUnauthorizedHavingProvidedWrongId()
        {
            //Composizione della request
            var request = new UserPasswordUpdateRequest
            {
                UserId   = RandomizationUtils.GenerateRandomString(10),
                Password = RandomizationUtils.GenerateRandomString(10)
            };

            //Invoke del metodo
            var response = Controller.UpdateUserPassword(request);

            //Parsing della risposta e assert
            var parsed = ParseExpectedUnauthorized(response);

            //verifica contatori
            Assert.IsNull(parsed.Data);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> UpdatePassword([FromRoute] int id, [FromBody] UserPasswordUpdateRequest request)
        {
            UserFullInfoResponce result;

            try
            {
                result = await m_usersAPIServicee.UpdateUserPasswordAsync(id, request);
            }
            catch (NotFoundException)
            {
                return(NotFound());
            }
            catch (ForbidenPasswordUpdateException)
            {
                ModelState.AddModelError("", "Only an administrator or account owner can update password");
                return(StatusCode(StatusCodes.Status403Forbidden, new BadRequestType(ModelState)));
            }

            return(Ok(result));
        }
Ejemplo n.º 9
0
        public async Task <UserFullInfoResponce> UpdateUserPasswordAsync(int id, UserPasswordUpdateRequest request)
        {
            var updatedUser = await m_db.Users.Include(x => x.Profile).FirstOrDefaultAsync(x => x.Id == id);

            if (updatedUser is null)
            {
                throw new NotFoundException();
            }

            if (!m_authService.IsAuthUser(updatedUser) && !m_authService.AuthUserInRole(Roles.AdminRoleName))
            {
                throw new ForbidenPasswordUpdateException();
            }

            updatedUser.PasswordHash    = m_passwordService.SaltHash(request.NewPassword);
            updatedUser.Profile.Updated = DateTime.UtcNow;

            await m_db.SaveChangesAsync();

            return(m_mapper.Map <UserFullInfoResponce>(updatedUser));
        }
Ejemplo n.º 10
0
 public async Task <UserResult> UpdatePasswordAsync(UserPasswordUpdateRequest request)
 {
     return(await _authenticationRepository.UpdatePasswordAsync(request));
 }