public async Task <IActionResult> Login()
        {
            string referer   = Request.Headers["Referer"].ToString().TrimEnd('/');
            string returnUrl = referer + _loginReturnPath;

            if (HttpContext.Connection.ClientCertificate == null)
            {
                returnUrl += $"?error=true";
                return(Redirect(returnUrl));
            }

            try
            {
                //Parse client certificate
                X509Certificate2 certificate = HttpContext.Connection.ClientCertificate;
                ParseResiult     parseResult = DigitalSignatureParser.DecodeCert(certificate);

                if (parseResult.Success)
                {
                    ApplicationUser user = _userManager.Users.SingleOrDefault(u => u.Certificate_UniqueIdentifier.Trim() == parseResult.HolderEGN.Trim() && !u.Deleted);

                    if (user == null)
                    {
                        returnUrl += $"?error=true&message=userNotFound";
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        /*
                         * Ако потребителя е сменил своето име в подписа, го променяме и в базата
                         * т.е. ако жена се омъжи и смени фамилията си и т.н.
                         * Ако подписа е променен също запазваме данните
                         */
                        if (user.Certificate_Name == null ||
                            user.Certificate_Name.ToLower().Trim() != parseResult.HolderName.ToLower().Trim() ||
                            user.Certificate_Thumbprint != certificate.Thumbprint)
                        {
                            //Check if certificate is the same and update user info if needed
                            user.Certificate            = certificate.RawData;
                            user.Certificate_Thumbprint = certificate.Thumbprint;
                            user.Certificate_Name       = parseResult.HolderName;
                            await _userManager.UpdateAsync(user);
                        }
                    }

                    if (!user.EmailConfirmed)
                    {
                        await SendConfirmEmailAsync(user);

                        returnUrl += $"?error=true&message=EmailNotConfirmed,ConfirmationEmailResend";
                        return(Redirect(returnUrl));
                    }

                    if (!user.ConfirmedByAdmin)
                    {
                        returnUrl += $"?error=true&message=notConfirmedByAdmin";
                        return(Redirect(returnUrl));
                    }

                    //sign in existing user
                    return(await SignInExistingUser(user, returnUrl));
                }

                Log.Error("Error parsing login certificate" + String.Join(", ", parseResult.Errors));
                returnUrl += $"?error=true";
                return(Redirect(returnUrl));
            }
            catch (Exception x)
            {
                Log.Error(x, "Error parsing login certificate");
                returnUrl += $"?error=true";
                return(Redirect(returnUrl));
            }
        }
        public async Task <IActionResult> Register([FromQuery] string userType, [FromQuery] string email, [FromQuery] string chsiNumber, [FromQuery] string lang = "bg")
        {
            string referer   = Request.Headers["Referer"].ToString().TrimEnd('/');
            string returnUrl = referer + _registerReturnPath;

            Thread.CurrentThread.CurrentCulture   = new CultureInfo(lang);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);

            if (HttpContext.Connection.ClientCertificate == null || string.IsNullOrWhiteSpace(userType))
            {
                returnUrl += $"?error=true";
                return(Redirect(returnUrl));
            }

            if ((userType == UserType.CHSI.ToString() || userType == UserType.CHSIHelper.ToString()) && string.IsNullOrWhiteSpace(chsiNumber))
            {
                returnUrl += $"?error=true";
                return(Redirect(returnUrl));
            }

            try
            {
                X509Certificate2 certificate = HttpContext.Connection.ClientCertificate;
                ParseResiult     parseResult = DigitalSignatureParser.DecodeCert(certificate);

                if (parseResult.Success)
                {
                    //check egn
                    bool isDuplicateEgn = _userManager.Users.Any(u => u.Certificate_UniqueIdentifier == parseResult.HolderEGN.ToUpper().Trim() && !u.Deleted);

                    if (isDuplicateEgn)
                    {
                        returnUrl += $"?error=true&message=duplicateEgn";
                        return(Redirect(returnUrl));
                    }

                    // if user did not pass an email we put the one from the digital signature
                    if (string.IsNullOrWhiteSpace(email))
                    {
                        email = parseResult.HolderEmail;
                    }

                    //check email
                    if (string.IsNullOrWhiteSpace(email))
                    {
                        //Redirect to register page with parameter to gather additional info
                        returnUrl += "?requireEmail=true";
                        return(Redirect(returnUrl));
                    }

                    //Create new user
                    ApplicationUser user = new ApplicationUser()
                    {
                        Certificate            = certificate.RawData,
                        Certificate_Thumbprint = certificate.Thumbprint,
                        Email                        = email,
                        EmailConfirmed               = false,
                        UserName                     = GenerateUserName(parseResult.HolderName),
                        Certificate_Name             = parseResult.HolderName.Trim(),
                        Certificate_UniqueIdentifier = parseResult.HolderEGN.Trim(),
                        AuthType                     = AuthType.ESIGN.ToString(),
                        UserType                     = userType,
                        ConfirmedByAdmin             = false,
                        CreatedOn                    = DateTime.UtcNow
                    };

                    string userRole = Constants.Role_AuctionOrgaziner;

                    if (userType == UserType.AUCPAR.ToString())
                    {
                        user.ConfirmedByAdmin = true;
                        userRole = Constants.Role_AuctionParticipant;
                    }
                    else if (userType == UserType.CHSI.ToString())
                    {
                        user.CHSINumber = chsiNumber;
                        //Check CHSI in CHSI register by number
                        await CheckCHSI(user, returnUrl);
                    }
                    else if (userType == UserType.CHSIHelper.ToString())
                    {
                        user.CHSINumber = chsiNumber;
                        //TODO Check CHSI helpers in CHSI register by number
                        //Return error if chsi is not found
                        bool ChsiRegisterCheck = true;

                        user.CheckedInCHSIRegister = ChsiRegisterCheck;
                        user.ConfirmedByAdmin      = ChsiRegisterCheck;
                    }

                    IdentityResult ir = await _userManager.CreateAsync(user);

                    if (!ir.Succeeded)
                    {
                        //create new user fail
                        Log.Error("Error creating user with ESign", String.Join(',', ir.Errors.Select(x => x.Description)));
                        returnUrl += $"?error=true";
                        return(Redirect(returnUrl));
                    }

                    //Assign to role
                    var roleAddResult = await _userManager.AddToRoleAsync(user, userRole);

                    if (!roleAddResult.Succeeded)
                    {
                        Log.Error($"Error adding user ID= {user.Id} to role {userRole}", string.Join(',', roleAddResult.Errors.Select(x => x.Description)));
                    }

                    try
                    {
                        //create person
                        await CreatePerson(user.Id, parseResult.HolderName, email);

                        //send confirmation email
                        await SendConfirmEmailAsync(user);

                        return(Redirect(returnUrl));
                    }
                    catch (Exception x)
                    {
                        //await AuditService.EditContentAndUserAsync(AuditId, AuditContentType.Activity,
                        //        AuditMessages.Failure.ToString(), user.Id, user.UserName);

                        Log.Error("Error creating person with ESign", x);
                        IdentityResult deleteResult = await _userManager.DeleteAsync(user);

                        returnUrl += $"?error=true";
                        return(Redirect(returnUrl));
                    }
                }

                Log.Error("Error parsing certificate" + String.Join(", ", parseResult.Errors));
                returnUrl += $"?error=true";
                return(Redirect(returnUrl));
            }
            catch (Exception x)
            {
                //cannot parse certificate
                Log.Error(x, "Error parsing certificate on register");
                returnUrl += $"?error=true";
                return(Redirect(returnUrl));
            }
        }