/**
         * Close user account.
         */
        internal static async Task CloseUserAccount(AmazonDynamoDBClient dbClient, string userId)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(userId);

            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, userId);

            Debug.AssertValidOrNull(user);
            if (user != null)
            {
                // User exists
                Debug.Tested();
                Debug.AssertNull(user.Deleted);
                if (user.Closed == null)
                {
                    // User account is not already closed
                    Debug.Tested();
                    user.Closed = DateTime.Now;
                    await IdentityServiceLogicLayer.InvalidateUserAccessTokens(dbClient, userId);
                }
                else
                {
                    // User account is already closed
                    Debug.Untested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_USER_ACCOUNT_CLOSED);
                }
            }
            else
            {
                // User does not exist (or is soft deleted)
                Debug.Tested();
                throw new Exception(IdentityServiceLogicLayer.ERROR_USER_NOT_FOUND);
            }
        }
        /**
         * Set user phone number.
         */
        public static async Task SetUserPhoneNumber(AmazonDynamoDBClient dbClient, string loggedInUserId, SetUserPhoneNumberRequest setUserPhoneNumberRequest)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(setUserPhoneNumberRequest);
            Debug.AssertString(setUserPhoneNumberRequest.phoneNumber);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);

            // Make changes (if necessary)
            if (user.PhoneNumber != setUserPhoneNumberRequest.phoneNumber)
            {
                // Set the new phone number
                user.PhoneNumber = setUserPhoneNumberRequest.phoneNumber;

                // Mark it as not verified
                user.PhoneNumberVerified = null;

                // Save the user
                await IdentityServiceDataLayer.SaveUser(dbClient, user);

                // Send the OTP via SMS
                string oneTimePassword = "******";//??++GENERATE OTP
                Link   link            = await IdentityServiceLogicLayer.CreateLink(dbClient, IdentityServiceLogicLayer.LINK_TYPE_VERIFY_PHONE_NUMBER, loggedInUserId, oneTimePassword);

                Debug.AssertValid(link);
                //??++SMS OTP
                LoggingHelper.LogMessage($"PHONE NUMBER VERIFICATION LINK ID: {link.ID}");
            }
        }
コード例 #3
0
        /**
         * Check password.
         */
        public static async Task CheckPassword(AmazonDynamoDBClient dbClient, CheckPasswordRequest checkPasswordRequest, string loggedInUserId)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(checkPasswordRequest);
            Debug.AssertString(checkPasswordRequest.password);
            Debug.AssertID(loggedInUserId);

            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);
            if (user.Locked)
            {
                // The user is locked.
                // This code should never be called as locked users cannot login.
                Debug.Unreachable();
                throw new Exception(IdentityServiceLogicLayer.ERROR_USER_LOCKED);
            }
            else if (user.Blocked)
            {
                // The user is blocked.
                // This code should never be called as blocked users cannot login.
                Debug.Unreachable();
                throw new Exception(IdentityServiceLogicLayer.ERROR_USER_BLOCKED);
            }
            else if (user.PasswordHash != Helper.Hash(checkPasswordRequest.password))
            {
                Debug.Tested();
                throw new Exception(IdentityServiceLogicLayer.ERROR_INCORRECT_PASSWORD);
            }
            else
            {
                Debug.Tested();
            }
        }
        /**
         * Set user permissions.
         */
        internal static async Task SetUserPermissions(AmazonDynamoDBClient dbClient, string userId, JToken requestBody)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(userId);
            Debug.AssertValid(requestBody);
            Debug.AssertValid((JArray)requestBody["permissions"]);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, userId);

            Debug.AssertValidOrNull(user);
            if (user != null)
            {
                Debug.Untested();
                Debug.AssertValid(user.Permissions);

                // Change the permissions
                //??--user.Permissions.RemoveAll(permission => (permission.Item1 == userId));
                user.Permissions.Clear();
                foreach (var permission in (JArray)requestBody["permissions"])
                {
                    Debug.AssertString((string)permission);
                    user.Permissions.Add((string)permission);//??--new Tuple<string, string>(userId, (string)permission));
                }
                // Save the user
                await IdentityServiceDataLayer.SaveUser(dbClient, user);
            }
            else
            {
                Debug.Untested();
                throw new Exception(IdentityServiceLogicLayer.ERROR_USER_NOT_FOUND);
            }
        }
        /**
         * Set user password.
         */
        public static async Task SetUserPassword(AmazonDynamoDBClient dbClient, string loggedInUserId, SetUserPasswordRequest setUserPasswordRequest)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(setUserPasswordRequest);
            Debug.AssertString(setUserPasswordRequest.oldPassword);
            Debug.AssertString(setUserPasswordRequest.newPassword);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);

            // Check password
            if (user.PasswordHash == Helper.Hash(setUserPasswordRequest.oldPassword))
            {
                // Make changes (if necessary)
                string newPasswordHash = Helper.Hash(setUserPasswordRequest.newPassword);
                if (user.PasswordHash != newPasswordHash)
                {
                    user.PasswordHash = newPasswordHash;

                    // Save the user
                    await IdentityServiceDataLayer.SaveUser(dbClient, user);
                }
            }
            else
            {
                throw new Exception(IdentityServiceLogicLayer.ERROR_INCORRECT_PASSWORD);
            }
        }
        /**
         * Close account.
         */
        public static async Task CloseAccount(AmazonDynamoDBClient dbClient, string loggedInUserId, CloseAccountRequest closeAccountRequest)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(closeAccountRequest);
            Debug.AssertString(closeAccountRequest.password);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);
            Debug.AssertNull(user.Closed);

            // Check the password
            if (user.PasswordHash == Helper.Hash(closeAccountRequest.password))
            {
                // Make changes
                user.Closed = DateTime.Now;

                // Save the user
                await IdentityServiceDataLayer.SaveUser(dbClient, user);

                // Actually log user out
                await IdentityServiceLogicLayer.InvalidateUserAccessTokens(dbClient, loggedInUserId);
            }
            else
            {
                Debug.Untested();
                throw new Exception(IdentityServiceLogicLayer.ERROR_INCORRECT_PASSWORD);
            }
        }
コード例 #7
0
        /**
         * Resend email verification.
         */
        private static async Task DoResendEmailVerification(AmazonDynamoDBClient dbClient, User user)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(user);
            Debug.AssertEmail(user.EmailAddress);

            // Revoke existing link(s)
            await IdentityServiceLogicLayer.RevokeUserLinks(dbClient, user.ID, IdentityServiceLogicLayer.LINK_TYPE_VERIFY_EMAIL_ADDRESS);

            // Create a new link
            Link link = await IdentityServiceLogicLayer.CreateLink(dbClient, IdentityServiceLogicLayer.LINK_TYPE_VERIFY_EMAIL_ADDRESS, user.ID);

            Debug.AssertValid(link);
            Debug.AssertString(link.ID);

            // Email the new link
            Dictionary <string, string> replacementFields = new Dictionary <string, string>();

            replacementFields["link"] = link.ID;
            EmailHelper.EmailTemplate(EmailHelper.EMAIL_TEMPLATE_EMAIL_VERIFICATION, user.EmailAddress, replacementFields);

            // Debug code
            //??--IdentityServiceLogicLayer.VerifyEmailLinkId = link.ID;
            LoggingHelper.LogMessage($"EMAIL VERIFICATION LINK ID: {link.ID}");
        }
