Пример #1
0
        public async Task <IActionResult> Create(IFormCollection request)
        {
            try
            {
                Enum.TryParse(request.Str("noticeboard"), out Noticeboard noticeboard);

                Notice n = new Notice
                {
                    Title       = request.Str("title"),
                    Noticeboard = noticeboard,
                    LongDesc    = request.Str("long_desc"),
                    Urgent      = request.Bool("urgent") ? 1 : 0,
                    Active      = request.Bool("active"),
                };

                await _Database.AddAsync(n);

                await _Database.SaveChangesAsync();

                return(Ok($"Notice \"{n.Title}\" has been issued."));
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error saving notice: {0}", ex.Message);
                _Logger.LogTrace(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Error issuing the notice, try again later.", ex.Message)));
            }
        }
        public async Task <IActionResult> AddItem(IFormCollection request)
        {
            try
            {
                if (string.IsNullOrEmpty(request.Str("navitem")))
                {
                    return(BadRequest(new ResponseHelper("Something went wrong, please try again later", "No nav-item data was sent")));
                }

                NavItem newItem = JsonConvert.DeserializeObject <NavItem>(request.Str("navitem"));

                // Give an order index that places this at the end of the list, for its section
                newItem.OrderIndex = await _Db.NavItems.Where(n => n.Section == newItem.Section).DefaultIfEmpty().MaxAsync(m => m.OrderIndex) + 1;

                await _Db.AddAsync(newItem);

                // Add new dropdowns, if any
                if (newItem.NavItemPages != null)
                {
                    await _Db.AddRangeAsync(newItem.NavItemPages);
                }

                await _Db.SaveChangesAsync();

                return(Ok(newItem.Id));
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error creating new navlink", ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Something went wrong, please try again later.", ex.Message)));
            }
        }
        public async Task <IActionResult> AddCategory(IFormCollection form)
        {
            try
            {
                string categoryName = form.Str("categoryName");

                // Check for existing record by this name
                if (await _Db.FactFileCategories.Where(cat => cat.Name == categoryName).FirstOrDefaultAsync() != null)
                {
                    return(BadRequest(new ResponseHelper("A category with this name already exists!")));
                }

                // Add new record and save
                await _Db.FactFileCategories.AddAsync(new FactFileCategory
                {
                    Name   = categoryName,
                    Active = true
                });

                await _Db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error retrieving fact file categories", ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Something went wrong, please try again in a few minutes.", ex.Message)));
            }
        }
        public async Task <IActionResult> UpdateContactSettings(IFormCollection request)
        {
            try
            {
                SystemSettings settings = await _Db.SystemSettings.OrderByDescending(o => o.Id).FirstOrDefaultAsync();

                // Update the new information
                settings.EmailBookings = request.Str("emailBookings");
                settings.EmailGeneral  = request.Str("emailGeneral");
                settings.Phone         = request.Str("phone");
                settings.UrlFacebook   = request.Str("urlFacebook");
                settings.UrlGooglePlay = request.Str("urlGooglePlay");
                settings.UrlGoogleMaps = request.Str("urlGoogleMaps");
                settings.FooterText    = request.Str("missionStatement");

                // Save to database
                await _Db.SaveChangesAsync();

                _Logger.LogInformation($"{User.AccountName()} updated the sites contact settings");
                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error updating system contact settings: {0}", ex.Message);
                _Logger.LogTrace(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Error updating system contact settings, please try again later", ex.Message)));
            }
        }
        public async Task <IActionResult> AddQuickLink(int pageId, int sectionId)
        {
            try
            {
                Page page = await _Db.Pages.FindAsync(pageId);

                page.QuickLink = (QuickLinkSection)sectionId;
                await _Db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error adding quick link: {0}", ex.Message);
                _Logger.LogTrace(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Error adding quick link, please try again later", ex.Message)));
            }
        }
Пример #6
0
        public async Task <IActionResult> AddTrack(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(BadRequest(new ResponseHelper("You must provide a track name.")));
            }

            Track track = new Track
            {
                Name   = name,
                Active = false
            };

            await _Db.AddAsync(track);

            await _Db.SaveChangesAsync();

            return(Ok(track.Id));
        }
Пример #7
0
        public async Task <bool> AddVoteAsync(string userId, string category)
        {
            using (var context = new WebsiteDataContext())
            {
                context.Mobro2016Votes.AddOrUpdate(new Mobro2016Vote(userId, category));
                var _ = await context.SaveChangesAsync().ConfigureAwait(false);
            }

            return(true);
        }
Пример #8
0
        public async Task <IActionResult> Index(IFormCollection request)
        {
            try
            {
                Account account = await _Db.Accounts.FindAsync(User.AccountId());

                account.Name        = request.Str("name");
                account.Email       = request.Str("email");
                account.PhoneNumber = request.Str("phoneNumber");
                await _Db.SaveChangesAsync();

                _Logger.LogInformation("Information updated for account belonging to {0}", account.Name);
                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error updating account belonging to {0}: {1}", User.AccountName(), ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest(new ResponseHelper("We could not update your account, please try again later", ex.Message)));
            }
        }
Пример #9
0
        public async Task <IActionResult> UpdateAccountStatus(int id)
        {
            try
            {
                Account account = await _Db.Accounts.FindAsync(id);

                // Stop a user from disabling their own account
                if (account.Id == User.AccountId())
                {
                    return(Conflict("You cannot alter your own account status"));
                }

                // Non Developers cannot alter developer accounts
                if (account.Developer && !_Db.Accounts.Find(User.AccountId()).Developer)
                {
                    return(BadRequest("You cannot change the settings of a developer's account"));
                }

                account.Active = !account.Active;


                await _Db.SaveChangesAsync();

                _Logger.LogInformation("{0} has {1} {2}s account", User.AccountName(), (account.Active ? "Activated" : "Deactivated"), account.Name);

                await _EmailService.SendAccountStatusAsync(account.Active, account.ToEmailContact(), HttpContext.Request.BaseUrl());

                return(Ok($"{(account.Active ? "Activated" : "Deactivated")} {account.Name}s account"));
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error changing the status of an account (Account Id: {0}): {1}", id, ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message)));
            }
        }
        public async Task <IActionResult> Index(string token, IFormCollection request)
        {
            if (string.IsNullOrEmpty(token))
            {
                _Logger.LogDebug("Password reset attempted ({0}) with no token provided", request.Str("email"));
                return(BadRequest((new ResponseHelper("Invalid reset token"))));
            }

            try
            {
                PasswordReset reset = await _Db.PasswordResets.Include(i => i.Account)
                                      .Where(c => c.Token == token && c.Account.Email == request.Str("email") && c.ExpiresAt > DateTime.UtcNow)
                                      .FirstOrDefaultAsync();

                if (reset == null)
                {
                    _Logger.LogDebug("Password reset attempted ({0}) with expired or invalid token", request.Str("email"));
                    return(BadRequest((new ResponseHelper("Reset token invalid or expired"))));
                }

                if (request.Str("password") != request.Str("passswordConfirm"))
                {
                    _Logger.LogDebug("Password reset attempted ({0}) with mismatching passwords", request.Str("email"));
                    return(BadRequest(new ResponseHelper("Your password and password confirmation do not match")));
                }


                Account account = await _Db.Accounts.FindAsync(reset.Account.Id);

                account.Password           = _Hasher.HashPassword(account, request.Str("password"));
                account.ForcePasswordReset = false;
                reset.ExpiresAt            = DateTime.UtcNow;


                await _Db.SaveChangesAsync();

                _Logger.LogInformation("Password has been updated for account belonging to {0}", account.Name);

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error updating password for account belonging to {0}: {1}", request.Str("email"), ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message)));
            }
        }
Пример #11
0
        public async Task <IActionResult> Index(IFormCollection request)
        {
            Account account = await _Db.Accounts.Where(c => c.Email == request.Str("email")).FirstOrDefaultAsync();

            if (account != null)
            {
                _Logger.LogDebug("Unable to create account using {0} as an account already exists for this email address", request.Str("email"));
                return(BadRequest(new ResponseHelper("An account with that email address already exists")));
            }

            try
            {
                account = new Account
                {
                    Email  = request.Str("email"),
                    Name   = request.Str("name"),
                    Active = false,
                };

                account.Password = _Hasher.HashPassword(account, RandomString(30));
                await _Db.AddAsync(account);

                PasswordReset reset = new PasswordReset(
                    account,
                    DateTime.UtcNow.AddHours(_Config["LoginSettings:NewAccountResetTokenLength"].ToInt())
                    );

                await _Db.AddAsync(reset);

                await _Db.SaveChangesAsync();

                _Logger.LogInformation("New account created - Name: {0}, Email: {1}", account.Name, account.Email);
                await _EmailService.SendNewAccountEmailAsync(reset, User, Request.BaseUrl());

                return(Ok(Url.Action("Index", "Users", new { area = "admin" })));
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error while creating new account: {0}", ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message)));
            }
        }
Пример #12
0
        public async Task ResetAsync()
        {
            using (var context = new WebsiteDataContext())
            {
                context.Mobro2016Votes.RemoveRange(context.Mobro2016Votes.AsEnumerable());
                var _ = await context.SaveChangesAsync().ConfigureAwait(false);
            }

            using (var context = new WebsiteDataContext())
            {
                this.AddVote(context, Guid.NewGuid().ToString(), "barry-stache");
                this.AddVote(context, Guid.NewGuid().ToString(), "biker-stache");
                this.AddVote(context, Guid.NewGuid().ToString(), "groucho-stache");
                this.AddVote(context, Guid.NewGuid().ToString(), "logan-stache");
                this.AddVote(context, Guid.NewGuid().ToString(), "mutton-chops-stache");
                this.AddVote(context, Guid.NewGuid().ToString(), "price-stache");
                this.AddVote(context, Guid.NewGuid().ToString(), "stark-stache");
                this.AddVote(context, Guid.NewGuid().ToString(), "tai-chi-master-stache");

                var _ = await context.SaveChangesAsync().ConfigureAwait(false);
            }
        }
        public async Task <IActionResult> Index(IFormCollection request)
        {
            try
            {
                Account account = await _Db.Accounts.Where(c => c.Email == request.Str("email")).FirstOrDefaultAsync();

                if (account != null)
                {
                    List <PasswordReset> oldTokens = await _Db.PasswordResets.Where(c => c.Account.Id == account.Id).ToListAsync() ?? new List <PasswordReset>();

                    foreach (PasswordReset resetToken in oldTokens)
                    {
                        resetToken.ExpiresAt = DateTime.UtcNow;
                    }

                    PasswordReset reset = new PasswordReset(
                        account,
                        DateTime.UtcNow.AddMinutes(_Config["LoginSettings:PasswordResetTokenLength"].ToInt())
                        );

                    await _Db.AddAsync(reset);

                    await _Db.SaveChangesAsync();

                    await _EmailService.SendPasswordResetEmailAsync(reset, this.Request.BaseUrl());

                    _Logger.LogInformation("Password reset requested for account belonging to {0}", account.Name);
                }

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error requesting password reset for account belonging to {0}: {1}", request.Str("email"), ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message)));
            }
        }
Пример #14
0
        public async Task <IActionResult> AddQuiz(QuizArgs data)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            Quiz newQuiz = new Quiz
            {
                Title      = data.Title,
                ImageId    = (int)data.ImageId,
                Shuffle    = (bool)data.Shuffle,
                UnlockCode = data.UnlockCode
            };

            await _Db.AddAsync(newQuiz);

            await _Db.SaveChangesAsync();

            return(Ok(newQuiz.Id));
        }
