Exemple #1
0
        public ActionResult Index()
        {
            ViewBag.IsHomePage = true;
            ViewBag.SearchInfo = cacheService.GetOrSetCache(
                "geonetworkRecordsCount",
                () =>
            {
                try
                {
                    using (var client = restApiService.GetClient())
                    {
                        return(restApiService.PostRequest <JObject>(
                                   client,
                                   "search/records/_search",
                                   new StringContent(
                                       ApplicationData.ReadGeonetworkConfigFile("SearchInfo.json"),
                                       Encoding.UTF8,
                                       "application/json")));
                    }
                }
                catch (Exception exc)
                {
                    Logger.Error(exc);
                    return(null);
                }
            });

            using (ContextManager.NewConnection())
            {
                ViewBag.Providers = providerService.Search(
                    new ProviderQueryModel {
                    StatusId = EnumHelper.ProviderStatuses[ProviderStatus.Valid]
                });
                ViewBag.BackgroundImages = adminService.GetHomeImages();
            }

            return(View());
        }
Exemple #2
0
        private User GetUser(string userName, string password)
        {
            if (userName.IsNullOrEmptyOrWhiteSpace() || password.IsNullOrEmptyOrWhiteSpace())
            {
                return(null);
            }

            // Check user in geonetwork
            object geonetworkUser = null;

            try
            {
                using (var client = restApiService.GetClient(new UserPrincipal {
                    UserName = userName, Password = password
                }))
                {
                    geonetworkUser = restApiService.GetRequest <object>(client, "me");
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
            }

            User user = null;

            if (userName.IsNotNullOrEmpty())
            {
                using (contextManager.NewConnection())
                {
                    user = accountService.GetByUserName(userName);
                }
            }

            if (geonetworkUser != null)
            {
                return(user);
            }

            if (user?.Password == null ||
                password?.IsNotNullOrEmpty() != true ||
                !PasswordTools.ValidatePassword(password, user.Password))
            {
                return(null);
            }

            return(user);
        }
        private void InitGeoNetworkData(IReadOnlyCollection <GroupTableModel> items)
        {
            if (items.IsNotNullOrEmpty())
            {
                using (var client = restApiService.GetClient())
                {
                    foreach (var item in items)
                    {
                        var groupDto = restApiService.GetRequest <GroupDTO>(client, $"groups/{item.GeoNetworkId}");
                        if (groupDto.Logo.IsNullOrEmptyOrWhiteSpace())
                        {
                            continue;
                        }

                        var request = (HttpWebRequest)WebRequest.Create($"{ConfigurationReader.GeoNetworkAddress}images/harvesting/{groupDto.Logo}");
                        item.Logo = Convert.ToBase64String(((HttpWebResponse)request.GetResponse()).GetResponseStream().ToByteArray());
                    }
                }
            }
        }
        public ActionResult Upsert(Guid?id)
        {
            var model = new UserUpsertViewModel();

            List <Nomenclature> profiles;

            using (ContextManager.NewConnection())
            {
                ViewBag.Roles = roleService.Search(new RoleQuery {
                    UserId = User.Id
                });
                profiles = nomenclatureService.Get("nrolegnw");

                if (id.HasValue)
                {
                    model       = Mapper.Map <UserUpsertViewModel>(userService.Get(id.Value));
                    model.Roles = roleService.GetUserRoles(id.Value);
                }
            }

            //// when register user there is no geonetwork account yet
            if (model.GeoNetworkId.HasValue)
            {
                using (var client = restApiService.GetClient())
                {
                    var geoNetworkUser = restApiService.GetRequest <UserDTO>(client, $"users/{model.GeoNetworkId}");

                    model.IsAdministrator = geoNetworkUser.Profile == Enum.GetName(
                        typeof(GeoNetWorkProfile),
                        GeoNetWorkProfile.Administrator);

                    model.GeoNetworkAddress = geoNetworkUser.Addresses?.FirstOrDefault();

                    if (!model.IsAdministrator)
                    {
                        var geoNetworkUserGroups = restApiService.GetRequest <List <UserGroup> >(
                            client,
                            $"users/{model.GeoNetworkId}/groups");
                        var firstGroupId = geoNetworkUserGroups.FirstOrDefault()?.Id;

                        model.Group = new GroupForUser
                        {
                            Id = firstGroupId?.GroupId
                        };

                        model.Profile = profiles?.Single(
                            item => item.Id.Equals(
                                EnumHelper.GetProfileIdByProfile(
                                    (GeoNetWorkProfile)Enum.Parse(
                                        typeof(GeoNetWorkProfile),
                                        firstGroupId?.Profile,
                                        true))));
                    }
                }
            }

            this.InitAdminBreadcrumb(
                Title,
                string.Format(
                    model.Id.HasValue
                        ? string.Format(Resource.Editing, model.UserName)
                        : string.Format(Resource.Creating, Resource.User.ToLower())),
                true);

            return(Request.IsAjaxRequest()
                ? PartialView(model) as ActionResult
                : View(model));
        }
Exemple #5
0
        public ActionResult Upsert(GroupUpsertModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (var client = restApiService.GetClient())
                    {
                        // read all cagegories from api to map selected ones. The api needs all properties, not only ids!!!
                        var all      = restApiService.GetRequest <List <Category> >(client, "tags");
                        var groupDto = Mapper.Map <GroupDTO>(model);
                        groupDto.DefaultCategory = model.DefaultCategory != null
                            ? all.Single(item => item.Id.Equals(model.DefaultCategory.Id))
                            : null;

                        groupDto.AllowedCategories = all.Where(
                            item => model.SelectedAllowedCategories.IsNotNullOrEmpty() &&
                            model.SelectedAllowedCategories.Contains(item.Id.Value));

                        var json = SerializeGroupDTOToJson(groupDto);
                        restApiService.PutRequest(
                            client,
                            model.GeoNetworkId.HasValue ? $"groups/{model.GeoNetworkId}" : "groups",
                            new StringContent(json, Encoding.UTF8, "application/json"));

                        var geoNetworkGroup = restApiService.GetRequest <List <GroupDTO> >(client, "groups")
                                              ?.Single(
                            item => item.Name == model.Names.GetValueForCurrentCulture());
                        model.GeoNetworkId = Convert.ToInt64(geoNetworkGroup.Id);

                        InitLabels(geoNetworkGroup, model);
                        json = SerializeGroupDTOToJson(geoNetworkGroup);

                        restApiService.PutRequest(
                            client,
                            $"groups/{model.GeoNetworkId}",
                            new StringContent(json, Encoding.UTF8, "application/json"));
                    }

                    var group = Mapper.Map <Group>(model);
                    using (var transaction = ContextManager.NewTransaction())
                    {
                        groupService.Upsert(group);
                        transaction.Commit();
                    }

                    this.ShowMessage(MessageType.Success, Resource.ChangesSuccessfullySaved);
                    return(RedirectToAction("Index", new { group.Id }));
                }
                catch (Exception e)
                {
                    Logger.Error(e);
                    ModelState.AddModelError(string.Empty, e is UserException userException ? userException.Message : Resource.InternalServerError);
                }
            }

            this.InitAdminBreadcrumb(
                Title,
                string.Format(
                    model.Id.HasValue
                        ? string.Format(Resource.Editing, model.Names.GetValueForCurrentCulture())
                        : string.Format(Resource.Creating, Resource.Organization.ToLower())),
                true);

            return(Request.IsAjaxRequest()
                ? PartialView(model) as ActionResult
                : View(model));
        }
