Example #1
0
        public async Task <Tag> Create(string name)
        {
            if (!ValidateTagName(name))
            {
                return(null);
            }

            var normalizedName = NormalizeTagName(name, _tagNormalizationDictionary);

            if (_tagRepo.Any(t => t.NormalizedName == normalizedName))
            {
                return(Get(normalizedName));
            }

            var newTag = new TagEntity
            {
                DisplayName    = name,
                NormalizedName = normalizedName
            };

            var tag = await _tagRepo.AddAsync(newTag);

            await _audit.AddEntry(BlogEventType.Content, BlogEventId.TagCreated,
                                  $"Tag '{tag.NormalizedName}' created.");

            return(new()
            {
                DisplayName = newTag.DisplayName,
                NormalizedName = newTag.NormalizedName
            });
        }
Example #2
0
        public async Task <Guid> CreateAsync(string username, string clearPassword)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException(nameof(username), "value must not be empty.");
            }

            if (string.IsNullOrWhiteSpace(clearPassword))
            {
                throw new ArgumentNullException(nameof(clearPassword), "value must not be empty.");
            }

            var uid     = Guid.NewGuid();
            var account = new LocalAccountEntity
            {
                Id            = uid,
                CreateTimeUtc = DateTime.UtcNow,
                Username      = username.ToLower().Trim(),
                PasswordHash  = Helper.HashPassword(clearPassword.Trim())
            };

            await _accountRepo.AddAsync(account);

            await _audit.AddEntry(BlogEventType.Settings, BlogEventId.SettingsAccountCreated, $"Account '{account.Id}' created.");

            return(uid);
        }
Example #3
0
        public async Task <IActionResult> OnPostAsync()
        {
            try
            {
                if (!_captcha.Validate(CaptchaCode, HttpContext.Session))
                {
                    ModelState.AddModelError(nameof(CaptchaCode), "Wrong Captcha Code");
                }

                if (ModelState.IsValid)
                {
                    var uid = await _localAccountService.ValidateAsync(Username, Password);

                    if (uid != Guid.Empty)
                    {
                        var claims = new List <Claim>
                        {
                            new (ClaimTypes.Name, Username),
                            new (ClaimTypes.Role, "Administrator"),
                            new ("uid", uid.ToString())
                        };
                        var ci = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                        var p  = new ClaimsPrincipal(ci);

                        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, p);

                        await _localAccountService.LogSuccessLoginAsync(uid,
                                                                        HttpContext.Connection.RemoteIpAddress?.ToString());

                        var successMessage = $@"Authentication success for local account ""{Username}""";

                        _logger.LogInformation(successMessage);
                        await _blogAudit.AddEntry(BlogEventType.Authentication, BlogEventId.LoginSuccessLocal, successMessage);

                        return(RedirectToPage("/Admin/Post"));
                    }
                    ModelState.AddModelError(string.Empty, "Invalid Login Attempt.");
                    return(Page());
                }

                var failMessage = $@"Authentication failed for local account ""{Username}""";

                _logger.LogWarning(failMessage);
                await _blogAudit.AddEntry(BlogEventType.Authentication, BlogEventId.LoginFailedLocal, failMessage);

                Response.StatusCode = StatusCodes.Status400BadRequest;
                ModelState.AddModelError(string.Empty, "Bad Request.");
                return(Page());
            }
            catch (Exception e)
            {
                _logger.LogWarning($@"Authentication failed for local account ""{Username}""");

                ModelState.AddModelError(string.Empty, e.Message);
                return(Page());
            }
        }