コード例 #8
0
        /**
         * Set user preferences.
         */
        public static async Task SetUserPreferences(AmazonDynamoDBClient dbClient, string loggedInUserId, SetUserPreferencesRequest setUserPreferencesRequest)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(setUserPreferencesRequest);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);

            // Make changes (if necessary)
            if ((user.PreferredLanguage != setUserPreferencesRequest.preferredLanguage) ||
                (user.PreferredCurrency != setUserPreferencesRequest.preferredCurrency) ||
                (user.PreferredTimeZone != setUserPreferencesRequest.preferredTimeZone))
            {
                user.PreferredLanguage = setUserPreferencesRequest.preferredLanguage;
                user.PreferredCurrency = setUserPreferencesRequest.preferredCurrency;
                user.PreferredTimeZone = setUserPreferencesRequest.preferredTimeZone;

                // Save the user
                await IdentityServiceDataLayer.SaveUser(dbClient, user);
            }
        }
        /**
         * Set user name.
         */
        public static async Task SetUserName(AmazonDynamoDBClient dbClient, string loggedInUserId, SetUserNameRequest setUserNameRequest)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(setUserNameRequest);
            Debug.AssertString(setUserNameRequest.givenName);
            Debug.AssertString(setUserNameRequest.familyName);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);

            // Make changes (if necessary)
            if ((user.GivenName != setUserNameRequest.givenName) ||
                (user.FamilyName != setUserNameRequest.familyName) ||
                (user.FullName != setUserNameRequest.fullName) ||
                (user.PreferredName != setUserNameRequest.preferredName))
            {
                user.GivenName     = setUserNameRequest.givenName;
                user.FamilyName    = setUserNameRequest.familyName;
                user.FullName      = setUserNameRequest.fullName;
                user.PreferredName = setUserNameRequest.preferredName;

                // Save the user
                await IdentityServiceDataLayer.SaveUser(dbClient, user);
            }
        }
        /**
         * Set user limits.
         */
        public static async Task SetUserLimits(AmazonDynamoDBClient dbClient, string loggedInUserId, SetUserLimitsRequest setUserLimitsRequest)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(setUserLimitsRequest);

            if ((setUserLimitsRequest.maxDailySpendingAmount != null) ||
                (setUserLimitsRequest.maxTimeLoggedIn != null) ||
                (setUserLimitsRequest.excludeUntil != null))
            {
                // At least one of the limits may be being changed
                Debug.Tested();

                // Load the user
                User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

                Debug.AssertValid(user);

                // Make changes
                SetUserMaxDailySpendingAmount(user, setUserLimitsRequest);
                SetUserMaxTimeLoggedIn(user, setUserLimitsRequest);
                SetUserExcludeUntil(user, setUserLimitsRequest);

                // Save the user
                await IdentityServiceDataLayer.SaveUser(dbClient, user);
            }
            else
            {
                Debug.Tested();
            }
        }
        /**
         * Update system locked global setting.
         */
        internal static async Task UpdateSystemLockedGlobalSetting(AmazonDynamoDBClient dbClient,
                                                                   string loggedInUserId,
                                                                   bool value,
                                                                   bool force = false)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertIDOrNull(loggedInUserId);

            // Setting 'system locked' flag.
            if (value)
            {
                // Setting to true (allowed)
                Debug.Tested();
                User loggedInUser = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

                Debug.AssertValidOrNull(loggedInUser);
                if (IdentityServiceLogicLayer.UserHasPermission(loggedInUser, IdentityServiceLogicLayer.PERMISSION_CAN_LOCK_SYSTEM))
                {
                    Debug.Tested();
                    //??--if (!IdentityGlobalSettings.ContainsKey(GLOBAL_SETTING_SYSTEM_LOCKED) || !(bool)IdentityGlobalSettings[GLOBAL_SETTING_SYSTEM_LOCKED])
                    bool systemLocked = await IdentityServiceLogicLayer.GetBoolIdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_SYSTEM_LOCKED, false);

                    if (!systemLocked)
                    {
                        Debug.Tested();
                        //??--IdentityGlobalSettings[GLOBAL_SETTING_SYSTEM_LOCKED] = value;
                        await IdentityServiceDataLayer.AddIdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_SYSTEM_LOCKED, value.ToString());
                    }
                    else
                    {
                        Debug.Tested();
                        throw new Exception(SharedLogicLayer.ERROR_SYSTEM_ALREADY_LOCKED);
                    }
                }
                else
                {
                    Debug.Tested();
                    throw new Exception(SharedLogicLayer.ERROR_NO_PERMISSION);
                }
            }
            else if (force)
            {
                // Forcing the set to false.
                Debug.Tested();
                //??--IdentityGlobalSettings[GLOBAL_SETTING_SYSTEM_LOCKED] = value;
                await IdentityServiceDataLayer.AddIdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_SYSTEM_LOCKED, value.ToString());
            }
            else
            {
                // Setting to false (not allowed)
                Debug.Untested();
                throw new Exception(SharedLogicLayer.ERROR_NO_PERMISSION);
            }
        }
        /**
         * Get full user details.
         * This includes closed (but not deleted) users.
         */
        internal static async Task <User> GetFullUserDetails(AmazonDynamoDBClient dbClient, string userId)
        {
            Debug.Untested();
            Debug.AssertID(userId);

            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, userId, false);

            Debug.AssertValidOrNull(user);
            if (user != null)
            {
                Debug.Tested();
                return(user);
            }
            else
            {
                Debug.Tested();
                throw new Exception(IdentityServiceLogicLayer.ERROR_USER_NOT_FOUND);
            }
            //??? GetUserDetailsResponse retVal = new GetUserDetailsResponse() {
            //     emailAddress = user.EmailAddress,
            //     givenName = user.GivenName,
            //     familyName = user.FamilyName,
            //     preferredName = user.PreferredName,
            //     fullName = user.FullName,
            //     dateOfBirth = APIHelper.APIDateStringFromDate(user.DateOfBirth),
            //     gender = user.Gender,
            //     address1 = user.Address1,
            //     address2 = user.Address2,
            //     address3 = user.Address3,
            //     address4 = user.Address4,
            //     city = user.City,
            //     region = user.Region,
            //     country = user.Country,
            //     postalCode = user.PostalCode,
            //     phoneNumber = user.PhoneNumber,
            //     phoneNumberVerified = APIHelper.APIDateTimeStringFromDateTime(user.PhoneNumberVerified),
            //     newEmailAddress = user.NewEmailAddress,
            //     allowNonEssentialEmails = user.AllowNonEssentialEmails,
            //     totalTicketsPurchased = user.TotalTicketsPurchased,
            //     ticketsPurchasedInCurrentGame = user.TicketsPurchasedInCurrentGame,
            //     preferredLanguage = user.PreferredLanguage,
            //     preferredCurrency = user.PreferredCurrency,
            //     preferredTimeZone = user.PreferredTimeZone,
            //     maxDailySpendingAmount = user.MaxDailySpendingAmount,
            //     newMaxDailySpendingAmount = user.NewMaxDailySpendingAmount,
            //     newMaxDailySpendingAmountTime = APIHelper.APIDateTimeStringFromDateTime(user.NewMaxDailySpendingAmountTime),
            //     maxTimeLoggedIn = user.MaxTimeLoggedIn,
            //     newMaxTimeLoggedIn = user.NewMaxTimeLoggedIn,
            //     newMaxTimeLoggedInTime = APIHelper.APIDateTimeStringFromDateTime(user.NewMaxTimeLoggedInTime),
            //     excludeUntil = APIHelper.APIDateTimeStringFromDateTime(user.ExcludeUntil),
            //     newExcludeUntil = APIHelper.APIDateTimeStringFromDateTime(user.NewExcludeUntil),
            //     newExcludeUntilTime = APIHelper.APIDateTimeStringFromDateTime(user.NewExcludeUntilTime)
            // };
        }
        /**
         * Verify phone number.
         */
        public static async Task VerifyPhoneNumber(AmazonDynamoDBClient dbClient, string loggedInUserId, VerifyPhoneNumberRequest verifyPhoneNumberRequest)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(verifyPhoneNumberRequest);
            Debug.AssertString(verifyPhoneNumberRequest.oneTimePassword);

            // Find valid link
            Link link = await FindValidLinkByUserID(dbClient, loggedInUserId, IdentityServiceLogicLayer.LINK_TYPE_VERIFY_PHONE_NUMBER);

            Debug.AssertValidOrNull(link);
            if (link != null)
            {
                // Valid link exists
                Debug.Tested();
                Debug.AssertString(link.OneTimePassword);
                if (link.OneTimePassword == verifyPhoneNumberRequest.oneTimePassword)
                {
                    // One-time password matches
                    Debug.Tested();

                    // Load the user
                    User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

                    Debug.AssertValid(user);
                    Debug.AssertValidOrNull(user.PhoneNumberVerified);
                    if (user.PhoneNumberVerified == null)
                    {
                        // User's phone number not verified
                        Debug.Untested();

                        // Change the user and revoke the link
                        await DoVerifyPhoneNumber(dbClient, user, link);
                    }
                    else
                    {
                        Debug.Untested();
                        throw new Exception(IdentityServiceLogicLayer.ERROR_PHONE_NUMBER_VERIFIED, new Exception(IdentityServiceLogicLayer.PHONE_NUMBER_VERIFIED));
                    }
                }
                else
                {
                    Debug.Tested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_INCORRECT_PASSWORD, new Exception(IdentityServiceLogicLayer.INCORRECT_PASSWORD));
                }
            }
            else
            {
                Debug.Tested();
                throw new Exception(SharedLogicLayer.ERROR_INVALID_LINK, new Exception(SharedLogicLayer.ERROR_INVALID_LINK));
            }
        }