Пример #15
0
        public async Task <IActionResult> CreateRevision(int pageId, IFormCollection request)
        {
            /* To be supplied in request body -
             *
             * Reason for change - e.g. Updated pricing information
             * Template ID
             * Collection of text components
             * Collection of media components
             *
             */
            try
            {
                // Load page from database
                Page page = await _Db.Pages.FindAsync(pageId);

                if (page == null)
                {
                    return(BadRequest("No page exists for given page ID"));
                }

                List <TextComponent> newRevisionTextComponents =
                    request.Deserialize(typeof(List <TextComponent>), "textComponents");

                List <MediaComponent> newRevisionMediaComponents =
                    request.Deserialize(typeof(List <MediaComponent>), "imageComponents");

                // Todo: Do this after the view has had template switching enabled
                // Load template from database
                // PageTemplate template = await _Db.PageTemplates
                //    .FindAsync(request.Int("templateId"));

                // Fetch the original revision
                PageRevision old = await _Db.PageRevisions
                                   .Include(pr => pr.Template)
                                   .Include(pr => pr.RevisionMediaComponents)
                                   .ThenInclude(rmc => rmc.MediaComponent)
                                   .Include(pr => pr.RevisionTextComponents)
                                   .ThenInclude(rtc => rtc.TextComponent)
                                   .ThenInclude(tc => tc.CmsButton)
                                   .Where(pr => pr.Page == page)
                                   .OrderByDescending(pr => pr.CreatedAt)
                                   .FirstOrDefaultAsync();

                var oldRevision = new
                {
                    old.Template,
                    TextComponents = old.RevisionTextComponents
                                     .Select(rtc => rtc.TextComponent)
                                     .OrderBy(tc => tc.SlotNo)
                                     .ToList(),

                    MediaComponents = old.RevisionMediaComponents
                                      .Select(rmc => rmc.MediaComponent)
                                      .OrderBy(tc => tc.SlotNo)
                                      .ToList()
                };

                // Create the new page revision
                PageRevision newRevision = new PageRevision
                {
                    Page      = page,
                    Template  = oldRevision.Template,
                    Reason    = request.Str("reason"),
                    CreatedBy = await _Db.Accounts.FindAsync(User.AccountId()),
                };

                // Assign the new revision an ID
                await _Db.AddAsync(newRevision);

                for (int i = 0; i < newRevision.Template.TextAreas; i++)
                {
                    TextComponent textComponentToSave = null;

                    // Only save a new text component if it has changed
                    if (!newRevisionTextComponents[i].Equals(oldRevision.TextComponents[i]))
                    {
                        textComponentToSave = newRevisionTextComponents[i];

                        // Set ID to 0 so that EF Core assigns us a new one
                        textComponentToSave.Id = 0;

                        // Save a new button if the components button does not yet exist in database.
                        if (textComponentToSave.CmsButton != null &&
                            !textComponentToSave.CmsButton.Equals(oldRevision.TextComponents[i].CmsButton))
                        {
                            await _Db.AddAsync(textComponentToSave.CmsButton);
                        }

                        // Generate ID for the new TextComponent
                        await _Db.AddAsync(textComponentToSave);
                    }

                    // Add association between component and new revision
                    await _Db.AddAsync(new RevisionTextComponent
                    {
                        // Use the new components ID if it exists, other use existing (unchanged) component
                        // from previous revision
                        TextComponentId = textComponentToSave?.Id ?? oldRevision.TextComponents[i].Id,
                        PageRevisionId  = newRevision.Id
                    });
                }

                // Do the same for media components
                for (int i = 0; i < newRevision.Template.MediaAreas; i++)
                {
                    MediaComponent mediaComponentToSave = null;

                    // Only create new media component if the old one was modified
                    if (!newRevisionMediaComponents[i].Equals(oldRevision.MediaComponents[i]))
                    {
                        mediaComponentToSave = newRevisionMediaComponents[i];

                        // Generate new ID
                        mediaComponentToSave.Id = 0;
                        await _Db.AddAsync(mediaComponentToSave);
                    }

                    // Add association to new revision
                    await _Db.AddAsync(new RevisionMediaComponent
                    {
                        PageRevisionId   = newRevision.Id,
                        MediaComponentId = mediaComponentToSave?.Id ?? oldRevision.MediaComponents[i].Id
                    });
                }

                // Save changes
                await _Db.SaveChangesAsync();

                _Logger.LogDebug("New page revision created for page {0} ({1}): {2}", pageId, page.Name, newRevision.Reason);

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error creating new revision for page {0}: {1}", pageId, ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest("Something went wrong, please try again later."));
            }
        }