Example #4
0
        public async Task <IActionResult> General([FromForm] MagicWrapper <GeneralSettingsViewModel> wrapperModel, [FromServices] ITimeZoneResolver timeZoneResolver)
        {
            var model = wrapperModel.ViewModel;

            var settings = _blogConfig.GeneralSettings;

            settings.MetaKeyword                = model.MetaKeyword;
            settings.MetaDescription            = model.MetaDescription;
            settings.CanonicalPrefix            = model.CanonicalPrefix;
            settings.SiteTitle                  = model.SiteTitle;
            settings.Copyright                  = model.Copyright;
            settings.LogoText                   = model.LogoText;
            settings.SideBarCustomizedHtmlPitch = model.SideBarCustomizedHtmlPitch;
            settings.SideBarOption              = Enum.Parse <SideBarOption>(model.SideBarOption);
            settings.FooterCustomizedHtmlPitch  = model.FooterCustomizedHtmlPitch;
            settings.TimeZoneUtcOffset          = timeZoneResolver.GetTimeSpanByZoneId(model.SelectedTimeZoneId).ToString();
            settings.TimeZoneId                 = model.SelectedTimeZoneId;
            settings.ThemeId            = model.SelectedThemeId;
            settings.OwnerName          = model.OwnerName;
            settings.OwnerEmail         = model.OwnerEmail;
            settings.Description        = model.OwnerDescription;
            settings.ShortDescription   = model.OwnerShortDescription;
            settings.AutoDarkLightTheme = model.AutoDarkLightTheme;

            await _blogConfig.SaveAsync(_blogConfig.GeneralSettings);

            AppDomain.CurrentDomain.SetData("CurrentThemeColor", null);

            await _blogAudit.AddEntry(BlogEventType.Settings, BlogEventId.SettingsSavedGeneral, "General Settings updated.");

            return(NoContent());
        }
Example #5
0
        public async Task AddAsync(string title, string linkUrl)
        {
            if (!Uri.IsWellFormedUriString(linkUrl, UriKind.Absolute))
            {
                throw new InvalidOperationException($"{nameof(linkUrl)} is not a valid url.");
            }

            var link = new FriendLinkEntity
            {
                Id      = Guid.NewGuid(),
                LinkUrl = Helper.SterilizeLink(linkUrl),
                Title   = title
            };

            await _friendlinkRepo.AddAsync(link);

            await _audit.AddEntry(BlogEventType.Content, BlogEventId.FriendLinkCreated, "FriendLink created.");
        }
Example #6
0
        public async Task <IActionResult> Delete([NotEmpty] Guid pingbackId, [FromServices] IBlogAudit blogAudit)
        {
            await _pingbackService.DeletePingback(pingbackId);

            await blogAudit.AddEntry(BlogEventType.Content, BlogEventId.PingbackDeleted,
                                     $"Pingback '{pingbackId}' deleted.");

            return(NoContent());
        }
Example #7
0
        public async Task ToggleApprovalAsync(Guid[] commentIds)
        {
            if (commentIds is null || !commentIds.Any())
            {
                throw new ArgumentNullException(nameof(commentIds));
            }

            var spec     = new CommentSpec(commentIds);
            var comments = await _commentRepo.GetAsync(spec);

            foreach (var cmt in comments)
            {
                cmt.IsApproved = !cmt.IsApproved;
                await _commentRepo.UpdateAsync(cmt);

                string logMessage = $"Updated comment approval status to '{cmt.IsApproved}' for comment id: '{cmt.Id}'";
                await _audit.AddEntry(
                    BlogEventType.Content, cmt.IsApproved?BlogEventId.CommentApproval : BlogEventId.CommentDisapproval, logMessage);
            }
        }
Example #8
0
        public async Task <Guid> CreateAsync(UpdatePageRequest request)
        {
            var uid  = Guid.NewGuid();
            var page = new PageEntity
            {
                Id              = uid,
                Title           = request.Title.Trim(),
                Slug            = request.Slug.ToLower().Trim(),
                MetaDescription = request.MetaDescription,
                CreateTimeUtc   = DateTime.UtcNow,
                HtmlContent     = request.HtmlContent,
                CssContent      = request.CssContent,
                HideSidebar     = request.HideSidebar,
                IsPublished     = request.IsPublished
            };

            await _pageRepo.AddAsync(page);

            await _audit.AddEntry(BlogEventType.Content, BlogEventId.PageCreated, $"Page '{page.Id}' created.");

            return(uid);
        }
Example #9
0
        public async Task CreateAsync(string displayName, string routeName, string note = null)
        {
            var exists = _catRepo.Any(c => c.RouteName == routeName);

            if (exists)
            {
                return;
            }

            var category = new CategoryEntity
            {
                Id          = Guid.NewGuid(),
                RouteName   = routeName.Trim(),
                Note        = note?.Trim(),
                DisplayName = displayName.Trim()
            };

            await _catRepo.AddAsync(category);

            _cache.Remove(CacheDivision.General, "allcats");

            await _audit.AddEntry(BlogEventType.Content, BlogEventId.CategoryCreated, $"Category '{category.RouteName}' created");
        }