<commit_before>﻿using System;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using SFA.DAS.EmployerUsers.Web.Authentication;
using IdentityServer3.Core;
using NLog;
using SFA.DAS.Configuration;
using SFA.DAS.EmployerUsers.Infrastructure.Configuration;
using SFA.DAS.EmployerUsers.Web.Models;
using SFA.DAS.EmployerUsers.Web.Models.SFA.DAS.EAS.Web.Models;
using SFA.DAS.EmployerUsers.Web.Orchestrators;
using SFA.DAS.EmployerUsers.WebClientComponents;

namespace SFA.DAS.EmployerUsers.Web.Controllers
{
    public class AccountController : ControllerBase
    {
        private readonly AccountOrchestrator _accountOrchestrator;
        private readonly IOwinWrapper _owinWrapper;
        private readonly IdentityServerConfiguration _identityServerConfiguration;
        private readonly ILogger _logger;
        private readonly IConfigurationService _configurationService;

        public AccountController(AccountOrchestrator accountOrchestrator, IOwinWrapper owinWrapper, IdentityServerConfiguration identityServerConfiguration, ILogger logger)
        {
            _accountOrchestrator = accountOrchestrator;
            _owinWrapper = owinWrapper;
            _identityServerConfiguration = identityServerConfiguration;
            _logger = logger;
        }