コード例 #14
0
        /**
         * Refresh access token.
         * The specified user ID must exist.
         */
        public static async Task <DateTime?> RefreshAccessToken(AmazonDynamoDBClient dbClient, string loggedInUserId)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);

            DateTime?   retVal      = null;
            AccessToken accessToken = await IdentityServiceLogicLayer.FindAccessTokenByUserID(dbClient, loggedInUserId);

            Debug.AssertValidOrNull(accessToken);
            if (accessToken != null)
            {
                //??--Int64 accessTokenLifetime = (Int64)GetIdentityGlobalSetting(GLOBAL_SETTING_ACCESS_TOKEN_LIFETIME, DEFAULT_ACCESS_TOKEN_LIFETIME);
                Int64 accessTokenLifetime = await IdentityServiceLogicLayer.GetInt64IdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_ACCESS_TOKEN_LIFETIME, IdentityServiceLogicLayer.DEFAULT_ACCESS_TOKEN_LIFETIME);

                if (accessToken.MaxExpiry == null)
                {
                    accessToken.Expires = DateTime.Now.AddSeconds(accessTokenLifetime);
                }
                else
                {
                    if (accessToken.Expires == accessToken.MaxExpiry)
                    {
                        throw new Exception(IdentityServiceLogicLayer.ERROR_CANNOT_EXTEND_ACCESS_TOKEN);
                    }
                    else
                    {
                        // Extend the expiry time.
                        accessToken.Expires = DateTime.Now.AddSeconds(accessTokenLifetime);
                        // Ensure the max expiry has not been exceeded
                        if (accessToken.Expires > accessToken.MaxExpiry)
                        {
                            Debug.Untested();
                            accessToken.Expires = (DateTime)accessToken.MaxExpiry;
                        }
                        else
                        {
                            Debug.Untested();
                        }
                    }
                }
                retVal = accessToken.Expires;
            }
            else
            {
                Debug.Untested();
            }
            return(retVal);
        }