Exemple #6
0
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            ModelState.Clear();

            // Validate captcha control
            if (!captchaService.Validate(Request["g-recaptcha-response"]))
            {
                ModelState.AddModelError(string.Empty, Resource.WrongCaptchaMessage);
            }

            User user = null;

            if (model.Token.IsNotNullOrEmpty())
            {
                user = GetUserByToken(model.Token);
            }
            else if (User?.Id != null)
            {
                using (ContextManager.NewConnection())
                {
                    user = accountService.GetByUserName(User.UserName);
                }

                // Validate old password - if is same as login user password
                if (model.OldPassword.IsNullOrEmpty() ||
                    !PasswordTools.ValidatePassword(model.OldPassword, user.Password))
                {
                    ModelState.AddModelError("OldPassword", Resource.PasswordsDoesNotMatch);
                }
            }

            if (user == null)
            {
                throw new WarningException(Resource.InvalidToken);
            }

            model.IsAdmin = user.IsAdmin;
            model.UserId  = user.Id.Value;

            if (!TryValidateModel(model) || !ModelState.IsValid)
            {
                return(View("ChangePassword", model));
            }

            using (var client = restApiService.GetClient(new UserPrincipal {
                UserName = ConfigurationReader.GeoNetworkAdminUser, Password = ConfigurationReader.GeoNetworkAdminPass
            }))
            {
                restApiService.PostRequest(
                    client,
                    $"users/{user.GeoNetworkId}/actions/forget-password?password={model.Password}&password2={model.ConfirmPassword}");
            }

            model.Password = PasswordTools.CreateHash(model.Password);

            var userPrincipal = Mapper.Map <IUser, UserPrincipal>(user);

            using (var transaction = ContextManager.NewTransaction(new RequestData(userPrincipal)))
            {
                userService.ChangePassword(Mapper.Map <ChangePasswordModel>(model));

                // If user is not active - activate it
                if (model.Token.IsNotNullOrEmpty() && user.Status.Id == EnumHelper.GetStatusIdByEnum(UserStatus.InActive))
                {
                    userService.ChangeStatus(
                        EnumHelper.GetStatusIdByEnum(UserStatus.Active),
                        user.Id.Value,
                        ConfigurationReader.AutomationUserId);
                }

                transaction.Commit();
            }

            return(RedirectToAction("Login"));
        }