public ServiceModels.ServiceResponse Open(int id)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var recordQuery = from n in DbContext.Notifications
                              where n.UserId == UserContext.ApplicationUser.Id
                              where n.Id == id
                              select n;

            var record = recordQuery.FirstOrDefault();

            if (record is null)
            {
                serviceResponse.RedirectPath = UrlHelper.Action(nameof(Notifications.Index), nameof(Notifications));
                return(serviceResponse);
            }

            if (record.Unread)
            {
                record.Unread = false;
                DbContext.Update(record);
                DbContext.SaveChanges();
            }

            serviceResponse.RedirectPath = UrlHelper.Action(nameof(Topics.Display), nameof(Topics), new { id = record.MessageId });
            return(serviceResponse);
        }
Beispiel #2
0
        public async Task <IActionResult> RedirectFromService(Controller controller, ServiceModels.ServiceResponse serviceResponse = null, Func <Task <IActionResult> > failAsync = null, Func <IActionResult> failSync = null)
        {
            if (!(serviceResponse is null))
            {
                if (!string.IsNullOrEmpty(serviceResponse.Message))
                {
                    controller.TempData[Constants.InternalKeys.StatusMessage] = serviceResponse.Message;
                }

                foreach (var kvp in serviceResponse.Errors)
                {
                    controller.ModelState.AddModelError(kvp.Key, kvp.Value);
                }

                if (serviceResponse.Success)
                {
                    var redirectPath = serviceResponse.RedirectPath;

                    if (string.IsNullOrEmpty(redirectPath))
                    {
                        redirectPath = GetReferrer(controller);
                    }

                    return(controller.Redirect(redirectPath));
                }
            }

            if (!(failAsync is null))
            {
                return(await failAsync());
            }
		public async Task<ServiceModels.ServiceResponse> EditMessage(InputModels.MessageInput input) {
			var serviceResponse = new ServiceModels.ServiceResponse();

			if (input.Id == 0) {
				throw new HttpBadRequestError();
			}

			var record = DbContext.Messages.FirstOrDefault(m => m.Id == input.Id);

			if (record is null) {
				serviceResponse.Error(nameof(input.Id), $"No record found with the ID '{input.Id}'.");
			}

			var processedMessage = await ProcessMessageInput(serviceResponse, input.Body);

			if (serviceResponse.Success) {
				await UpdateMessageRecord(processedMessage, record);
				serviceResponse.RedirectPath = UrlHelper.DisplayMessage(record.Id);

				await ForumHub.Clients.All.SendAsync("updated-message", new HubModels.Message {
					TopicId = record.ParentId,
					MessageId = record.Id
				});
			}

			return serviceResponse;
		}
Beispiel #4
0
        public async Task <ServiceModels.ServiceResponse> ConfirmEmail(InputModels.ConfirmEmailInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var account = await UserManager.FindByIdAsync(input.UserId);

            if (account is null)
            {
                serviceResponse.Error($"Unable to load account '{input.UserId}'.");
            }

            if (serviceResponse.Success)
            {
                var identityResult = await UserManager.ConfirmEmailAsync(account, input.Code);

                if (!identityResult.Succeeded)
                {
                    foreach (var error in identityResult.Errors)
                    {
                        Log.LogError($"Error confirming '{account.Email}'. Message: {error.Description}");
                        serviceResponse.Error(error.Description);
                    }
                }
                else
                {
                    Log.LogInformation($"User confirmed email '{account.Id}'.");
                }
            }

            await SignOut();

            return(serviceResponse);
        }
		public async Task<ServiceModels.ServiceResponse> CreateTopic(InputModels.MessageInput input) {
			var serviceResponse = new ServiceModels.ServiceResponse();

			var processedMessage = await ProcessMessageInput(serviceResponse, input.Body);

			if (!serviceResponse.Success) {
				return serviceResponse;
			}

			var record = CreateMessageRecord(processedMessage, null);

			var existingMessageBoards = DbContext.MessageBoards.Where(item => item.MessageId == record.Id).ToList();

			foreach (var item in existingMessageBoards) {
				DbContext.Remove(item);
			}

			foreach (var selectedBoard in input.SelectedBoards) {
				var board = (await BoardRepository.Records()).FirstOrDefault(item => item.Id == selectedBoard);

				if (board != null) {
					DbContext.MessageBoards.Add(new DataModels.MessageBoard {
						MessageId = record.Id,
						BoardId = board.Id,
						TimeAdded = DateTime.Now,
						UserId = UserContext.ApplicationUser.Id
					});
				}
			}

			DbContext.SaveChanges();

			serviceResponse.RedirectPath = UrlHelper.DisplayMessage(record.Id);
			return serviceResponse;
		}
Beispiel #6
0
        public async Task <ServiceModels.ServiceResponse> ResetPassword(InputModels.ResetPasswordInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var account = await UserManager.FindByEmailAsync(input.Email);

            if (account != null)
            {
                var identityResult = await UserManager.ResetPasswordAsync(account, input.Code, input.Password);

                if (!identityResult.Succeeded)
                {
                    foreach (var error in identityResult.Errors)
                    {
                        Log.LogError($"Error resetting password for '{account.Email}'. Message: {error.Description}");
                    }
                }
                else
                {
                    Log.LogInformation($"Password was reset for '{account.Email}'.");
                }
            }

            serviceResponse.RedirectPath = nameof(Account.ResetPasswordConfirmation);
            return(serviceResponse);
        }
Beispiel #7
0
        public ServiceModels.ServiceResponse Merge(int sourceId, int targetId)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var sourceRecord = DbContext.Messages.FirstOrDefault(item => item.Id == sourceId);

            if (sourceRecord is null)
            {
                serviceResponse.Error("Source record not found");
            }

            var targetRecord = DbContext.Messages.FirstOrDefault(item => item.Id == targetId);

            if (targetRecord is null)
            {
                serviceResponse.Error("Target record not found");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            if (sourceRecord.TimePosted > targetRecord.TimePosted)
            {
                Merge(sourceRecord, targetRecord);
            }
            else
            {
                Merge(targetRecord, sourceRecord);
            }

            return(serviceResponse);
        }
Beispiel #8
0
        public async Task <ServiceModels.ServiceResponse> MoveCategoryUp(int id)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var targetCategory = (await Categories()).FirstOrDefault(b => b.Id == id);

            if (targetCategory is null)
            {
                serviceResponse.Error("No category found with that ID.");
                return(serviceResponse);
            }

            if (targetCategory.DisplayOrder > 1)
            {
                var displacedCategory = (await Categories()).First(b => b.DisplayOrder == targetCategory.DisplayOrder - 1);

                displacedCategory.DisplayOrder++;
                DbContext.Update(displacedCategory);

                targetCategory.DisplayOrder--;
                DbContext.Update(targetCategory);

                DbContext.SaveChanges();
            }

            return(serviceResponse);
        }