コード例 #15
0
        /**
         * Get user details.
         */
        public static async Task <GetUserDetailsResponse> GetUserDetails(AmazonDynamoDBClient dbClient, string loggedInUserId)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);

            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);
            GetUserDetailsResponse retVal = new GetUserDetailsResponse()
            {
                emailAddress                  = user.EmailAddress,
                givenName                     = user.GivenName,
                familyName                    = user.FamilyName,
                preferredName                 = user.PreferredName,
                fullName                      = user.FullName,
                dateOfBirth                   = APIHelper.APIDateStringFromDate(user.DateOfBirth),
                gender                        = user.Gender,
                address1                      = user.Address1,
                address2                      = user.Address2,
                address3                      = user.Address3,
                address4                      = user.Address4,
                city                          = user.City,
                region                        = user.Region,
                country                       = user.Country,
                postalCode                    = user.PostalCode,
                phoneNumber                   = user.PhoneNumber,
                phoneNumberVerified           = APIHelper.APIDateTimeStringFromDateTime(user.PhoneNumberVerified),
                newEmailAddress               = user.NewEmailAddress,
                allowNonEssentialEmails       = user.AllowNonEssentialEmails,
                totalTicketsPurchased         = user.TotalTicketsPurchased,
                ticketsPurchasedInCurrentGame = user.TicketsPurchasedInCurrentGame,
                preferredLanguage             = user.PreferredLanguage,
                preferredCurrency             = user.PreferredCurrency,
                preferredTimeZone             = user.PreferredTimeZone,
                maxDailySpendingAmount        = user.MaxDailySpendingAmount,
                newMaxDailySpendingAmount     = user.NewMaxDailySpendingAmount,
                newMaxDailySpendingAmountTime = APIHelper.APIDateTimeStringFromDateTime(user.NewMaxDailySpendingAmountTime),
                maxTimeLoggedIn               = user.MaxTimeLoggedIn,
                newMaxTimeLoggedIn            = user.NewMaxTimeLoggedIn,
                newMaxTimeLoggedInTime        = APIHelper.APIDateTimeStringFromDateTime(user.NewMaxTimeLoggedInTime),
                excludeUntil                  = APIHelper.APIDateTimeStringFromDateTime(user.ExcludeUntil),
                newExcludeUntil               = APIHelper.APIDateTimeStringFromDateTime(user.NewExcludeUntil),
                newExcludeUntilTime           = APIHelper.APIDateTimeStringFromDateTime(user.NewExcludeUntilTime)
            };

            return(retVal);
        }
        /**
         * Resend phone number verification.
         */
        public static async Task ResendPhoneNumberVerification(AmazonDynamoDBClient dbClient, string loggedInUserId)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);//??++CHECK HARE AND ELSEWHERE FOR NULL - COULD PASS IN USER?
            Debug.AssertStringOrNull(user.PhoneNumber);
            Debug.AssertValidOrNull(user.PhoneNumberVerified);
            if (!string.IsNullOrEmpty(user.PhoneNumber))
            {
                // User's phone number exists
                Debug.Tested();
                if (user.PhoneNumberVerified == null)
                {
                    // User's phone number not verified
                    Debug.Tested();

                    // Revoke all 'verify phone number' links
                    await IdentityServiceLogicLayer.RevokeUserLinks(dbClient, loggedInUserId, IdentityServiceLogicLayer.LINK_TYPE_VERIFY_PHONE_NUMBER);

                    // Create and send new 'verify phone number' link
                    string oneTimePassword = "******";//??++GENERATE OTP
                    Link   link            = await IdentityServiceLogicLayer.CreateLink(dbClient, IdentityServiceLogicLayer.LINK_TYPE_VERIFY_PHONE_NUMBER, loggedInUserId, oneTimePassword);

                    Debug.AssertValid(link);
                    //??++SMS OTP
                    LoggingHelper.LogMessage($"PHONE NUMBER VERIFICATION LINK ID: {link.ID}");
                }
                else
                {
                    Debug.Untested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_PHONE_NUMBER_VERIFIED, new Exception(IdentityServiceLogicLayer.PHONE_NUMBER_VERIFIED));
                }
            }
            else
            {
                Debug.Tested();
                throw new Exception(IdentityServiceLogicLayer.ERROR_NO_PHONE_NUMBER_SET, new Exception(IdentityServiceLogicLayer.NO_PHONE_NUMBER_SET));
            }
        }
        /**
         * Logout.
         */
        public static async Task Logout(AmazonDynamoDBClient dbClient, string loggedInUserId)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);

            // Make changes
            user.LastLoggedOut = DateTime.Now;

            // Save the user
            await IdentityServiceDataLayer.SaveUser(dbClient, user);

            //
            await IdentityServiceLogicLayer.InvalidateUserAccessTokens(dbClient, loggedInUserId);
        }
コード例 #18
0
        /**
         * Set user gender.
         */
        public static async Task SetUserGender(AmazonDynamoDBClient dbClient, string loggedInUserId, SetUserGenderRequest setUserGenderRequest)
        {
            Debug.Tested();
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(setUserGenderRequest);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);

            // Make changes (if necessary)
            if (user.Gender != setUserGenderRequest.gender)
            {
                user.Gender = setUserGenderRequest.gender;

                // Save the user
                await IdentityServiceDataLayer.SaveUser(dbClient, user);
            }
        }
コード例 #19
0
        /**
         * Set user allow non-essential emails.
         */
        public static async Task SetUserAllowNonEssentialEmails(AmazonDynamoDBClient dbClient, string loggedInUserId, SetUserAllowNonEssentialEmailsRequest setUserAllowNonEssentialEmailsRequest)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(setUserAllowNonEssentialEmailsRequest);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);

            // Make changes (if necessary)
            if (user.AllowNonEssentialEmails != setUserAllowNonEssentialEmailsRequest.allowNonEssentialEmails)
            {
                user.AllowNonEssentialEmails = setUserAllowNonEssentialEmailsRequest.allowNonEssentialEmails;

                // Save the user
                await IdentityServiceDataLayer.SaveUser(dbClient, user);
            }
        }
        /**
         * Set user password.
         */
        internal static async Task SetUserPasswordDirect(AmazonDynamoDBClient dbClient, string userId, JToken requestBody)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(userId);
            Debug.AssertValid(requestBody);
            Debug.AssertString((string)requestBody["password"]);

            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, userId);

            Debug.AssertValidOrNull(user);
            if (user != null)
            {
                Debug.Tested();
                user.PasswordHash = Helper.Hash((string)requestBody["password"]);
            }
            else
            {
                Debug.Tested();
                throw new Exception(IdentityServiceLogicLayer.ERROR_USER_NOT_FOUND);
            }
        }
