<commit_before>﻿// <copyright file="RegisterRoute.cs" company="Stormpath, Inc.">
// Copyright (c) 2016 Stormpath, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Stormpath.Owin.Abstractions;
using Stormpath.Owin.Abstractions.ViewModel;
using Stormpath.Owin.Middleware.Internal;
using Stormpath.Owin.Middleware.Model;
using Stormpath.Owin.Middleware.Model.Error;
using Stormpath.SDK.Account;
using Stormpath.SDK.Client;
using Stormpath.SDK.Directory;
using Stormpath.SDK.Error;

namespace Stormpath.Owin.Middleware.Route
{
    public sealed class RegisterRoute : AbstractRoute
    {
        private static readonly string[] defaultFields = Configuration.Abstractions.Default.Configuration.Web.Register.Form.Fields.Select(kvp => kvp.Key).ToArray();

        private async Task<IAccount> HandleRegistration(
            IOwinEnvironment environment,
            RegisterPostModel postData,
            IEnumerable<string> fieldNames,
            Dictionary<string, object> customFields,
            IClient client,
            Func<string, CancellationToken, Task> errorHandler,
            Func<PreRegistrationContext, CancellationToken, Task> preRegistrationHandler,
            Func<PostRegistrationContext, CancellationToken, Task> postRegistrationHandler,
            CancellationToken cancellationToken)
        {
            var viewModel = new RegisterViewModelBuilder(_configuration.Web.Register).Build();
            var suppliedFieldNames = fieldNames?.ToArray() ?? new string[] {};

            bool missingEmailOrPassword = string.IsNullOrEmpty(postData.Email) || string.IsNullOrEmpty(postData.Password);
            if (missingEmailOrPassword)
            {
                await errorHandler("Missing email or password.", cancellationToken);
                return null;
            }

            bool hasConfirmPasswordField = viewModel.Form.Fields.Where(f => f.Name == "confirmPassword").Any();
            if (hasConfirmPasswordField)
            {
                if (postData.Password != postData.ConfirmPassword)
                {
                    await errorHandler($"Passwords do not match.", cancellationToken);
                    return null;
                }
            }

            foreach (var field in viewModel.Form.Fields)
            {
                if (field.Required && !suppliedFieldNames.Contains(field.Name, StringComparer.Ordinal))
                {
                    await errorHandler($"{field.Label} is missing.", cancellationToken);
                    return null;
                }
            }

            var givenNameField = viewModel.Form.Fields.Where(f => f.Name == "givenName").SingleOrDefault();
            bool isGivenNameRequired = givenNameField?.Required ?? false;
            if (string.IsNullOrEmpty(postData.GivenName) && !isGivenNameRequired)
            {
                postData.GivenName = "UNKNOWN";
            }

            var surnameField = viewModel.Form.Fields.Where(f => f.Name == "surname").SingleOrDefault();
            bool isSurnameRequired = surnameField?.Required ?? false;
            if (string.IsNullOrEmpty(postData.Surname) && !isSurnameRequired)
            {
                postData.Surname = "UNKNOWN";
            }

            var enabledFields = viewModel.Form.Fields.Select(f => f.Name);

            var undefinedFields = suppliedFieldNames
                .Concat(customFields.Select(f => f.Key))
                .Except(enabledFields);
            if (undefinedFields.Any())
            {
                await errorHandler($"Unknown field '{undefinedFields.First()}'.", cancellationToken);<commit_msg>Simply code and pass TCK<commit_after>﻿// <copyright file="RegisterRoute.cs" company="Stormpath, Inc.">
// Copyright (c) 2016 Stormpath, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Stormpath.Owin.Abstractions;
using Stormpath.Owin.Abstractions.ViewModel;
using Stormpath.Owin.Middleware.Internal;
using Stormpath.Owin.Middleware.Model;
using Stormpath.Owin.Middleware.Model.Error;
using Stormpath.SDK.Account;
using Stormpath.SDK.Client;
using Stormpath.SDK.Directory;
using Stormpath.SDK.Error;

namespace Stormpath.Owin.Middleware.Route
{
    public sealed class RegisterRoute : AbstractRoute
    {
        private static readonly string[] defaultFields = Configuration.Abstractions.Default.Configuration.Web.Register.Form.Fields.Select(kvp => kvp.Key).ToArray();

        private async Task<IAccount> HandleRegistration(
            IOwinEnvironment environment,
            RegisterPostModel postData,
            IEnumerable<string> fieldNames,
            Dictionary<string, object> customFields,
            IClient client,
            Func<string, CancellationToken, Task> errorHandler,
            Func<PreRegistrationContext, CancellationToken, Task> preRegistrationHandler,
            Func<PostRegistrationContext, CancellationToken, Task> postRegistrationHandler,
            CancellationToken cancellationToken)
        {
            var viewModel = new RegisterViewModelBuilder(_configuration.Web.Register).Build();
            var suppliedFieldNames = fieldNames?.ToArray() ?? new string[] {};

            bool hasConfirmPasswordField = viewModel.Form.Fields.Where(f => f.Name == "confirmPassword").Any();
            if (hasConfirmPasswordField)
            {
                if (postData.Password != postData.ConfirmPassword)
                {
                    await errorHandler($"Passwords do not match.", cancellationToken);
                    return null;
                }
            }

            foreach (var field in viewModel.Form.Fields)
            {
                if (field.Required && !suppliedFieldNames.Contains(field.Name, StringComparer.Ordinal))
                {
                    await errorHandler($"{field.Label} is required.", cancellationToken);
                    return null;
                }
            }

            var givenNameField = viewModel.Form.Fields.Where(f => f.Name == "givenName").SingleOrDefault();
            bool isGivenNameRequired = givenNameField?.Required ?? false;
            if (string.IsNullOrEmpty(postData.GivenName) && !isGivenNameRequired)
            {
                postData.GivenName = "UNKNOWN";
            }

            var surnameField = viewModel.Form.Fields.Where(f => f.Name == "surname").SingleOrDefault();
            bool isSurnameRequired = surnameField?.Required ?? false;
            if (string.IsNullOrEmpty(postData.Surname) && !isSurnameRequired)
            {
                postData.Surname = "UNKNOWN";
            }

            var enabledFields = viewModel.Form.Fields.Select(f => f.Name);

            var undefinedFields = suppliedFieldNames
                .Concat(customFields.Select(f => f.Key))
                .Except(enabledFields);
            if (undefinedFields.Any())
            {
                await errorHandler($"Unknown field '{undefinedFields.First()}'.", cancellationToken);
{'fraction_non_alphanumeric': 0.0972356935014549, 'fraction_numerical': 0.0019398642095053346, 'mean_word_length': 2.482059940903335, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1366101', 'n_tokens_mistral': 2063, 'n_tokens_neox': 2012, 'n_words': 513}