Пример #16
0
        //POST: /admin/pages/create
        public async Task <IActionResult> Create(IFormCollection request,
                                                 [Bind("Name", "Description", "Section")] Page page)
        {
            PageTemplate template = await _Db.PageTemplates.FindAsync(
                request.Int("templateId"));

            if (template == null)
            {
                return(NotFound($"The chosen template was not found."));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest("Server side validation failed."));
            }

            try
            {
                await _Db.AddAsync(page);

                // Create initial page revision
                PageRevision pageRevision = new PageRevision
                {
                    Page      = page,
                    Template  = template,
                    CreatedBy = await _Db.Accounts.FindAsync(User.AccountId())
                };
                await _Db.AddAsync(pageRevision);

                // Create empty text fields, and associate to new page
                for (int i = 0; i < template.TextAreas; i++)
                {
                    TextComponent textField = new TextComponent {
                        SlotNo = i
                    };
                    await _Db.AddAsync(textField);

                    await _Db.AddAsync(new RevisionTextComponent
                    {
                        TextComponent = textField,
                        PageRevision  = pageRevision,
                    });
                }

                // Create empty media fields, and associate to new page
                for (int i = 0; i < template.MediaAreas; i++)
                {
                    MediaComponent mediaComponent = new MediaComponent {
                        SlotNo = i
                    };
                    await _Db.AddAsync(mediaComponent);

                    await _Db.AddAsync(new RevisionMediaComponent
                    {
                        PageRevisionId   = pageRevision.Id,
                        MediaComponentId = mediaComponent.Id
                    });
                }

                // Save all to database in one transaction
                await _Db.SaveChangesAsync();

                // Return new page URL to the caller
                return(Ok(page.AbsoluteUrl));
            }
            catch (Exception ex)
            {
                _Logger.LogWarning("Error creating new page: {0}", ex.Message);
                _Logger.LogWarning(ex.StackTrace);
                return(BadRequest("There was an error creating the page. Please try again later."));
            }
        }