コード例 #21
0
        /**
         * Set user address.
         */
        public static async Task SetUserAddress(AmazonDynamoDBClient dbClient, string loggedInUserId, SetUserAddressRequest setUserAddressRequest)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(setUserAddressRequest);
            Debug.AssertString(setUserAddressRequest.address1);
            Debug.AssertString(setUserAddressRequest.country);
            Debug.AssertString(setUserAddressRequest.postalCode);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, loggedInUserId);

            Debug.AssertValid(user);

            // Make changes (if necessary)
            if ((user.Address1 != setUserAddressRequest.address1) ||
                (user.Address2 != setUserAddressRequest.address2) ||
                (user.Address3 != setUserAddressRequest.address3) ||
                (user.Address4 != setUserAddressRequest.address4) ||
                (user.City != setUserAddressRequest.city) ||
                (user.Region != setUserAddressRequest.region) ||
                (user.Country != setUserAddressRequest.country) ||
                (user.PostalCode != setUserAddressRequest.postalCode))
            {
                user.Address1   = setUserAddressRequest.address1;
                user.Address2   = setUserAddressRequest.address2;
                user.Address3   = setUserAddressRequest.address3;
                user.Address4   = setUserAddressRequest.address4;
                user.City       = setUserAddressRequest.city;
                user.Region     = setUserAddressRequest.region;
                user.Country    = setUserAddressRequest.country;
                user.PostalCode = setUserAddressRequest.postalCode;

                // Save the user
                await IdentityServiceDataLayer.SaveUser(dbClient, user);
            }
        }
        /**
         * Get user permissions.
         */
        public static async Task <string[]> GetUserPermissions(AmazonDynamoDBClient dbClient, string userId)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(userId);

            // Load the user
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, userId);

            Debug.AssertValidOrNull(user);
            if (user != null)
            {
                // User exists (account may be open or closed)
                Debug.Tested();
                Debug.AssertValid(user.Permissions);
                //??-- List<string> permissions = new List<string>();
                // foreach (var permission in Permissions) {
                //     Debug.Tested();
                //     Debug.AssertValid(permission);
                //     Debug.AssertID(permission.Item1);
                //     Debug.AssertString(permission.Item2);
                //     if (permission.Item1 == userId) {
                //         Debug.Tested();
                //         permissions.Add(permission.Item2);
                //     } else {
                //         Debug.Tested();
                //     }
                // }
                return(user.Permissions.ToArray());
            }
            else
            {
                // User does not exist (or is soft deleted)
                Debug.Tested();
                throw new Exception(IdentityServiceLogicLayer.ERROR_USER_NOT_FOUND);
            }
        }
        /**
         * Verify email with details.
         */
        public static async Task VerifyEmailWithDetails(AmazonDynamoDBClient dbClient, VerifyEmailWithDetailsRequest verifyEmailWithDetailsRequest)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(verifyEmailWithDetailsRequest);
            Debug.AssertString(verifyEmailWithDetailsRequest.verifyEmailLinkId);
            Debug.AssertEmail(verifyEmailWithDetailsRequest.emailAddress);

            // Find a valid link
            Link link = await IdentityServiceLogicLayer.FindValidLink(dbClient, verifyEmailWithDetailsRequest.verifyEmailLinkId, IdentityServiceLogicLayer.LINK_TYPE_VERIFY_EMAIL_ADDRESS);

            Debug.AssertValidOrNull(link);
            if (link != null)
            {
                // Valid link exits
                Debug.Tested();
                Debug.AssertID(link.UserID);

                // Find user
                User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, link.UserID);

                Debug.AssertValidOrNull(user);
                if (user != null)
                {
                    // User exists
                    Debug.Untested();
                    Debug.AssertEmail(user.EmailAddress);
                    Debug.AssertValidOrNull(user.EmailAddressVerified);

                    if (user.EmailAddressVerified == null)
                    {
                        // Email address not verified
                        Debug.Untested();

                        if (user.EmailAddress == verifyEmailWithDetailsRequest.emailAddress)
                        {
                            // Verifying correct email address
                            Debug.Untested();

                            // Change user and revoke link
                            await DoVerifyEmailWithDetails(dbClient, user, link, verifyEmailWithDetailsRequest);
                        }
                        else
                        {
                            Debug.Tested();
                            throw new Exception(SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS, new Exception(SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS));
                        }
                    }
                    else
                    {
                        Debug.Untested();
                        throw new Exception(IdentityServiceLogicLayer.ERROR_EMAIL_ALREADY_VERIFIED, new Exception(IdentityServiceLogicLayer.EMAIL_ALREADY_VERIFIED));
                    }
                }
                else
                {
                    // User does not exist (may have been deleted)
                    Debug.Untested();
                    throw new Exception(SharedLogicLayer.ERROR_INVALID_LINK_USER, new Exception(SharedLogicLayer.ERROR_INVALID_LINK_USER));
                }
            }
            else
            {
                Debug.Tested();
                throw new Exception(SharedLogicLayer.ERROR_INVALID_LINK, new Exception(SharedLogicLayer.ERROR_INVALID_LINK));
            }
        }
        /**
         * Verify email.
         * ??++BREAK INTO SMALLER METHODS
         */
        public static async Task VerifyEmail(AmazonDynamoDBClient dbClient, VerifyEmailRequest verifyEmailRequest)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(verifyEmailRequest);
            Debug.AssertEmail(verifyEmailRequest.emailAddress);
            Debug.AssertString(verifyEmailRequest.verifyEmailLinkId);

            // Find a valid link
            Link link = await IdentityServiceLogicLayer.FindValidLink(dbClient, verifyEmailRequest.verifyEmailLinkId, IdentityServiceLogicLayer.LINK_TYPE_VERIFY_EMAIL_ADDRESS);

            Debug.AssertValidOrNull(link);
            if (link != null)
            {
                // Valid link exits
                Debug.Tested();
                Debug.AssertID(link.UserID);

                // Find user
                User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, link.UserID, true);

                Debug.AssertValidOrNull(user);
                if (user != null)
                {
                    // User exists
                    Debug.Tested();
                    Debug.AssertEmail(user.EmailAddress);
                    Debug.AssertValidOrNull(user.EmailAddressVerified);
                    if (user.NewEmailAddress == verifyEmailRequest.emailAddress)
                    {
                        // Verifying new email address
                        Debug.Tested();

                        // Make changes to the user
                        user.EmailAddress         = verifyEmailRequest.emailAddress;
                        user.NewEmailAddress      = null;
                        user.EmailAddressVerified = DateTime.Now;

                        // Save the user
                        await IdentityServiceDataLayer.SaveUser(dbClient, user);

                        // Revoke the link
                        link.Revoked = true;
                        //??++SAVE LINK
                    }
                    else
                    {
                        // Possibly verifying main email address
                        Debug.Tested();
                        if (user.EmailAddressVerified == null)
                        {
                            // Main email address not verified
                            Debug.Tested();
                            if (user.EmailAddress == verifyEmailRequest.emailAddress)
                            {
                                // Verifying main email address
                                Debug.Tested();
                                Debug.AssertNull(user.NewEmailAddress);

                                // Make changes to the user
                                user.EmailAddressVerified = DateTime.Now;

                                // Save the user
                                await IdentityServiceDataLayer.SaveUser(dbClient, user);

                                // Revoke the link
                                link.Revoked = true;
                                //??++SAVE LINK
                            }
                            else
                            {
                                // Verifying wrong email address
                                Debug.Tested();
                                throw new Exception(SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS, new Exception(SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS));
                            }
                        }
                        else
                        {
                            // Main email address already verified
                            Debug.Tested();
                            throw new Exception(IdentityServiceLogicLayer.ERROR_EMAIL_ALREADY_VERIFIED, new Exception(IdentityServiceLogicLayer.EMAIL_ALREADY_VERIFIED));
                        }
                    }
                }
                else
                {
                    // User does not exist (may have been closed)
                    Debug.Tested();
                    throw new Exception(SharedLogicLayer.ERROR_INVALID_LINK_USER, new Exception(SharedLogicLayer.ERROR_INVALID_LINK_USER));
                }
            }
            else
            {
                Debug.Tested();
                throw new Exception(SharedLogicLayer.ERROR_INVALID_LINK, new Exception(SharedLogicLayer.ERROR_INVALID_LINK));
            }
        }