        [HttpGet]
        [Route("identity/employer/login")]
        public ActionResult Login(string id, string clientId)
        {

            var signinMessage = _owinWrapper.GetSignInMessage(id);
            var returnUrl = "";
            if (signinMessage != null)
            {
                returnUrl = signinMessage.ReturnUrl;
            }

            if (string.IsNullOrEmpty(clientId))
            {
                clientId = _owinWrapper.GetIdsClientId();
                returnUrl = _owinWrapper.GetIdsReturnUrl();
            }

            _owinWrapper.SetIdsContext(returnUrl, clientId);

            var model = new OrchestratorResponse<LoginViewModel>
            {
                Data = new LoginViewModel
                {
                    ReturnUrl = returnUrl,
                    ClientId = clientId
                }
            };
            if (TempData["AccountUnlocked"] != null)
            {
                model.FlashMessage = new FlashMessageViewModel()
                {

                    Severity = FlashMessageSeverityLevel.Success,
                    Headline = "Account Unlocked",
                    SubMessage =
                        "Your account has been unlocked, if you can't remember your password use the Forgotten Password link below"
                };
            }
            return View(model);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("identity/employer/login")]
        public async Task<ActionResult> Login(string id, LoginViewModel model)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(nameof(id), "Missing id when posting to login");
            }
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model), "Missing login model when posting to login");
            }

            model.OriginatingAddress = Request.UserHostAddress;
            var result = await _accountOrchestrator.Login(model);
            var response = new OrchestratorResponse<LoginViewModel>();

            if (result == null)
            {
                throw new NullReferenceException("Orchestrator did not return a result");
            }

            if (result.Data.Success)
            {
                if (result.Data.RequiresActivation)
                {
                    return RedirectToAction("Confirm");
                }

                var signinMessage = _owinWrapper.GetSignInMessage(id);
                if (signinMessage == null)
                {
                   _logger.Info($"Could not find signin message for id {id}, Redirecting to Employer Portal");
                    return await RedirectToEmployerPortal();
                }
                return Redirect(signinMessage.ReturnUrl);
            }

            if (result.Data.AccountIsLocked)
            {

                return RedirectToAction("Unlock");
            }

            if (result.Status != HttpStatusCode.OK)
            {
                response.Data = new LoginViewModel
                {
                    ReturnUrl = model.ReturnUrl,
                    ClientId = model.ClientId
                };
                response.FlashMessage = result.FlashMessage;
                response.Status = result.Status;
                response.Data.ErrorDictionary = result.FlashMessage.ErrorMessages;
                response.Status = HttpStatusCode.OK;


                return View(response);
            }

            return View(response);
        }

        [Route("account/logout")]
        public async Task<ActionResult> Logout()
        {
            var authenticationManager = HttpContext.GetOwinContext().Authentication;
            var idToken = authenticationManager.User.FindFirst("id_token")?.Value;
            _owinWrapper.SignoutUser();
            var url = $"https://{HttpContext.Request.Url.Authority}/identity/connect/endsession?id_token_hint=" + idToken;

            return new RedirectResult(url);
        }

        [HttpGet]
        [Route("account/register")]
        [OutputCache(Duration = 0)]
        public async Task<ActionResult> Register(string clientId, string returnUrl)
        {

            if (string.IsNullOrEmpty(clientId))
            {
                clientId = _owinWrapper.GetIdsClientId();
                returnUrl = _owinWrapper.GetIdsReturnUrl();
            }
            if (string.IsNullOrEmpty(returnUrl))
            {
                returnUrl = _owinWrapper.GetIdsReturnUrl();
            }

            var loginReturnUrl = Url.Action("Index", "Home", null, Request.Url.Scheme)
                                 + "identity/connect/authorize";
            var isLocalReturnUrl = returnUrl.ToLower().StartsWith(loginReturnUrl.ToLower());
            var model = await _accountOrchestrator.StartRegistration(clientId, returnUrl, isLocalReturnUrl);

            if (!model.Valid)
            {
                return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
            }

            _owinWrapper.RemovePartialLoginCookie();
            _owinWrapper.SignoutUser();

            HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity());

            var viewModel = new OrchestratorResponse<RegisterViewModel> { Data = model};

            return View(viewModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("identity/employer/register")]
        [OutputCache(Duration = 0)]
        public async Task<ActionResult> Register(RegisterViewModel model, string returnUrl)
        {
            if (string.IsNullOrEmpty(returnUrl))
            {
                return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
            }
            var id = GetLoggedInUserId();
<commit_msg>AML-3823 Added preset user details from URL<commit_after>﻿using System;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using SFA.DAS.EmployerUsers.Web.Authentication;
using IdentityServer3.Core;
using NLog;
using SFA.DAS.Configuration;
using SFA.DAS.EmployerUsers.Infrastructure.Configuration;
using SFA.DAS.EmployerUsers.Web.Models;
using SFA.DAS.EmployerUsers.Web.Models.SFA.DAS.EAS.Web.Models;
using SFA.DAS.EmployerUsers.Web.Orchestrators;
using SFA.DAS.EmployerUsers.WebClientComponents;

namespace SFA.DAS.EmployerUsers.Web.Controllers
{
    public class AccountController : ControllerBase
    {
        private readonly AccountOrchestrator _accountOrchestrator;
        private readonly IOwinWrapper _owinWrapper;
        private readonly IdentityServerConfiguration _identityServerConfiguration;
        private readonly ILogger _logger;
        private readonly IConfigurationService _configurationService;

        public AccountController(AccountOrchestrator accountOrchestrator, IOwinWrapper owinWrapper, IdentityServerConfiguration identityServerConfiguration, ILogger logger)
        {
            _accountOrchestrator = accountOrchestrator;
            _owinWrapper = owinWrapper;
            _identityServerConfiguration = identityServerConfiguration;
            _logger = logger;
        }

        [HttpGet]
        [Route("identity/employer/login")]
        public ActionResult Login(string id, string clientId)
        {

            var signinMessage = _owinWrapper.GetSignInMessage(id);
            var returnUrl = "";
            if (signinMessage != null)
            {
                returnUrl = signinMessage.ReturnUrl;
            }

            if (string.IsNullOrEmpty(clientId))
            {
                clientId = _owinWrapper.GetIdsClientId();
                returnUrl = _owinWrapper.GetIdsReturnUrl();
            }

            _owinWrapper.SetIdsContext(returnUrl, clientId);

            var model = new OrchestratorResponse<LoginViewModel>
            {
                Data = new LoginViewModel
                {
                    ReturnUrl = returnUrl,
                    ClientId = clientId
                }
            };
            if (TempData["AccountUnlocked"] != null)
            {
                model.FlashMessage = new FlashMessageViewModel()
                {

                    Severity = FlashMessageSeverityLevel.Success,
                    Headline = "Account Unlocked",
                    SubMessage =
                        "Your account has been unlocked, if you can't remember your password use the Forgotten Password link below"
                };
            }
            return View(model);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("identity/employer/login")]
        public async Task<ActionResult> Login(string id, LoginViewModel model)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(nameof(id), "Missing id when posting to login");
            }
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model), "Missing login model when posting to login");
            }

            model.OriginatingAddress = Request.UserHostAddress;
            var result = await _accountOrchestrator.Login(model);
            var response = new OrchestratorResponse<LoginViewModel>();

            if (result == null)
            {
                throw new NullReferenceException("Orchestrator did not return a result");
            }

            if (result.Data.Success)
            {
                if (result.Data.RequiresActivation)
                {
                    return RedirectToAction("Confirm");
                }

                var signinMessage = _owinWrapper.GetSignInMessage(id);
                if (signinMessage == null)
                {
                   _logger.Info($"Could not find signin message for id {id}, Redirecting to Employer Portal");
                    return await RedirectToEmployerPortal();
                }
                return Redirect(signinMessage.ReturnUrl);
            }

            if (result.Data.AccountIsLocked)
            {

                return RedirectToAction("Unlock");
            }

            if (result.Status != HttpStatusCode.OK)
            {
                response.Data = new LoginViewModel
                {
                    ReturnUrl = model.ReturnUrl,
                    ClientId = model.ClientId
                };
                response.FlashMessage = result.FlashMessage;
                response.Status = result.Status;
                response.Data.ErrorDictionary = result.FlashMessage.ErrorMessages;
                response.Status = HttpStatusCode.OK;


                return View(response);
            }

            return View(response);
        }

        [Route("account/logout")]
        public async Task<ActionResult> Logout()
        {
            var authenticationManager = HttpContext.GetOwinContext().Authentication;
            var idToken = authenticationManager.User.FindFirst("id_token")?.Value;
            _owinWrapper.SignoutUser();
            var url = $"https://{HttpContext.Request.Url.Authority}/identity/connect/endsession?id_token_hint=" + idToken;

            return new RedirectResult(url);
        }

        [HttpGet]
        [Route("account/register")]
        [OutputCache(Duration = 0)]
        public async Task<ActionResult> Register(string clientId, string returnUrl, string firstName, string lastName, string email)
        {

            if (string.IsNullOrEmpty(clientId))
            {
                clientId = _owinWrapper.GetIdsClientId();
                returnUrl = _owinWrapper.GetIdsReturnUrl();
            }
            if (string.IsNullOrEmpty(returnUrl))
            {
                returnUrl = _owinWrapper.GetIdsReturnUrl();
            }

            var loginReturnUrl = Url.Action("Index", "Home", null, Request.Url.Scheme)
                                 + "identity/connect/authorize";
            var isLocalReturnUrl = returnUrl.ToLower().StartsWith(loginReturnUrl.ToLower());
            var model = await _accountOrchestrator.StartRegistration(clientId, returnUrl, isLocalReturnUrl);

            if (!model.Valid)
            {
                return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
            }

            if (!string.IsNullOrWhiteSpace(firstName)) model.FirstName = firstName;
            if (!string.IsNullOrWhiteSpace(lastName)) model.LastName = lastName;
            if (!string.IsNullOrWhiteSpace(email)) model.Email = email;

            _owinWrapper.RemovePartialLoginCookie();
            _owinWrapper.SignoutUser();

            HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity());

            var viewModel = new OrchestratorResponse<RegisterViewModel> { Data = model};

            return View(viewModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("identity/employer/register")]
        [OutputCache(Duration = 0)]
        public async Task<ActionResult> Register(RegisterViewModel model, string returnUrl)
        {
            if (string.IsNullOrEmpty(returnUrl))
            {
                return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
            }
            var id = GetLoggedInUserId();

{'fraction_non_alphanumeric': 0.08088034886890161, 'fraction_numerical': 0.000681384573453257, 'mean_word_length': 1.8795369825387482, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '256419', 'n_tokens_mistral': 3694, 'n_tokens_neox': 3537, 'n_words': 722}