Пример #17
0
        public async Task <IActionResult> Index(IFormCollection request)
        {
            try
            {
                // Create required directories if not existing
                EnsureInit();

                // Deserialize cropping data if applicable
                CropData cropData = null;
                if (request.Str("cropData") != null)
                {
                    cropData = JsonConvert.DeserializeObject <CropData>(request.Str("cropData"));
                }


                // Original filename
                string uploadedName = request.Str("filename");

                // Generate a backend filename for the uploaded file - same extension as uploaded file.
                string filename = Guid.NewGuid().ToString() + Path.GetExtension(uploadedName);

                string fileType = request.Str("fileType");

                // Determine what type of file has been uploaded and act accordingly (may want to refactor these)

                // FOR IMAGES
                if (MediaType.MimesForCategory(MediaCategory.Image).Contains(fileType))
                {
                    string filepath = Path.Combine("Storage", "Media", "Images", filename);

                    // Save image and all associated versions of it.
                    var filedata = ImageUtils.SaveImage(request.Str("file")
                                                        .Split(',')[1], filepath, cropData);

                    // Create database record to track images
                    ImageMedia dbImageMedia = new ImageMedia {
                        Name      = Path.GetFileNameWithoutExtension(uploadedName),
                        MediaType = MediaType.FromString(fileType),
                        FilePath  = filepath,
                        Size      = filedata["size"],
                        Title     = request.Str("title"),
                        Alt       = request.Str("alt"),
                        Width     = filedata["width"],
                        Height    = filedata["height"],
                        Versions  = filedata["versions"]
                    };

                    await _Db.AddAsync(dbImageMedia);
                }

                // FOR AUDIO
                else if (MediaType.MimesForCategory(MediaCategory.Audio).Contains(fileType))
                {
                    string filepath = Path.Combine("Storage", "Media", "Audio", filename);

                    // Save the audio file
                    byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes();
                    await System.IO.File.WriteAllBytesAsync(filepath, bytes);

                    // Read the audio file to determine its duration - it will either be mp3(mpeg) or wav

                    // Configure ffprobe path using appsettings values
                    FFProbe probe = new FFProbe();
                    probe.ToolPath = _Config["ffprobePath"];

                    // If running linux, look for ffprobe instaed of ffprobe.exe
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        probe.FFProbeExeName = "ffprobe";
                    }

                    // Get audio file metadata
                    MediaInfo mediaInfo = probe.GetMediaInfo(Path.Combine(_HostingEnv.ContentRootPath, filepath));

                    // Create the media database record
                    AudioMedia audioMedia = new AudioMedia
                    {
                        Name      = Path.GetFileNameWithoutExtension(uploadedName),
                        MediaType = MediaType.FromString(fileType),
                        FilePath  = filepath,
                        Size      = new FileInfo(filepath).Length,
                        Duration  = Math.Round(mediaInfo.Duration.TotalSeconds)
                    };

                    await _Db.AddAsync(audioMedia);
                }

                // FOR GENERAL
                else if (MediaType.MimesForCategory(MediaCategory.General).Contains(fileType))
                {
                    string filepath = Path.Combine("Storage", "Media", "Documents", filename);

                    // Save the file
                    byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes();
                    System.IO.File.WriteAllBytes(filepath, bytes);

                    // Create the media database record
                    GeneralMedia generalMedia = new GeneralMedia
                    {
                        Name      = Path.GetFileNameWithoutExtension(uploadedName),
                        MediaType = MediaType.FromString(fileType),
                        FilePath  = filepath,
                        Size      = new FileInfo(filepath).Length,
                    };

                    await _Db.AddAsync(generalMedia);
                }

                else
                {
                    return(new UnsupportedMediaTypeResult());
                }

                await _Db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error uploading file: {0}", ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Something went wrong, please contact the devloper if the problem persists", ex.Message)));
            }
        }