コード例 #25
0
        /**
         * Set user password after reset.
         */
        public static async Task SetUserPasswordAfterReset(AmazonDynamoDBClient dbClient, SetUserPasswordAfterResetRequest setUserPasswordAfterResetRequest)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(setUserPasswordAfterResetRequest);
            Debug.AssertString(setUserPasswordAfterResetRequest.resetPasswordLinkId);
            Debug.AssertEmail(setUserPasswordAfterResetRequest.emailAddress);
            Debug.AssertPassword(setUserPasswordAfterResetRequest.newPassword);

            // Find the valid link
            Link link = await IdentityServiceLogicLayer.FindValidLink(dbClient, setUserPasswordAfterResetRequest.resetPasswordLinkId, IdentityServiceLogicLayer.LINK_TYPE_RESET_PASSWORD);

            Debug.AssertValidOrNull(link);
            if (link != null)
            {
                // Valid link exists
                Debug.Tested();
                Debug.AssertID(link.UserID);

                // Load the user
                User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, link.UserID, true);

                Debug.AssertValidOrNull(user);
                if (user != null)
                {
                    Debug.Tested();
                    Debug.AssertEmail(user.EmailAddress);
                    if (user.EmailAddress == setUserPasswordAfterResetRequest.emailAddress)
                    {
                        // Email address matches user's email address
                        Debug.Tested();

                        // Make changes
                        user.PasswordHash = Helper.Hash(setUserPasswordAfterResetRequest.newPassword);
                        user.Locked       = false;

                        // Save the user
                        await IdentityServiceDataLayer.SaveUser(dbClient, user);

                        // Revoke link
                        link.Revoked = true;
                        //??++SAVE LINK
                    }
                    else
                    {
                        Debug.Tested();
                        throw new Exception(SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS, new Exception(SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS));
                    }
                }
                else
                {
                    // User does not exist - may have been closed (and possibly subsequently deleted).
                    Debug.Tested();
                    throw new Exception(SharedLogicLayer.ERROR_INVALID_LINK_USER, new Exception(SharedLogicLayer.ERROR_INVALID_LINK_USER));
                }
            }
            else
            {
                Debug.Tested();
                throw new Exception(SharedLogicLayer.ERROR_INVALID_LINK, new Exception(SharedLogicLayer.ERROR_INVALID_LINK));
            }
        }
コード例 #26
0
        /**
         * Login.
         * Returns an access token if successful, along with the access token's expiry time.
         */
        public static async Task <Tuple <string, DateTime> > Login(AmazonDynamoDBClient dbClient, LoginRequest loginRequest)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(loginRequest);
            Debug.AssertEmail(loginRequest.emailAddress);
            Debug.AssertString(loginRequest.password);

            // Find user with email and password hash
            //??--User user = IdentityServiceLogicLayer.Users.Find(u => (u.EmailAddress == loginRequest.emailAddress));
            User user = await IdentityServiceDataLayer.FindUserByEmailAddress(dbClient, loginRequest.emailAddress);

            Debug.AssertValidOrNull(user);
            if (user != null)
            {
                // User found with specified email address
                Debug.Tested();
                Debug.AssertID(user.ID);
                if (user.Closed != null)
                {
                    Debug.Tested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_USER_ACCOUNT_CLOSED);
                }
                else if (user.Blocked)
                {
                    Debug.Tested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_USER_BLOCKED);
                }
                else if (user.Locked)
                {
                    Debug.Tested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_USER_LOCKED);
                }
                else
                {
                    // User is not closed, blocked or locked.
                    Debug.Tested();
                    if (user.PasswordHash == Helper.Hash(loginRequest.password))
                    {
                        // Correct password - log the user in.
                        Debug.Tested();
                        // Invalidate any existing access tokens
                        await IdentityServiceLogicLayer.InvalidateUserAccessTokens(dbClient, user.ID);

                        // Set the last login time to now
                        user.LastLoggedIn = DateTime.Now;
                        // Mark failed login attempts as zero
                        user.FailedLoginAttempts = 0;

                        // Save the user
                        await IdentityServiceDataLayer.SaveUser(dbClient, user);

                        // Create a new access token
                        //??--Int64 accessTokenLifetime = (Int64)GetIdentityGlobalSetting(GLOBAL_SETTING_ACCESS_TOKEN_LIFETIME, DEFAULT_ACCESS_TOKEN_LIFETIME);
                        Int64 accessTokenLifetime = await IdentityServiceLogicLayer.GetInt64IdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_ACCESS_TOKEN_LIFETIME, IdentityServiceLogicLayer.DEFAULT_ACCESS_TOKEN_LIFETIME);

                        AccessToken accessToken = new AccessToken()
                        {
                            ID      = RandomHelper.Next().ToString(),
                            UserID  = user.ID,
                            Expires = DateTime.Now.AddSeconds(accessTokenLifetime)
                        };
                        // Setup the access token max expiry time
                        //??--Int64 maxUserLoginTime = (Int64)GetIdentityGlobalSetting(GLOBAL_SETTING_MAX_USER_LOGIN_TIME, DEFAULT_MAX_USER_LOGIN_TIME);
                        Int64 maxUserLoginTime = await IdentityServiceLogicLayer.GetInt64IdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_MAX_USER_LOGIN_TIME, IdentityServiceLogicLayer.DEFAULT_MAX_USER_LOGIN_TIME);

                        if ((user.MaxTimeLoggedIn == null) || (user.MaxTimeLoggedIn == 0))
                        {
                            Debug.Tested();
                            if (maxUserLoginTime != 0)
                            {
                                Debug.Tested();
                                accessToken.MaxExpiry = DateTime.Now.AddMinutes((UInt64)maxUserLoginTime);
                            }
                            else
                            {
                                Debug.Tested();
                            }
                        }
                        else
                        {
                            Debug.Tested();
                            if (maxUserLoginTime != 0)
                            {
                                Debug.Untested();
                                UInt64 maxUserLoginTime_ = Math.Min((UInt64)maxUserLoginTime, (UInt64)user.MaxTimeLoggedIn);
                                accessToken.MaxExpiry = DateTime.Now.AddMinutes(maxUserLoginTime_);
                            }
                            else
                            {
                                Debug.Tested();
                                accessToken.MaxExpiry = DateTime.Now.AddMinutes((UInt64)user.MaxTimeLoggedIn);
                            }
                        }
                        // Ensure the max expiry has not been exceeded
                        if ((accessToken.MaxExpiry != null) && (accessToken.Expires > accessToken.MaxExpiry))
                        {
                            Debug.Untested();
                            accessToken.Expires = (DateTime)accessToken.MaxExpiry;
                        }
                        else
                        {
                            Debug.Tested();
                        }
                        // Add the access token
                        //??--AccessTokens.Add(accessToken.ID, accessToken);
                        await IdentityServiceDataLayer.AddAccessToken(dbClient, accessToken);

                        // Return the access token ID and expiry date/time
                        //??--expiryTime = accessToken.Expires;
                        return(new Tuple <string, DateTime>(accessToken.ID, (DateTime)accessToken.Expires));
                    }
                    else
                    {
                        // Incorrect password
                        Debug.Tested();
                        //??--Int16 maxLoginAttempts = (Int16)GetIdentityGlobalSetting(GLOBAL_SETTING_LOCK_ON_FAILED_LOGIN_ATTEMPTS, DEFAULT_MAX_LOGIN_ATTEMPTS);
                        Int64 maxLoginAttempts = await IdentityServiceLogicLayer.GetInt64IdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_LOCK_ON_FAILED_LOGIN_ATTEMPTS, IdentityServiceLogicLayer.DEFAULT_MAX_LOGIN_ATTEMPTS);

                        if (++user.FailedLoginAttempts == maxLoginAttempts)
                        {
                            // Too many password attempts - user locked.
                            Debug.Tested();
                            user.Locked = true;

                            // Save the user
                            await IdentityServiceDataLayer.SaveUser(dbClient, user);

                            throw new Exception(IdentityServiceLogicLayer.ERROR_USER_LOCKED);
                        }
                        else
                        {
                            Debug.Tested();
                            throw new Exception(IdentityServiceLogicLayer.ERROR_INCORRECT_PASSWORD);
                        }
                    }
                }
            }
            else
            {
                Debug.Tested();
                throw new Exception(SharedLogicLayer.ERROR_UNRECOGNIZED_EMAIL_ADDRESS);
            }
        }