Beispiel #9
0
        public async Task ProcessMessagesContinue(InputModels.Continue input, bool force = false)
        {
            input.ThrowIfNull(nameof(input));

            var messageQuery = from message in DbContext.Messages
                               where force || !message.Processed
                               orderby message.Id descending
                               select message;

            var take = SettingsRepository.MessagesPerPage(true);
            var skip = take * input.CurrentStep;

            var messages = messageQuery.Skip(skip).Take(take).ToList();

            foreach (var message in messages)
            {
                var serviceResponse = new ServiceModels.ServiceResponse();

                var processedMessage = await ProcessMessageInput(serviceResponse, message.OriginalBody);

                if (serviceResponse.Success)
                {
                    message.OriginalBody = processedMessage.OriginalBody;
                    message.DisplayBody  = processedMessage.DisplayBody;
                    message.ShortPreview = processedMessage.ShortPreview;
                    message.LongPreview  = processedMessage.LongPreview;
                    message.Cards        = processedMessage.Cards;
                    message.Processed    = true;

                    DbContext.Update(message);
                }
            }

            DbContext.SaveChanges();
        }
Beispiel #10
0
        public async Task <ServiceModels.ServiceResponse> CreateReply(InputModels.MessageInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            if (input.Id == 0)
            {
                throw new HttpBadRequestError();
            }

            var replyRecord = DbContext.Messages.FirstOrDefault(m => m.Id == input.Id);

            if (replyRecord is null)
            {
                serviceResponse.Error($"A record does not exist with ID '{input.Id}'");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            var processedMessage = await ProcessMessageInput(serviceResponse, input.Body);

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            var record = CreateMessageRecord(processedMessage, replyRecord);

            serviceResponse.RedirectPath = UrlHelper.DirectMessage(record.Id);
            return(serviceResponse);
        }
Beispiel #11
0
        public async Task <ServiceModels.ServiceResponse> EditMessage(InputModels.MessageInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            if (input.Id == 0)
            {
                throw new HttpBadRequestError();
            }

            var record = DbContext.Messages.FirstOrDefault(m => m.Id == input.Id);

            if (record is null)
            {
                serviceResponse.Error(nameof(input.Id), $"No record found with the ID '{input.Id}'.");
            }

            var processedMessage = await ProcessMessageInput(serviceResponse, input.Body);

            if (serviceResponse.Success)
            {
                serviceResponse.RedirectPath = UrlHelper.DirectMessage(record.Id);
                UpdateMessageRecord(processedMessage, record);
            }

            return(serviceResponse);
        }
Beispiel #12
0
        public async Task <InputModels.ProcessedMessageInput> ProcessMessageInput(ServiceModels.ServiceResponse serviceResponse, string messageBody)
        {
            InputModels.ProcessedMessageInput processedMessage = null;

            try {
                processedMessage = PreProcessMessageInput(messageBody);
                PreProcessSmileys(processedMessage);
                ParseBBC(processedMessage);
                ProcessSmileys(processedMessage);
                await ProcessMessageBodyUrls(processedMessage);

                FindMentionedUsers(processedMessage);
                PostProcessMessageInput(processedMessage);
            }
            catch (ArgumentException e) {
                serviceResponse.Error(nameof(InputModels.MessageInput.Body), $"An error occurred while processing the message. {e.Message}");
            }

            if (processedMessage is null)
            {
                serviceResponse.Error(nameof(InputModels.MessageInput.Body), $"An error occurred while processing the message.");
                return(processedMessage);
            }

            return(processedMessage);
        }
Beispiel #13
0
		public async Task<ServiceModels.ServiceResponse> DeleteMessage(int messageId) {
			var serviceResponse = new ServiceModels.ServiceResponse();

			var record = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == messageId);

			if (record is null) {
				throw new HttpNotFoundError();
			}

			var parentId = record.ParentId;

			if (parentId != 0) {
				serviceResponse.RedirectPath = $"{UrlHelper.Action(nameof(Topics.Latest), nameof(Topics), new { id = parentId })}#message{parentId}";

				var directRepliesQuery = from message in DbContext.Messages
										 where message.ReplyId == messageId
										 select message;

				foreach (var reply in directRepliesQuery) {
					reply.OriginalBody =
						$"[quote]{record.OriginalBody}\n" +
						$"Message deleted by {UserContext.ApplicationUser.DisplayName} on {DateTime.Now.ToString("MMMM dd, yyyy")}[/quote]" +
						reply.OriginalBody;

					reply.ReplyId = 0;

					DbContext.Update(reply);
				}

				await DbContext.SaveChangesAsync();
			}
			else {
				serviceResponse.RedirectPath = UrlHelper.Action(nameof(Topics.Index), nameof(Topics));
			}

			var topicReplies = await DbContext.Messages.Where(m => m.ParentId == messageId).ToListAsync();

			foreach (var reply in topicReplies) {
				await RemoveMessageArtifacts(reply);
			}

			await RemoveMessageArtifacts(record);

			await DbContext.SaveChangesAsync();

			if (parentId > 0) {
				var parent = await DbContext.Messages.FirstOrDefaultAsync(item => item.Id == parentId);

				if (parent != null) {
					await RecountRepliesForTopic(parent);
				}
			}

			return serviceResponse;
		}