Пример #18
0
        public async Task <IActionResult> Index(IFormCollection request, string ReturnUrl)
        {
            if (!User.Identity.IsAuthenticated)
            {
                try
                {
                    Account account = await _Db.Accounts.Where(c => c.Email == request.Str("email")).FirstOrDefaultAsync();

                    // No Account
                    if (account == null)
                    {
                        _Logger.LogInformation("User attempted logging in with invalid email address");
                        return(Unauthorized(new ResponseHelper("Invalid email or password")));
                    }

                    // Invalid Password
                    if (_Hasher.VerifyHashedPassword(account, account.Password, request.Str("password")) != PasswordVerificationResult.Success)
                    {
                        _Logger.LogInformation("User attempted logging into account belonging to {0} with invalid password", account.Name);
                        return(Unauthorized(new ResponseHelper("Invalid email or password")));
                    }

                    // Inactive Account
                    if (!account.Active)
                    {
                        _Logger.LogInformation("User attempted logging into account belonging to {0}, but the account needs to be activated", account.Name);
                        return(Unauthorized(new ResponseHelper("Your account requires activation from an administrator")));
                    }


                    var claims = new List <Claim>
                    {
                        new Claim("id", account.Id.ToString()),
                        new Claim("name", account.Name),
                        new Claim("email", account.Email)
                    };

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

                    var authProperties = new AuthenticationProperties
                    {
                        AllowRefresh = true,
                        IsPersistent = true,
                    };

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

                    account.LastLogin = DateTime.UtcNow;
                    await _Db.SaveChangesAsync();

                    _Logger.LogDebug("User has logged into account belonging to {0}", account.Name);
                }
                catch (Exception ex)
                {
                    _Logger.LogError("Error while logging in: {0}", ex.Message);
                    _Logger.LogError(ex.StackTrace);
                    return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message)));
                }
            }

            if (string.IsNullOrEmpty(ReturnUrl))
            {
                ReturnUrl = Url.Action(
                    "Index",
                    "Dashboard",
                    new { area = "admin" }
                    );
            }
            else
            {
                ReturnUrl = this.Request.BaseUrl() + ReturnUrl.Substring(1);
            }

            return(Ok(ReturnUrl));
        }