コード例 #27
0
        /**
         * Set user email.
         * If email is already in use then throw an exception.
         */
        public static async Task SetUserEmail(AmazonDynamoDBClient dbClient, string userId, SetUserEmailRequest setUserEmailRequest)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(userId);
            Debug.AssertValid(setUserEmailRequest);
            Debug.AssertEmail(setUserEmailRequest.emailAddress);

            // Check that the specified email address is not already in use.
            User user = await IdentityServiceLogicLayer.FindUserByEmailAddressOrNewEmailAddress(dbClient, setUserEmailRequest.emailAddress);

            Debug.AssertValidOrNull(user);
            if (user != null)
            {
                Debug.Untested();
                if (user.ID != userId)
                {
                    Debug.Untested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_EMAIL_IN_USE);
                }
            }
            //??-- foreach (var user_ in Users) {
            //     Debug.Tested();
            //     Debug.AssertValid(user_);
            //     if (user_.Deleted == null) {
            //         if (user_.ID != userId) {
            //             Debug.Tested();
            //             if ((user_.EmailAddress == setUserEmailRequest.emailAddress) ||
            //                 (user_.NewEmailAddress == setUserEmailRequest.emailAddress)) {
            //                     Debug.Tested();
            //                 throw new Exception(ERROR_EMAIL_IN_USE);
            //             } else {
            //                 Debug.Tested();
            //             }
            //         } else {
            //             Debug.Tested();
            //         }
            //     } else {
            //         Debug.Untested();
            //     }
            // }
            else
            {
                Debug.Untested();

                // Load the user
                user = await IdentityServiceLogicLayer.FindUserByID(dbClient, userId, true);

                Debug.AssertValidOrNull(user);
            }
            if (user != null)
            {
                // User exists (not closed and not soft deleted)
                Debug.Tested();
                Debug.AssertNull(user.Closed);
                Debug.AssertNull(user.Deleted);
                if (user.NewEmailAddress == null)
                {
                    // The user's email address is not already being changed.
                    Debug.Tested();
                    if (user.EmailAddress != setUserEmailRequest.emailAddress)
                    {
                        // The email address being changed to is different from the existing one.
                        Debug.Tested();
                        user.NewEmailAddress = setUserEmailRequest.emailAddress;

                        // Save the user
                        await IdentityServiceDataLayer.SaveUser(dbClient, user);

                        // Send the validate link.
                        Link link = await IdentityServiceLogicLayer.CreateLink(dbClient, IdentityServiceLogicLayer.LINK_TYPE_VERIFY_EMAIL_ADDRESS, user.ID);

                        Debug.AssertValid(link);
                        Debug.AssertString(link.ID);
                        //??++SEND VERIFICATION EMAIL?
                        //??--IdentityServiceLogicLayer.VerifyEmailLinkId = link.ID;
                        LoggingHelper.LogMessage($"EMAIL VERIFICATION LINK ID: {link.ID}");
                    }
                    else
                    {
                        // The email address being changed to is the same as the existing one.
                        Debug.Tested();
                    }
                }
                else if (user.NewEmailAddress != setUserEmailRequest.emailAddress)
                {
                    // The user's email address is already being changed but to a different address than the specified value.
                    Debug.Tested();
                    throw new Exception(IdentityServiceLogicLayer.ERROR_EMAIL_ALREADY_BEING_CHANGED);
                }
                else
                {
                    // The user's email address is already being changed to the specified value.
                    Debug.Tested();
                }
            }
            else
            {
                // User does not exist (or is closed or soft deleted)
                Debug.Tested();
                throw new Exception(IdentityServiceLogicLayer.ERROR_USER_NOT_FOUND);
            }
        }
        /**
         * Creates an account.
         */
        public static async Task <Tuple <User, bool> > CreateAccount(AmazonDynamoDBClient dbClient, CreateAccountRequest createAccountRequest)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(createAccountRequest);
            //??--Debug.AssertValid(IdentityServiceLogicLayer.Users);

            // Is there an existing user?
            User user = await IdentityServiceLogicLayer.FindUserByEmailAddressOrNewEmailAddress(dbClient, createAccountRequest.emailAddress);

            //??--User user = IdentityServiceLogicLayer.Users.Find(u => ((u.EmailAddress == createAccountRequest.emailAddress) || (u.NewEmailAddress == createAccountRequest.emailAddress)));
            Debug.AssertValidOrNull(user);
            bool bReOpened = false;

            if (user == null)
            {
                // No user exists with the supplied email address.
                // Create a new user
                user = new User()
                {
                    ID           = RandomHelper.Next(),
                    EmailAddress = createAccountRequest.emailAddress,
                    PasswordHash = Helper.Hash(createAccountRequest.password)
                };
                SetupUserFromCreateAccountRequest(user, createAccountRequest);

                // Add the new user to the data store
                await IdentityServiceLogicLayer.AddUserCreatingSyndicate(dbClient, user);

                // Create an email verification link
                Link link = await IdentityServiceLogicLayer.CreateLink(dbClient, IdentityServiceLogicLayer.LINK_TYPE_VERIFY_EMAIL_ADDRESS, user.ID);

                Debug.AssertValid(link);
                Debug.AssertString(link.ID);
                //??--IdentityServiceLogicLayer.VerifyEmailLinkId = link.ID;

                // Send email verification email
                Dictionary <string, string> replacementFields = new Dictionary <string, string>();
                replacementFields["link"] = link.ID;
                EmailHelper.EmailTemplate(EmailHelper.EMAIL_TEMPLATE_CREATE_ACCOUNT, createAccountRequest.emailAddress, replacementFields);

                // Indicate that a new user was created.
                bReOpened = false;
            }
            else
            {
                // A user already exists with the supplied email address.
                if (user.Closed != null)
                {
                    // Account is closed so possibly re-open.
                    //??--if ((bool)GetIdentityGlobalSetting(GLOBAL_SETTING_USERS_CAN_REOPEN_ACCOUNT, true))
                    if (await IdentityServiceLogicLayer.GetBoolIdentityGlobalSetting(dbClient, IdentityServiceLogicLayer.GLOBAL_SETTING_USERS_CAN_REOPEN_ACCOUNT, true))
                    {
                        // Accounts allowed to be re-opened
                        user.Closed = null;

                        // Setup the user
                        SetupUserFromCreateAccountRequest(user, createAccountRequest);

                        // Save the user
                        await IdentityServiceDataLayer.SaveUser(dbClient, user);

                        // Send account re-opened email
                        Dictionary <string, string> replacementFields = new Dictionary <string, string>();
                        EmailHelper.EmailTemplate(EmailHelper.EMAIL_TEMPLATE_ACCOUNT_REOPENED, createAccountRequest.emailAddress, replacementFields);

                        // Indicate that an existing, closed, user was re-opened.
                        bReOpened = true;
                    }
                    else
                    {
                        // Accounts cannot be re-opened so throw an error.
                        throw new Exception(IdentityServiceLogicLayer.ERROR_USER_ACCOUNT_CLOSED);
                    }
                }
                else
                {
                    // Account is not closed so throw an error.
                    throw new Exception(IdentityServiceLogicLayer.ERROR_EMAIL_IN_USE);
                }
            }
            return(new Tuple <User, bool>(user, bReOpened));
        }
