-
Notifications
You must be signed in to change notification settings - Fork 47
/
DefaultController.cs
82 lines (75 loc) · 2.98 KB
/
DefaultController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Mvp.Project.MvpSite.Middleware;
using Mvp.Project.MvpSite.Models;
using Okta.AspNetCore;
using Sitecore.AspNet.RenderingEngine;
using Sitecore.LayoutService.Client.Exceptions;
using Sitecore.LayoutService.Client.Response.Model;
using Sitecore.LayoutService.Client.Response.Model.Fields;
namespace Mvp.Project.MvpSite.Controllers
{
public class DefaultController(ILogger<DefaultController> logger)
: Controller
{
// Inject Sitecore rendering middleware for this controller action
// (enables model binding to Sitecore objects such as Route,
// and causes requests to the Sitecore Layout Service for controller actions)
[UseMvpSiteRendering]
public IActionResult Index(LayoutViewModel model)
{
IActionResult result = null;
ISitecoreRenderingContext request = HttpContext.GetSitecoreRenderingContext();
if (request.Response?.HasErrors ?? false)
{
foreach (SitecoreLayoutServiceClientException error in request.Response.Errors)
{
switch (error)
{
default:
logger.LogError(error, error.Message);
throw error;
}
}
}
else if (!(HttpContext.User.Identity?.IsAuthenticated ?? false) && IsSecurePage(request) && !(request.Response?.Content?.Sitecore?.Context?.IsEditing ?? false))
{
AuthenticationProperties properties = new()
{
RedirectUri = HttpContext.Request.GetEncodedUrl()
};
result = Challenge(properties, OktaDefaults.MvcAuthenticationScheme);
}
else
{
result = View(model);
}
return result;
}
private static bool IsSecurePage(ISitecoreRenderingContext request)
{
bool result = false;
if (request.Response?.Content?.Sitecore?.Route?.Fields.TryGetValue("RequiresAuthentication", out IFieldReader requiresAuthFieldReader) ?? false)
{
result = requiresAuthFieldReader.Read<CheckboxField>().Value;
}
return result;
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new LayoutViewModel
{
MenuTitle = new TextField("Error")
});
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Healthz()
{
// TODO: Do we want to add logic here to confirm connectivity with SC etc?
return Ok("Healthy");
}
}
}