Beispiel #14
0
        public async Task <ServiceModels.ServiceResponse> MergeBoard(InputModels.MergeInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var fromBoard = (await Records()).FirstOrDefault(b => b.Id == input.FromId);
            var toBoard   = (await Records()).FirstOrDefault(b => b.Id == input.ToId);

            if (fromBoard is null)
            {
                serviceResponse.Error($"A record does not exist with ID '{input.FromId}'");
            }

            if (toBoard is null)
            {
                serviceResponse.Error($"A record does not exist with ID '{input.ToId}'");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            var topicBoards = DbContext.TopicBoards.Where(m => m.BoardId == fromBoard.Id).ToList();

            // Reassign messages to new board
            foreach (var topicBoard in topicBoards)
            {
                topicBoard.BoardId = toBoard.Id;
                DbContext.Update(topicBoard);
            }

            DbContext.SaveChanges();

            var categoryId = fromBoard.CategoryId;

            // Delete the board
            DbContext.Boards.Remove(fromBoard);

            DbContext.SaveChanges();

            // Remove the category if empty
            if (!DbContext.Boards.Any(b => b.CategoryId == categoryId))
            {
                var categoryRecord = (await Categories()).FirstOrDefault(item => item.Id == categoryId);

                if (categoryRecord != null)
                {
                    DbContext.Categories.Remove(categoryRecord);
                    DbContext.SaveChanges();
                }
            }

            return(serviceResponse);
        }
Beispiel #15
0
        public async Task <ServiceModels.ServiceResponse> UpdateAvatar(InputModels.UpdateAvatarInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var userRecord = await UserManager.FindByIdAsync(input.Id);

            if (userRecord is null)
            {
                var message = $"No user record found for '{input.Id}'.";
                serviceResponse.Error(message);
                Log.LogCritical(message);
            }

            CanEdit(input.Id);

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            var allowedExtensions = new[] { ".gif", ".jpg", ".png", ".jpeg" };

            var extension = Path.GetExtension(input.NewAvatar.FileName).ToLower();

            if (!allowedExtensions.Contains(extension))
            {
                serviceResponse.Error(nameof(input.NewAvatar), "Your avatar must end with .gif, .jpg, .jpeg, or .png");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            using (var inputStream = input.NewAvatar.OpenReadStream()) {
                inputStream.Position = 0;

                userRecord.AvatarPath = await ImageStore.Save(new ImageStoreSaveOptions {
                    ContainerName = Constants.InternalKeys.AvatarContainer,
                    FileName      = $"avatar{userRecord.Id}.png",
                    ContentType   = "image/png",
                    InputStream   = inputStream,
                    MaxDimension  = 100,
                    Overwrite     = true
                });
            }

            DbContext.Update(userRecord);
            DbContext.SaveChanges();

            Log.LogInformation($"Avatar was modified by '{UserContext.ApplicationUser.DisplayName}' for account '{userRecord.DisplayName}'.");

            return(serviceResponse);
        }
Beispiel #16
0
		async Task MergeReply(DataModels.Message record, InputModels.MessageInput input, ServiceModels.ServiceResponse serviceResponse) {
			var newBody = $"{record.OriginalBody}\n{input.Body}";
			var processedMessage = await ProcessMessageInput(serviceResponse, newBody);

			if (serviceResponse.Success) {
				await UpdateMessageRecord(processedMessage, record);
				serviceResponse.RedirectPath = UrlHelper.DisplayMessage(record.Id);

				await ForumHub.Clients.All.SendAsync("updated-message", new HubModels.Message {
					TopicId = record.ParentId > 0 ? record.ParentId : record.Id,
					MessageId = record.Id
				});
			}
		}
Beispiel #17
0
        public async Task <ServiceModels.ServiceResponse> Create(InputModels.CreateSmileyInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var allowedExtensions = new[] { "gif", "png" };
            var extension         = Path.GetExtension(input.File.FileName).ToLower().Substring(1);

            if (Regex.IsMatch(input.File.FileName, @"[^a-zA-Z 0-9_\-\.]"))
            {
                serviceResponse.Error("File", "Your filename contains invalid characters.");
            }

            if (!allowedExtensions.Contains(extension))
            {
                serviceResponse.Error("File", $"Your file must be: {string.Join(", ", allowedExtensions)}.");
            }

            if (DbContext.Smileys.Any(s => s.Code == input.Code))
            {
                serviceResponse.Error(nameof(input.Code), "Another smiley exists with that code.");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            var smileyRecord = new DataModels.Smiley {
                Code     = input.Code,
                Thought  = input.Thought,
                FileName = input.File.FileName
            };

            DbContext.Smileys.Add(smileyRecord);

            using (var inputStream = input.File.OpenReadStream()) {
                smileyRecord.Path = await ImageStore.Save(new ImageStoreSaveOptions {
                    ContainerName = Constants.InternalKeys.SmileyContainer,
                    FileName      = input.File.FileName,
                    ContentType   = input.File.ContentType,
                    InputStream   = inputStream,
                    Overwrite     = true
                });
            }

            DbContext.SaveChanges();

            serviceResponse.Message = $"Smiley '{smileyRecord.FileName}' was added with code '{smileyRecord.Code}'.";
            return(serviceResponse);
        }
Beispiel #18
0
        public async Task <ServiceModels.ServiceResponse> MoveBoardUp(int id)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var targetBoard = (await Records()).FirstOrDefault(b => b.Id == id);

            if (targetBoard is null)
            {
                serviceResponse.Error("No board found with that ID.");
                return(serviceResponse);
            }

            var categoryBoards = (await Records()).Where(b => b.CategoryId == targetBoard.CategoryId).OrderBy(b => b.DisplayOrder).ToList();

            var currentIndex = 1;

            foreach (var board in categoryBoards)
            {
                board.DisplayOrder = currentIndex++;
                DbContext.Update(board);
            }

            DbContext.SaveChanges();

            targetBoard = categoryBoards.First(b => b.Id == id);

            if (targetBoard.DisplayOrder > 1)
            {
                var displacedBoard = categoryBoards.FirstOrDefault(b => b.DisplayOrder == targetBoard.DisplayOrder - 1);

                if (displacedBoard != null)
                {
                    displacedBoard.DisplayOrder++;
                    DbContext.Update(displacedBoard);
                }

                targetBoard.DisplayOrder--;
                DbContext.Update(targetBoard);

                DbContext.SaveChanges();
            }
            else
            {
                targetBoard.DisplayOrder = 2;
            }

            return(serviceResponse);
        }
Beispiel #19
0
        public async Task <ServiceModels.ServiceResponse> Create(InputModels.CreateRoleInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            if (input.Name != null)
            {
                input.Name = input.Name.Trim();
            }

            if (string.IsNullOrEmpty(input.Name))
            {
                serviceResponse.Error(nameof(InputModels.CreateRoleInput.Name), "Name is required");
            }

            if (input.Description != null)
            {
                input.Description = input.Description.Trim();
            }

            if (string.IsNullOrEmpty(input.Description))
            {
                serviceResponse.Error(nameof(InputModels.CreateRoleInput.Description), "Description is required");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            if (await RoleManager.FindByNameAsync(input.Name) != null)
            {
                serviceResponse.Error(nameof(InputModels.CreateRoleInput.Name), "A role with this name already exists");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            await CreateRecord(input);

            serviceResponse.RedirectPath = UrlHelper.Action(nameof(Roles.Index), nameof(Roles));

            return(serviceResponse);
        }
Beispiel #20
0
        public async Task <ServiceModels.ServiceResponse> Register(InputModels.RegisterInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var birthday = new DateTime(input.BirthdayYear, input.BirthdayMonth, input.BirthdayDay);

            var user = new DataModels.ApplicationUser {
                DisplayName = input.DisplayName,
                Registered  = DateTime.Now,
                LastOnline  = DateTime.Now,
                UserName    = input.Email,
                Email       = input.Email,
                Birthday    = birthday
            };

            var identityResult = await UserManager.CreateAsync(user, input.Password);

            if (identityResult.Succeeded)
            {
                Log.LogInformation($"User created a new account with password '{input.Email}'.");

                var code = await UserManager.GenerateEmailConfirmationTokenAsync(user);

                var callbackUrl = EmailConfirmationLink(user.Id, code);

                if (!EmailSender.Ready)
                {
                    serviceResponse.RedirectPath = callbackUrl;
                    return(serviceResponse);
                }

                await EmailSender.SendEmailConfirmationAsync(input.Email, callbackUrl);
            }
            else
            {
                foreach (var error in identityResult.Errors)
                {
                    Log.LogError($"Error registering '{input.Email}'. Message: {error.Description}");
                    serviceResponse.Error(error.Description);
                }
            }

            return(serviceResponse);
        }
Beispiel #21
0
		public async Task<ServiceModels.ServiceResponse> CreateReply(InputModels.MessageInput input) {
			var serviceResponse = new ServiceModels.ServiceResponse();

			if (input.Id == 0) {
				throw new HttpBadRequestError();
			}

			var replyRecord = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == input.Id);

			if (replyRecord is null) {
				serviceResponse.Error($"A record does not exist with ID '{input.Id}'");
			}

			var now = DateTime.Now;
			var recentReply = (now - replyRecord.LastReplyPosted) < (now - now.AddSeconds(-30));

			if (recentReply && replyRecord.ParentId == 0) {
				var targetId = replyRecord.LastReplyId > 0 ? replyRecord.LastReplyId : replyRecord.Id;
				var previousMessageRecord = await DbContext.Messages.FirstOrDefaultAsync(m => m.Id == targetId);

				if (previousMessageRecord?.PostedById == UserContext.ApplicationUser.Id) {
					await MergeReply(previousMessageRecord, input, serviceResponse);
					return serviceResponse;
				}
			}

			if (!serviceResponse.Success) {
				return serviceResponse;
			}

			var processedMessage = await ProcessMessageInput(serviceResponse, input.Body);

			if (serviceResponse.Success) {
				var record = CreateMessageRecord(processedMessage, replyRecord);
				serviceResponse.RedirectPath = UrlHelper.DisplayMessage(record.Id);

				await ForumHub.Clients.All.SendAsync("new-reply", new HubModels.Message {
					TopicId = record.ParentId,
					MessageId = record.Id
				});
			}

			return serviceResponse;
		}
Beispiel #22
0
        public async Task <ServiceModels.ServiceResponse> Edit(InputModels.QuotesInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            foreach (var quoteInput in input.Quotes)
            {
                var record = (await Records()).FirstOrDefault(r => r.Id == quoteInput.Id);

                if (record is null)
                {
                    serviceResponse.Error($@"No record was found with the id '{quoteInput.Id}'.");
                }

                if (serviceResponse.Success)
                {
                    if (quoteInput.Approved != record.Approved)
                    {
                        record.Approved = quoteInput.Approved;
                        DbContext.Update(record);
                    }

                    if (quoteInput.OriginalBody != record.OriginalBody)
                    {
                        record.OriginalBody = quoteInput.OriginalBody;

                        var processedMessageInput = await MessageRepository.ProcessMessageInput(serviceResponse, quoteInput.OriginalBody);

                        record.DisplayBody = processedMessageInput.DisplayBody;

                        DbContext.Update(record);
                    }

                    if (serviceResponse.Success)
                    {
                        DbContext.SaveChanges();
                        serviceResponse.Message = $"Changes saved.";
                    }
                }
            }

            return(serviceResponse);
        }
Beispiel #23
0
        public async Task <ServiceModels.ServiceResponse> SendVerificationEmail()
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var code = await UserManager.GenerateEmailConfirmationTokenAsync(UserContext.ApplicationUser);

            var callbackUrl = EmailConfirmationLink(UserContext.ApplicationUser.Id, code);
            var email       = UserContext.ApplicationUser.Email;

            if (!EmailSender.Ready)
            {
                serviceResponse.RedirectPath = callbackUrl;
                return(serviceResponse);
            }

            await EmailSender.SendEmailConfirmationAsync(email, callbackUrl);

            serviceResponse.Message = "Verification email sent. Please check your email.";
            return(serviceResponse);
        }
Beispiel #24
0
        public async Task <ServiceModels.ServiceResponse> Delete(int quoteId)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var record = (await Records()).FirstOrDefault(r => r.Id == quoteId);

            if (record is null)
            {
                serviceResponse.Error($@"No record was found with the id '{quoteId}'.");
            }

            if (serviceResponse.Success)
            {
                DbContext.Quotes.Remove(record);
                await DbContext.SaveChangesAsync();

                serviceResponse.Message = $"Quote deleted.";
            }

            return(serviceResponse);
        }
Beispiel #25
0
        public async Task <ServiceModels.ServiceResponse> Delete(int id)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var smileyRecord = await DbContext.Smileys.FindAsync(id);

            if (smileyRecord is null)
            {
                serviceResponse.Error($@"No smiley was found with the id '{id}'");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            var otherSmileys = DbContext.Smileys.Where(s => s.FileName == smileyRecord.FileName).ToList();

            DbContext.Smileys.Remove(smileyRecord);

            var thoughts = DbContext.MessageThoughts.Where(t => t.SmileyId == id).ToList();

            if (thoughts.Any())
            {
                DbContext.MessageThoughts.RemoveRange(thoughts);
            }

            var container = CloudBlobClient.GetContainerReference("smileys");

            if (!otherSmileys.Any() && await container.ExistsAsync())
            {
                var blobReference = container.GetBlockBlobReference(smileyRecord.Path);
                await blobReference.DeleteIfExistsAsync();
            }

            DbContext.SaveChanges();

            serviceResponse.Message = $"The smiley was deleted.";
            return(serviceResponse);
        }
Beispiel #26
0
        public async Task <ServiceModels.ServiceResponse> Delete(int id)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var smileyRecord = await DbContext.Smileys.FindAsync(id);

            if (smileyRecord is null)
            {
                serviceResponse.Error($@"No smiley was found with the id '{id}'");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            DbContext.Smileys.Remove(smileyRecord);

            var thoughts = DbContext.MessageThoughts.Where(t => t.SmileyId == id).ToList();

            if (thoughts.Any())
            {
                DbContext.MessageThoughts.RemoveRange(thoughts);
            }

            // Only delete the file if no other smileys are using the file.
            if (!DbContext.Smileys.Any(s => s.FileName == smileyRecord.FileName))
            {
                await ImageStore.Delete(new ImageStoreDeleteOptions {
                    ContainerName = Constants.InternalKeys.SmileyImageContainer,
                    Path          = smileyRecord.Path
                });
            }

            DbContext.SaveChanges();

            serviceResponse.Message = $"The smiley was deleted.";
            return(serviceResponse);
        }
Beispiel #27
0
        public ServiceModels.ServiceResponse UpdateSiteSettings(InputModels.EditSettingsInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            foreach (var settingInput in input.Settings)
            {
                var existingRecords = Records.Where(s => s.Name == settingInput.Key && string.IsNullOrEmpty(s.UserId)).ToList();

                if (existingRecords.Any())
                {
                    DbContext.RemoveRange(existingRecords);
                }

                if (string.IsNullOrEmpty(settingInput.Value))
                {
                    continue;
                }

                var baseSetting = BaseSettings.Get(settingInput.Key);

                if (baseSetting.Options != null && !baseSetting.Options.Contains(settingInput.Value))
                {
                    throw new HttpBadRequestError();
                }

                var record = new DataModels.SiteSetting {
                    Name      = settingInput.Key,
                    Value     = settingInput.Value,
                    AdminOnly = settingInput.AdminOnly
                };

                DbContext.SiteSettings.Add(record);
            }

            DbContext.SaveChanges();

            serviceResponse.Message = $"Site settings were updated.";
            return(serviceResponse);
        }
Beispiel #28
0
        public async Task <ServiceModels.ServiceResponse> Merge(int sourceId, int targetId)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var sourceRecord = DbContext.Topics.FirstOrDefault(item => item.Id == sourceId);

            if (sourceRecord is null || sourceRecord.Deleted)
            {
                serviceResponse.Error("Source record not found");
            }

            var targetRecord = DbContext.Topics.FirstOrDefault(item => item.Id == targetId);

            if (targetRecord is null || targetRecord.Deleted)
            {
                serviceResponse.Error("Target record not found");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            if (sourceRecord.FirstMessageTimePosted > targetRecord.FirstMessageTimePosted)
            {
                await Merge(sourceRecord, targetRecord);

                serviceResponse.RedirectPath = UrlHelper.Action(nameof(Topics.Latest), nameof(Topics), new { id = targetRecord.Id });
            }
            else
            {
                await Merge(targetRecord, sourceRecord);

                serviceResponse.RedirectPath = UrlHelper.Action(nameof(Topics.Latest), nameof(Topics), new { id = sourceRecord.Id });
            }

            return(serviceResponse);
        }
Beispiel #29
0
        public async Task <ServiceModels.ServiceResponse> MergeCategory(InputModels.MergeInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var fromCategory = (await Categories()).FirstOrDefault(b => b.Id == input.FromId);
            var toCategory   = (await Categories()).FirstOrDefault(b => b.Id == input.ToId);

            if (fromCategory is null)
            {
                serviceResponse.Error($"A record does not exist with ID '{input.FromId}'");
            }

            if (toCategory is null)
            {
                serviceResponse.Error($"A record does not exist with ID '{input.ToId}'");
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            var displacedBoards = (await Records()).Where(b => b.CategoryId == fromCategory.Id).ToList();

            foreach (var displacedBoard in displacedBoards)
            {
                displacedBoard.CategoryId = toCategory.Id;
                DbContext.Update(displacedBoard);
            }

            DbContext.SaveChanges();

            DbContext.Categories.Remove(fromCategory);

            DbContext.SaveChanges();

            return(serviceResponse);
        }
Beispiel #30
0
        public async Task <ServiceModels.ServiceResponse> Login(InputModels.LoginInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            var result = await SignInManager.PasswordSignInAsync(input.Email, input.Password, input.RememberMe, lockoutOnFailure : false);

            if (result.IsLockedOut)
            {
                Log.LogWarning($"User account locked out '{input.Email}'.");
                serviceResponse.RedirectPath = UrlHelper.Action(nameof(Account.Lockout), nameof(Account));
            }
            else if (!result.Succeeded)
            {
                Log.LogWarning($"Invalid login attempt for account '{input.Email}'.");
                serviceResponse.Error("Invalid login attempt.");
            }
            else
            {
                Log.LogInformation($"User logged in '{input.Email}'.");
            }

            return(serviceResponse);
        }