コード例 #29
0
        /**
         * Update user details.
         */
        internal static async Task UpdateUserDetails(AmazonDynamoDBClient dbClient, string userId, JObject requestBody)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(userId);
            Debug.AssertValid(requestBody);

            //??++Fail if email, EmailAddressVerified, NewEmailAddress, PasswordHash, LastLoggedIn, LastLoggedOut, IsAnonymised, ANEEOnTimestamp, ANEEOffTimestamp, TotalTicketsPurchased, TicketsPurchasedInCurrentGame, FailedLoginAttempts,
            //      KYCStatus, KCYTimestamp, MaxDailySpendingAmount etc.
            //      is specified as per specification
            //???What about Closed, Deleted
            User user = await IdentityServiceLogicLayer.FindUserByID(dbClient, userId);

            Debug.AssertValidOrNull(user);
            if (user != null)
            {
                Debug.Tested();
                if (requestBody["givenName"] != null)
                {
                    user.GivenName = (string)requestBody["givenName"];
                }
                if (requestBody["familyName"] != null)
                {
                    user.FamilyName = (string)requestBody["familyName"];
                }
                if (requestBody["preferredName"] != null)
                {
                    user.PreferredName = (string)requestBody["preferredName"];
                }
                if (requestBody["fullName"] != null)
                {
                    user.FullName = (string)requestBody["fullName"];
                }
                if (requestBody["blocked"] != null)
                {
                    user.Blocked = (bool)requestBody["blocked"];
                }
                if (requestBody["locked"] != null)
                {
                    user.Locked = (bool)requestBody["locked"];
                }
                if (requestBody["dateOfBirth"] != null)
                {
                    user.DateOfBirth = (DateTime)APIHelper.DateFromAPIDateString((string)requestBody["dateOfBirth"]);
                }
                if (requestBody["gender"] != null)
                {
                    user.Gender = (UInt16)requestBody["gender"];
                }
                if (requestBody["address1"] != null)
                {
                    user.Address1 = (string)requestBody["address1"];
                }
                if (requestBody["address2"] != null)
                {
                    user.Address2 = (string)requestBody["address2"];
                }
                if (requestBody["address3"] != null)
                {
                    user.Address3 = (string)requestBody["address3"];
                }
                if (requestBody["address4"] != null)
                {
                    user.Address4 = (string)requestBody["address4"];
                }
                if (requestBody["city"] != null)
                {
                    user.City = (string)requestBody["city"];
                }
                if (requestBody["region"] != null)
                {
                    user.Region = (string)requestBody["region"];
                }
                if (requestBody["country"] != null)
                {
                    user.Country = (string)requestBody["country"];
                }
                if (requestBody["postalCode"] != null)
                {
                    user.PostalCode = (string)requestBody["postalCode"];
                }
                if (requestBody["phoneNumber"] != null)
                {
                    user.PhoneNumber = (string)requestBody["phoneNumber"];
                }
                if (requestBody["allowNonEssentialEmails"] != null)
                {
                    user.AllowNonEssentialEmails = (bool)requestBody["allowNonEssentialEmails"];
                    //ANEEOnTimestamp, ANEEOffTimestamp
                }
                if (requestBody["preferredLanguage"] != null)
                {
                    user.PreferredLanguage = (string)requestBody["preferredLanguage"];
                }
                if (requestBody["preferredCurrency"] != null)
                {
                    user.PreferredCurrency = (string)requestBody["preferredCurrency"];
                }
                if (requestBody["preferredTimeZone"] != null)
                {
                    user.PreferredTimeZone = (string)requestBody["preferredTimeZone"];
                }
                //??++UPDATE THE DATABASE!!!
            }
            else
            {
                Debug.Tested();
                throw new Exception(IdentityServiceLogicLayer.ERROR_USER_NOT_FOUND);
            }
            //??? GetUserDetailsResponse retVal = new GetUserDetailsResponse() {
            //     emailAddress = user.EmailAddress,
            //     givenName = user.GivenName,
            //     familyName = user.FamilyName,
            //     preferredName = user.PreferredName,
            //     fullName = user.FullName,
            //     dateOfBirth = APIHelper.APIDateStringFromDate(user.DateOfBirth),
            //     gender = user.Gender,
            //     address1 = user.Address1,
            //     address2 = user.Address2,
            //     address3 = user.Address3,
            //     address4 = user.Address4,
            //     city = user.City,
            //     region = user.Region,
            //     country = user.Country,
            //     postalCode = user.PostalCode,
            //     phoneNumber = user.PhoneNumber,
            //     phoneNumberVerified = APIHelper.APIDateTimeStringFromDateTime(user.PhoneNumberVerified),
            //     newEmailAddress = user.NewEmailAddress,
            //     allowNonEssentialEmails = user.AllowNonEssentialEmails,
            //     totalTicketsPurchased = user.TotalTicketsPurchased,
            //     ticketsPurchasedInCurrentGame = user.TicketsPurchasedInCurrentGame,
            //     preferredLanguage = user.PreferredLanguage,
            //     preferredCurrency = user.PreferredCurrency,
            //     preferredTimeZone = user.PreferredTimeZone,
            //     maxDailySpendingAmount = user.MaxDailySpendingAmount,
            //     newMaxDailySpendingAmount = user.NewMaxDailySpendingAmount,
            //     newMaxDailySpendingAmountTime = APIHelper.APIDateTimeStringFromDateTime(user.NewMaxDailySpendingAmountTime),
            //     maxTimeLoggedIn = user.MaxTimeLoggedIn,
            //     newMaxTimeLoggedIn = user.NewMaxTimeLoggedIn,
            //     newMaxTimeLoggedInTime = APIHelper.APIDateTimeStringFromDateTime(user.NewMaxTimeLoggedInTime),
            //     excludeUntil = APIHelper.APIDateTimeStringFromDateTime(user.ExcludeUntil),
            //     newExcludeUntil = APIHelper.APIDateTimeStringFromDateTime(user.NewExcludeUntil),
            //     newExcludeUntilTime = APIHelper.APIDateTimeStringFromDateTime(user.NewExcludeUntilTime)
            // };
        }